0% found this document useful (0 votes)
23 views

ADB Week 5

Uploaded by

salmantalib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

ADB Week 5

Uploaded by

salmantalib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

University of Salford, MSc Data Science

Module: Advanced Databases


Date: Trimester 2, 2023-2024
Session: Workshop Week 5

Topic: Functions
Tools: Microsoft SQL Server
Authors: Dr Azadeh Mohammadi, Nathan Topping
Objectives:
In this workshop you will learn how to:

Use different built-in functions in T-SQL

Create and call user defined functions

Create and call stored procedures


ADB - Week 5 Workshop: Functions

Part 1: Built-in Functions in SQL Server


In this section, you will practice Built-in Functions in SQL Server
Search for ‘SQL Server Management Studio’ in the Windows search bar to open
SSMS.

You should then click on Connect on the next screen to connect to the SQL Server
(NB – the Server name will be specific to your device so won’t match the below).
1) For this exercise, switch to the AdventureWorksLT2019 database.
(If you don’t have it in your databases, download
AdventureWorksLT2019.bak from the blackboard and save it in
C:\Users\Public. Then in the SSMs, right click on the Databases node from
object explorer window and select restore database. Select Device and click …
button. Then click Add button and select AdventureWorksLT2019.bak from
the above path and click OK.)

2) Click the New Query button from the top menu. A new query window opens in
which you can write queries to create objects and query database objects.

Write a SELECT statement to return columns that contain:


a. Current date and time. Use the column alias as CurrentDateTime.
b. Current date. Use the column alias as CurrentDate.
c. Current time. Use the column alias as CurrentTime.
d. Current year. Use the column alias as CurrentYear.
e. Current month number. Use the column alias as CurrentMonth.
f. Current day of month number. Use the column alias as CurrentDay.
--Option 1
SELECT GETDATE() AS CurrentDateTime,
CONVERT (DATE,GETDATE()) AS CurrentDate,
CONVERT (TIME,GETDATE()) AS CurrentTime,
DATEPART (YEAR,GETDATE()) AS CurrentYear,
DATEPART (MONTH,GETDATE()) AS CurrentMonth,
DATEPART (DAY,GETDATE()) AS CurrentDay;
The DATEPART function returns a specific part of a date. The first
parameter can be any of the values listed in the table below.
Datepart Abbreviations
Year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
Day dd, d
week wk, ww
weekday dw, w
hour hh
minute mi, n
second ss, s
millisecond ms
microsecond mcs
nanosecond ns

--Option 2
SELECT GETDATE() AS CurrentDateTime,
CAST(GETDATE() AS DATE) AS CurrentDate,
CAST(GETDATE() AS TIME) AS CurrentTime,
YEAR(GETDATE()) AS CurrentYear,
MONTH(GETDATE()) AS CurrentMonth,
DAY(GETDATE()) AS CurrentDay

Functions for working with date and time:


You can use the DATEDIFF function to calculate the difference between any two
dates. The DATEDIFF function accepts three parameters; the first is the datepart
to identify whether you are counting the difference in terms of days, hours, minutes,
months etc. The last two parameters are the two dates you want to compare.

3) Return the difference between today and first of January 2024 in terms of year,
month, day.

SELECT DATEDIFF(YY, '2024-1-1', GETDATE()) AS ElapsedYear,


DATEDIFF(mm, '2024-1-1', GETDATE()) AS ElapsedMonths,
DATEDIFF(dd, '2024-1-1', GETDATE()) AS ElapsedDay
4) Below query returns the CustomerID, the current date, the product's OrderDate,
and the number of months between the OrderDate and today's date.
SELECT CustomerID, OrderDate, GETDATE() AS Today,
DATEDIFF(MONTH, OrderDate, GETDATE()) AS ElapsedMonths
FROM SalesLT.SalesOrderHeader

5) Write a SELECT statement against the SalesLT.SalesOrderHeader table and


