ADB Week 5
ADB Week 5
Topic: Functions
Tools: Microsoft SQL Server
Authors: Dr Azadeh Mohammadi, Nathan Topping
Objectives:
In this workshop you will learn how to:
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.
--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
3) Return the difference between today and first of January 2024 in terms of year,
month, day.
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.
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;
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.
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
15) Write a query that adds six months to each order date in the
SalesLT.SalesOrderHeader table. Include the SalesOrderID and OrderDate
columns.
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;
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)
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.
--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;
28) Write a query displaying the first name and last name from the
SalesLT.Customer table all in uppercase.
FROM SalesLT.Customer
FROM SalesLT.Customer
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.
33) Use an aggregate function to identify the average list price of products in the
SalesLT.Product table
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.
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.
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
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