0% found this document useful (0 votes)
353 views9 pages

Module 7 Lab: Implementing Stored Procedures and Functions

This document provides instructions for creating and testing several stored procedures in SQL Server: 1. The GetDiscounts stored procedure is created to return discount information from the Sales.SpecialOffer table. 2. The GetDiscountsForCategory stored procedure is created to return discounts for a specified category. 3. The GetDiscountsForCategoryAndDate stored procedure returns discounts for a category between given start and end dates. 4. The AddDiscount stored procedure inserts a new discount into the Sales.SpecialOffer table and handles errors. Its execution context is later modified.

Uploaded by

kossuth atilla
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)
353 views9 pages

Module 7 Lab: Implementing Stored Procedures and Functions

This document provides instructions for creating and testing several stored procedures in SQL Server: 1. The GetDiscounts stored procedure is created to return discount information from the Sales.SpecialOffer table. 2. The GetDiscountsForCategory stored procedure is created to return discounts for a specified category. 3. The GetDiscountsForCategoryAndDate stored procedure returns discounts for a category between given start and end dates. 4. The AddDiscount stored procedure inserts a new discount into the Sales.SpecialOffer table and handles errors. Its execution context is later modified.

Uploaded by

kossuth atilla
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/ 9

Module 7 Lab: Implementing Stored Procedures and

Functions
Exercise 1: Creating Stored Procedures
Lab answer key

Creating and testing the GetDiscounts stored procedure.


You must perform the following steps to create and test the GetDiscounts stored
procedure:

1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and then click
SQL Server Management Studio.
2. In the Connect to Server dialog box, specify the values in the following table, and then click
Connect.
Property Value
Server type Database Engine
Server name MIAMI
Authentication Windows Authentication

3. On the File menu, point to Open, click Project/Solution, and then open the
AWProgrammability.ssmssln solution in D:\Labfiles\Starter.
4. If Solution Explorer is not visible, click Solution Explorer on the View menu.
5. In Solution Explorer, double-click the InitializeData.sql query file.
6. On the toolbar, click Execute, and then confirm that no errors occur.
7. In Solution Explorer, double-click the StoredProcedures.sql query file.
8. Select the Use AdventureWorks statement, and then on the toolbar, click Execute.
9. Locate the Create Sales.GetDiscounts comment, and then create the stored procedure, as
shown in the following Transact-SQL example.

CREATE PROCEDURE Sales.GetDiscounts


AS

SELECT Description,
DiscountPct,
Type,
Category,
StartDate,
EndDate,
MinQty,
MaxQty
FROM Sales.SpecialOffer
ORDER BY StartDate, EndDate
10. Select the CREATE PROCEDURE statement, and then on the toolbar, click Execute. Review
the query results, verifying that the statement executed successfully.
11. Locate the Test Sales.GetDiscounts comment, and then test the stored procedure, as shown
in the following Transact-SQL example.

EXEC Sales.GetDiscounts

12. Select the EXEC statement, and then on the toolbar, click Execute. In the query results,
verify that several rows are displayed.
13. On the File menu, click Save StoredProcedures.sql.
14. Keep the SQL Server Management Studio solution open. You will use it in the next
procedure.

Creating and testing the GetDiscountsForCategory stored procedure


You must perform the following steps to create and test the GetDiscountsForCategory
stored procedure:

1. Locate the Create Sales.GetDiscountsForCategory comment, and then create the stored
procedure, as shown in the following Transact-SQL example.

CREATE PROCEDURE Sales.GetDiscountsForCategory


@Category nvarchar(50)
AS

SELECT Description,
DiscountPct,
Type,
Category,
StartDate,
EndDate,
MinQty,
MaxQty
FROM Sales.SpecialOffer
WHERE Category = @Category
ORDER BY StartDate, EndDate
2. Select the CREATE PROCECURE statement, and then on the toolbar, click Execute. Review
the query results, verifying that the statement executed successfully.
3. Locate the Test Sales.GetDiscountsForCategory comment, and then test the stored
procedure, as shown in the following Transact-SQL example.