retrieve the SalesOrderID, OrderDate and TotalDue columns. Filter the
results to include only orders placed in the last seven days.
SELECT SalesOrderID,OrderDate, TotalDue

FROM SalesLT.SalesOrderHeader

WHERE DATEDIFF(d,OrderDate,GETDATE())<=7;

6) Write a query that calculates the number of days between the date an order
was placed and the date that it was shipped using the
SalesLT.SalesOrderHeader table. Include the SalesOrderID,OrderDate,
and ShipDate columns.

SELECT SalesOrderID, OrderDate, ShipDate,


DATEDIFF(d,OrderDate,ShipDate) AS NumberOfDays
FROM SalesLT.SalesOrderHeader;

Displaying the Integer Representations for Parts of a Date:


You need to separate a date into different columns for year, month, and day. You
can use the DATEPART function to retrieve the datepart specified from a date as
an integer.
7) What does the following code do?
SELECT CustomerID, OrderDate,
DATEPART(YEAR, OrderDate) AS [Year], DATEPART(MONTH,
OrderDate) AS [Month], DATEPART(DAY, OrderDate) AS [Day] FROM

SalesLT.SalesOrderHeader
8) Write a query that displays the year of each order date and the numeric
month of each order date in separate columns in the results. Include the
SalesOrderID and OrderDate columns.

--Option 1
SELECT SalesOrderID, OrderDate, DATEPART(yyyy,OrderDate) AS OrderYear,
DATEPART(m,OrderDate) AS OrderMonth
FROM SalesLT.SalesOrderHeader;
--Option2
SELECT SalesOrderID, OrderDate, YEAR(OrderDate) AS OrderYear,
MONTH(OrderDate) AS OrderMonth
FROM SalesLT.SalesOrderHeader;

9) Write a query using the SalesLT.SalesOrderHeader table to display the


orders placed during 2004 by using a date function. Include the
SalesOrderID and OrderDate columns in the results.
SELECT SalesOrderID, OrderDate
FROM SalesLT.SalesOrderHeader WHERE YEAR(OrderDate) = 2004;

10) Write a query using the SalesLT.Customer table listing the Customer
details in order of the year the record was modified and then the month the
record was modified. Include the CustomerID,FirstName,LastName and
ModifiedDate columns in the results.

SELECT CustomerID,FirstName,LastName,ModifiedDate FROM SalesLT.Customer


ORDER BY YEAR(ModifiedDate),MONTH(ModifiedDate);
Displaying the String Value for Part of a Date:
You can use the DATENAME function to get the name of the datepart portion of
the date (i.e., return the name of the month and day of the week for a specific date).
The DATENAME function returns a character string representing the datepart
specified.

11) Easter 2024 is on March 31. What day of the week is it? What day of the year
is it?
SELECT DATEName(Weekday, '2024-03-31'), DATEPart(dy, '2024-03-31')
12) Replace dy by d in the above question and see the result. What is the difference
of day and dayofyear?

13) Change the query written in question 8 to display the month name instead
of month number

14) What does the following code do?


SELECT CustomerID, OrderDate, DATENAME(MONTH, OrderDate) AS
MonthName, DATENAME(WEEKDAY, OrderDate) AS WeekDayName
FROM SalesLT.SalesOrderHeader

15) Write a query that adds six months to each order date in the
SalesLT.SalesOrderHeader table. Include the SalesOrderID and OrderDate
columns.

SELECT SalesOrderID, OrderDate, DATEADD(m,6,OrderDate) Plus6Months


FROM SalesLT.SalesOrderHeader;

Functions for working with numbers:


ROUND function can be used to round a number value to a specific number of
decimal places.
16) What is the result of the following code?
SELECT ROUND(119.653,1), ROUND(119.653,2);

