Create stored procedures in T-SQL
In this lab, you’ll use T-SQL statements to create and understand stored procedure
techniques in the adventureworks database. For your reference, the following diagram
shows the tables in the database (you may need to resize the pane to see them clearly).
Create and execute stored procedures
1. Start Azure Data Studio.
2. From the Servers pane, double-click the AdventureWorks connection. A
green dot will appear when the connection is successful.
3. Right click on the AdventureWorks connection and select New Query. A new
query window is displayed with a connection to the AdventureWorks
database.
4. Type the following T-SQL code:
CodeCopy
CREATE PROCEDURE [Link] AS
SELECT TOP(10) name, listprice
FROM [Link]
GROUP BY name, listprice
ORDER BY listprice DESC;
5. Select ⏵Run. You’ve created a stored procedure named [Link].
6. In the query pane, type the following T-SQL code after the previous code:
CodeCopy
EXECUTE [Link];
7. Highlight the written T-SQL code and click ⏵Run. You’ve now executed the
stored procedure.
8. Now modify the stored procedure so that it returns only products from a
specific product category by adding an input parameter. In the query pane,
type the following T-SQL code:
CodeCopy
ALTER PROCEDURE [Link] @ProductCategoryID int
AS
SELECT TOP(10) name, listprice
FROM [Link]
WHERE ProductCategoryID = @ProductCategoryID
GROUP BY name, listprice
ORDER BY listprice DESC;
9. In the query pane, type the following T-SQL code:
CodeCopy
EXECUTE [Link] @ProductCategoryID = 18;
10. Highlight the written T-SQL code and click ⏵Run to execute the stored
procedure, passing the parameter value by name.
Challenge
1. Pass a value to the stored procedure by position instead of by name. Try
Product Category 41.
Challenge answer
CodeCopy
EXECUTE [Link] 41;
Create an inline table valued function
1. In the query pane, type the following T-SQL code:
CodeCopy
CREATE FUNCTION [Link]
(@orderyear AS INT) RETURNS TABLE
AS
RETURN
SELECT
customerid, SUM(freight) AS totalfreight
FROM [Link]
WHERE YEAR(orderdate) = @orderyear
GROUP BY customerid;
2. Highlight the written T-SQL code and click ⏵Run to create the table-valued
function.
Challenge
1. Run the table-valued function to return data for the year 2008.
Challenge answer
CodeCopy
SELECT * FROM [Link](2008)