EXEC Sales.GetDiscountsForCategory 'Reseller'

4. Select the EXEC statement, and then on the toolbar, click Execute. In the query results,
verify that 13 rows are displayed.
5. On the File menu, click Save StoredProcedures.sql.
6. Keep the SQL Server Management Studio solution open. You will use it in the next
procedure.
Creating and testing the GetDiscountsForCategoryAndDate stored procedure
You must perform the following steps to create and test the
GetDiscountsForCategoryAndDate stored procedure:

1. Locate the Create Sales.GetDiscountsForCategoryAndDate comment, and then create the


stored procedure, as shown in the following Transact-SQL example.

CREATE PROCEDURE Sales.GetDiscountsForCategoryAndDate


@Category nvarchar(50),
@DateToCheck datetime = NULL
AS

IF (@DateToCheck IS NULL)
SET @DateToCheck = GetDate()

SELECT Description,
DiscountPct,
Type,
Category,
StartDate,
EndDate,
MinQty,
MaxQty
FROM Sales.SpecialOffer
WHERE Category = @Category
AND @DateToCheck BETWEEN StartDate AND EndDate
ORDER BY StartDate, EndDate

2. Select the CREATE PROCEDURE statement, and then on the toolbar, click Execute. Review
the query results, verifying that the statement executed successfully.
3. Locate the Test Sales.GetDiscountsForCategoryAndDate with category but no date
comment, and then test the stored procedure, as shown in the following Transact-SQL
example.

EXEC Sales.GetDiscountsForCategoryAndDate 'Reseller'

4. Select the EXEC statement, and then on the toolbar, click Execute. In the query results,
verify that six rows are displayed. This is the current list of discounts because the
@DateToCheck parameter defaults to the current date and time.
5. Locate the Test Sales.GetDiscountsForCategoryAndDate with both parameters comment,
and then test the stored procedure, as shown in the following Transact-SQL example.

DECLARE @DateToCheck datetime


SET @DateToCheck = DateAdd(month, 1, GetDate())
EXEC Sales.GetDiscountsForCategoryAndDate 'Reseller', @DateToCheck

6. Select the DECLARE, SET, and EXEC statements, and then on the toolbar, click Execute. In
the query results, verify that seven rows are displayed. This is the list of discounts that will be
current in one month’s time.
7. On the File menu, click Save StoredProcedures.sql.
8. Keep the SQL Server Management Studio solution open. You will use it in the next
procedure.

Creating and testing the AddDiscount stored procedure


You must perform the following steps to create and test the AddDiscount stored
procedure:

1. Locate the Create Sales.AddDiscount comment, and then create the stored procedure, as
shown in the following Transact-SQL example.

CREATE PROCEDURE Sales.AddDiscount


@Description nvarchar(255),
@DiscountPct smallmoney,
@Type nvarchar(50),
@Category nvarchar(50),
@StartDate datetime,
@EndDate datetime,
@MinQty int,
@MaxQty int,
@NewProductID int OUTPUT
AS

BEGIN TRY
INSERT Sales.SpecialOffer (Description, DiscountPct, Type, Category,
StartDate, EndDate, MinQty, MaxQty)
VALUES (@Description, @DiscountPct, @Type, @Category, @StartDate,
@EndDate, @MinQty, @MaxQty)

SET @NewProductID = SCOPE_IDENTITY()


RETURN 0
END TRY
BEGIN CATCH
INSERT dbo.ErrorLog
(UserName, ErrorNumber, ErrorSeverity,
ErrorState, ErrorProcedure, ErrorLine, ErrorMessage)
VALUES
(CONVERT(sysname, CURRENT_USER), ERROR_NUMBER(),
ERROR_SEVERITY(), ERROR_STATE(), ERROR_PROCEDURE(),
ERROR_LINE(), ERROR_MESSAGE() )