You can invoke ROUND with a negative argument to round to the left of the
decimal place. The following is an example that rounds product inventories to the
nearest 10 units and to the nearest 100 units:
17) What is the result of the following code?
SELECT
ROUND(119.653,0),
ROUND(119.653,-1),
ROUND(119.653,-2);
18) Write a query using the SalesLT.SalesOrderHeader table that displays the
SubTotal rounded to two decimal places. Include the SalesOrderID and
SubTotal columns in the results.
SELECT SalesOrderID,SubTotal, ROUND(SubTotal,2) AS SubTotal
FROM SalesLT.SalesOrderHeader;
19) Modify the previous query so that the SubTotal is rounded to the nearest
dollar.
SELECT SalesOrderID,SubTotal, ROUND(SubTotal,0) AS SubTotal
FROM SalesLT.SalesOrderHeader;

The RAND() function returns a random number between 0 (inclusive) and 1


(exclusive).
20) Write a statement that generates a decimal random number between 10 and
100.

SELECT RAND()*(100-10)+10;

21) Write a statement that generates an integer random number between 10 and
100.

--Option1
SELECT Floor(RAND()*(100-10)+10);

--Option2
SELECT cast(RAND()*(100-10)+10 as int)

Functions for working with Null Values:


The ISNULL() function is used to check if a value is null and if it is will return the
replacement value specified when calling the function. The syntax is:
ISNULL ( check_expression, replacement_value ). It is important to note that the
replacement value must be of a data type that is implicitly convertible to the same
type as the check expression. So, for example, if the column is an int data type, the
replacement value must be an integer and not characters.
22) Write a query using the SalesLT.Product table displaying the product ID, color,
and name columns. If the color column contains a NULL value, replace the
color with No Color.

SELECT ProductID, color, ISNULL(Color,'No Color') AS nColor, Name


FROM SalesLT.Product;

23) Write a query using the SalesLT.Product table displaying the product ID,
color, name columns and a description for each product that is displayed in the
“Name: Color” format. Make sure that all rows display a value even if the
Color value is missing. eg: "HL Road Frame - Black, 58: Black"
SELECT ProductID, Name, color, Name + ISNULL(': ' + Color,'') AS Description
FROM SalesLT.Product;

24) Modify the previous query to add No color to description for the products
that color is missing.

Functions for working with string data:


25) Write a query using the SalesLT.Product table displaying a description with
the “ProductID: Name” format. eg:"712: AWC Logo Cap" Hint: You will need
to use a function to write this query. Here are two possible answers:

--Option 1
SELECT CAST(ProductID AS VARCHAR) + ': ' + Name AS IDName
FROM SalesLT.Product;

--Option 2
SELECT CONVERT(VARCHAR, ProductID) + ': ' + Name AS IDName
FROM SalesLT.Product;

26) Write a query that displays the first 10 characters of the CompanyName column
in the SalesLT.Customer table. Here are two possible solutions:

--Option 1
SELECT LEFT(CompanyName,10) AS [Company Name] FROM
SalesLT.Customer;
--Option 2
SELECT SUBSTRING(CompanyName,1,10) AS [Company Name] FROM
SalesLT.Customer;

27) Write a query that displays characters 10 to 15 of the CompanyName column


in the SalesLT.Customer table.

SELECT companyname, SUBSTRING(CompanyName,10,6) AS


[Company Name 10-15]
FROM SalesLT.Customer;

28) Write a query displaying the first name and last name from the
SalesLT.Customer table all in uppercase.

SELECT UPPER(FirstName) AS FirstName, UPPER(LastName) AS LastName


FROM SalesLT.Customer;

29) Write a SELECT statement to return the FirstName, LastName and


EmailAddress from the SalesLT.Customer table. Filter the results to include
only the customers with FirstName longer than 10 characters.

SELECT FirstName, LastName, EmailAddress

FROM SalesLT.Customer

WHERE LEN(FirstName) > 10;

30) Write a SELECT statement to return the FirstName, LastName and


EmailAddress from the SalesLT.Customer table. Filter the results to include
only the customers with valid email address.
SELECT FirstName, LastName, EmailAddress

FROM SalesLT.Customer