RETURN -1
END CATCH

2. Select the CREATE PROCEDURE statement, and then on the toolbar, click Execute. Review
the query results, verifying that the statement executed successfully.
3. Locate the Test Sales.AddDiscount comment, and then test the stored procedure, as shown
in the following Transact-SQL example.

DECLARE @StartDate datetime, @EndDate datetime


SET @StartDate = GetDate()
SET @EndDate = DateAdd(month, 1, @StartDate)

DECLARE @NewId int


EXEC Sales.AddDiscount
'Half price of everything',
0.5,
'Seasonal Discount',
'Customer',
@StartDate,
@EndDate,
0,
20,
@NewID OUTPUT

SELECT @NewID

4. Select the DECLARE, SET, and EXEC statements, and then on the toolbar, click Execute. In
the query results, a new SpecialOfferID is returned.
5. Under the Test Sales.AddDiscount with errors comment, modify the preceding test as
shown in the following Transact-SQL example.

DECLARE @StartDate datetime, @EndDate datetime


SET @StartDate = GetDate()
SET @EndDate = DateAdd(month, 1, @StartDate)

DECLARE @NewId int, @ReturnValue int


EXEC @ReturnValue = Sales.AddDiscount
'Half price of everything',
-0.5, -- UNACCEPTABLE VALUE
'Seasonal Discount',
'Customer',
@StartDate,
@EndDate,
0,
20,
@NewID OUTPUT

IF (@ReturnValue = 0)
SELECT @NewID
ELSE
SELECT TOP 1 * FROM dbo.ErrorLog ORDER BY ErrorTime DESC

6. Select the DECLARE, SET, and EXEC statements, and then on the toolbar, click Execute. In
the query results, confirm that an error record is displayed that includes the ErrorProcedure
value AddDiscount.
7. On the File menu, click Save StoredProcedures.sql.
8. Keep the SQL Server Management Studio solution open. You will use it in the next
procedure.

Modifying execution context of the AddDiscount stored procedure


You must perform the following steps to modify the execution context of the
AddDiscount stored procedure:

1. Locate the Create Sales.AddDiscount comment, and then select the entire CREATE
PROCEDURE batch. On the Edit menu, click Copy.
2. Locate the Alter Sales.AddDiscount with execution context comment, and then position the
insertion point after the comment. On the Edit menu, click Paste.
3. Modify the statement as shown in the following Transact-SQL example.

ALTER PROCEDURE Sales.AddDiscount -- ALTER NOT CREATE


@Description nvarchar(255),
@DiscountPct smallmoney,
@Type nvarchar(50),
@Category nvarchar(50),
@StartDate datetime,
@EndDate datetime,
@MinQty int,
@MaxQty int,
@NewProductID int OUTPUT
WITH EXECUTE AS 'Adam' -- EXECUTE AS
AS

-- DO NOT MODIFY REMAINDER OF FUNCTION

4. Select the ALTER PROCEDURE statement, and then on the toolbar, click Execute. Review
the query results, verifying that the statement executed successfully.
5. Locate the Test Sales.AddDiscount with errors and execution context comment, and then
test the stored procedure by using the previously created EXEC statement.
6. Select the DECLARE, SET, and EXEC statements, and then on the toolbar, click Execute. In
the query results, confirm that an error record is displayed that includes the ErrorProcedure
value AddDiscount. Notice that this time the UserName is Adam instead of dbo because of
the execution context.
7. On the File menu, click Save StoredProcedures.sql.
8. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
Exercise 2: Creating Functions
Lab answer key

Creating and testing the GetMaximumDiscountForCategory user-defined function


You must perform the following steps to create and test the
GetMaximumDiscountForCategory user-defined function.

1. In Solution Explorer, double-click the UserDefinedFunctions.sql query file.