WHERE EmailAddress LIKE '[a-z,0-9,_,-,.]%@[a-z,0-9,_,-]%.[a-z][a-z]%';

31) Check what the following instruction do?


SELECT FirstName, LastName, EmailAddress FROM

SalesLT.Customer

WHERE PATINDEX('%@%',EmailAddress)>2;
PATINDEX returns the starting position of the first occurrence of a pattern in a
specified expression, or zero if the pattern is not found. So the above query
returns the information of customer where we have @ in the email address and
there is at least 1 character before that.

Using aggregate functions:


Aggregate functions perform some form of aggregation of the data, for example, a
summation or count of the number of records within a query. Common aggregate
functions include COUNT, SUM, AVG, MIN and MAX.
32) Use an aggregate function to identify the total number of products in the
SalesLT.Product table

SELECT COUNT(*) AS TotalProducts FROM


SalesLT.Product;

33) Use an aggregate function to identify the average list price of products in the
SalesLT.Product table

SELECT AVG(ListPrice) As AveragePrice FROM


SalesLT.Product;

If we use the GROUP BY clause, we can group the results of an aggregate function.
This produces a single summary row for each group. All columns used in the
SELECT part of the query must appear in the GROUP BY clause, unless the column
is only used within an aggregate function.
34) Identify the number of products of each color in the SalesLT.Product table.
Sort the results from the color with the highest number of products to the
lowest.

SELECT Color, COUNT(*) AS ProductsInColor FROM


SalesLT.Product
GROUP BY Color
ORDER BY ProductsInColor DESC;
35) Amend the above query so that we only return the three colors within the
highest number of products in that color.
SELECT TOP 3 Color, COUNT(*) AS ProductsInColor FROM
SalesLT.Product
GROUP BY Color
ORDER BY ProductsInColor DESC;

36) The HAVING clause is designed to be used with the GROUP BY clause, and
can be used to restrict the groups that appear in the final table. Whereas the
WHERE clause filters the individual rows going into the results table,
HAVING filters the groups going into the final results table. Amend the above
query so that we only include colors which have more than 10 products of that
color.

SELECT Color, COUNT(*) AS ProductsInColor FROM


SalesLT.Product
GROUP BY Color
HAVING COUNT(*) > 10
ORDER BY ProductsInColor DESC;

Part 2: User defined functions and stored procedure


37) Create a user-defined function called dbo.fn_AddTwoNumbers that accepts
two integer parameters. Return the value that is the sum of the two numbers.
Test the function.

CREATE FUNCTION dbo.addTwoNumbers(@NumberOne


INT,@NumberTwo INT)
RETURNS INT
AS BEGIN
RETURN @NumberOne+@NumberTwo
END

We can execute a function with the SELECT statement or the EXEC statement.
For using EXEC statement we have to declare a variable in which we will
store the value returned by the function.

Select dbo.addTwoNumbers(1,3)

Or
BEGIN
DECLARE
@output int
EXEC @output=dbo.addTwoNumbers @Numberone=1,@Numbertwo=3
print(@output)
END

38) Create a user-defined function called dbo.fnTrim that takes a VARCHAR(250)


parameter. This function should trim off the spaces from both the beginning
and the end of the string. Test the function.

CREATE FUNCTION dbo.fnTrim(@Expression VARCHAR(250))


RETURNS VARCHAR(250)
AS BEGIN
RETURN LTRIM(RTRIM(@Expression))
END

Call the function by executing the below code:


Select dbo.fnTrim(' test ')

Or

BEGIN
DECLARE
@output varchar(250)
EXEC @output=dbo.fnTrim @expression=' test '
print(@output)
END

39) Create a stored procedure that returns the customers of a specified city

CREATE PROCEDURE SelectAllCustomers @name nvarchar(30)


AS
SELECT * FROM SalesLT.Customer WHERE Firstname = @name

Execute the above procedure:

EXEC SelectAllCustomers @name='John'

You might also like