2. Select the Use AdventureWorks statement, and then on the toolbar, click Execute.
3. Locate the Create Sales.GetMaximumDiscountForCategory comment, and then create the
user-defined function, as shown in the following Transact-SQL example.

CREATE FUNCTION Sales.GetMaximumDiscountForCategory


(@Category nvarchar(50))
RETURNS smallmoney
AS
BEGIN
DECLARE @Max smallmoney

SELECT @Max = MAX(DiscountPct)


FROM Sales.SpecialOffer
WHERE Category = @Category
AND GetDate() BETWEEN StartDate AND EndDate
GROUP BY Category

IF (@Max IS NULL)
SET @Max = 0

RETURN @Max
END

4. Select the CREATE FUNCTION statement, and then on the toolbar, click Execute. Review
the query results, verifying that the statement executed successfully.
5. Locate the Test Sales.GetMaximumDiscountForCategory comment, and then test the
function, as shown in the following Transact-SQL example.

SELECT Sales.GetMaximumDiscountForCategory('Reseller')

6. Select the query, and then on the toolbar, click Execute. In the query results, verify that a
discount value is returned.
7. On the File menu, click Save UserDefinedFunctions.sql.
8. Keep the SQL Server Management Studio solution open. You will use it in the next
procedure.
Creating and testing the GetDiscountsForDate user-defined function
You must perform the following steps to create and test the GetDiscountsForDate user-
defined function:

1. Locate the Create Sales.GetDiscountsForDate comment, and then create the user-defined
function, as shown in the following Transact-SQL example.

CREATE FUNCTION Sales.GetDiscountsForDate (@DateToCheck datetime)


RETURNS TABLE
AS
RETURN (
SELECT Description,
DiscountPct,
Type,
Category,
StartDate,
EndDate,
MinQty,
MaxQty
FROM Sales.SpecialOffer
WHERE @DateToCheck BETWEEN StartDate AND EndDate
)

2. Select the CREATE FUNCTION statement, and then on the toolbar, click Execute. Review
the query results, verifying that the statement executed successfully.
3. Locate the Test Sales.GetDiscountsForDate comment, and then test the function, as shown
in the following Transact-SQL example.

SELECT *
FROM Sales.GetDiscountsForDate(GetDate())
ORDER BY DiscountPct DESC

4. Select the query, and then on the toolbar, click Execute. In the query results, verify that some
rows are displayed.
5. On the File menu, click Save UserDefinedFunctions.sql.
6. Keep the SQL Server Management Studio solution open. You will use it in the next
procedure.
Creating and testing the GetDiscountedProducts user-defined function
You must perform the following steps to create and test the GetDiscountedProducts
user-defined function:

1. Locate the Create Sales.GetDiscountedProducts comment, and then create the user-defined
function, as shown in the following Transact-SQL example. Use the prewritten IF statement
to replace the comment COPY PROVIDED IF STATEMENT HERE.

CREATE FUNCTION Sales.GetDiscountedProducts


(@IncludeHistory bit)
RETURNS @tbl_products TABLE
(ProductID int,
Name nvarchar(50),
ListPrice money,
DiscountDescription nvarchar(255),
DiscountPercentage smallmoney,
DiscountAmount money,
DiscountedPrice money)
AS
BEGIN
-- COPY PROVIDED IF STATEMENT HERE
RETURN
END

2. Select the CREATE FUNCTION statement, and then on the toolbar, click Execute. Review
the query results, verifying that the statement executed successfully.
3. Locate the Test Sales.GetDiscountedProducts comment, and then test the function, as
shown in the following Transact-SQL example.

SELECT * FROM Sales.GetDiscountedProducts(0)


SELECT * FROM Sales.GetDiscountedProducts(1)

4. Select the queries, and then on the toolbar, click Execute. In the query results, view the
number of rows returned by each query.
5. On the File menu, click Save UserDefinedFunctions.sql.
6. Close SQL Server Management Studio.

You might also like