Lesson 2 - Programming in Advanced SQL - Practical
Lesson 2 - Programming in Advanced SQL - Practical
Lesson 2 - Practical
Programming in Advanced SQL
Adapted from: Modern Database Management 13th Edition
Learning Objectives
• Syntax:
Conditional Expressions – Part 2
Conditional Expressions-Part 3
WHILE LOOP • DECLARE @s_value INT;
• SET @s_value = 0;
Syntax •
WHILE condition • WHILE @s_value <= 10
BEGIN • BEGIN
•
{...statements...} PRINT 'Inside WHILE LOOP on
END; Prog.com';
• SET @s_value = @s_value + 1;
• END;
•
•PRINT 'Done WHILE LOOP on
Prog.com';
• GO
Triggers – Part 1
Triggers – Part 2
Triggers – Part 3
Triggers – Part 4
Procedures and Functions – Part 1
• Syntax:
•
Procedures and Functions – Part 2
•
Procedures and Functions – Part 3
• Procedures
(stored procedure with an output Parameter)
Create or Replace procedure sp_CountContacts_By_Title
@Title nvarchar(8), @TitleCount int= 0 output
//The keyword output marks it as an output parameter
As
select Contact.Title, Contact.FirstName, Contact.LastName
from Person.Contact
where Contact.Title = @Title
Select @TitleCount = count(*)
from Person.Contact
where Title=@Title
return @TitleCount
Procedures and Functions – Part 4
• Executing a Procedure
Declare @return_value int,
@TitleCount int
Execute
@return_value=sp_CountContacts_By_Title
@Title='Mr.',
@TitleCount=@TitleCount output
• Modifying a Procedure
ALTER procedure sp_Select_All_PersonContact
As
SELECT Contact.Title, Contact.FirstName,
Contact.LastName
FROM Person.Contact
ORDER BY Contact.LastName
Procedures and Functions – Part 7
• Execute sp_helptext
'sp_Select_All_PersonContact’
• You can use IF and ELSE • You can use CASE expression to
commands to control the flow compare the results of an
of commands. expression with a series of tests
IF <some condition> and return a result when the test
returns true.
then <some command>
SELECT JobTitle,
ELSE <some condition>
CASE Gender
then <some command>
WHEN ‘M’ THEN ‘Male’
• You can use loops to process
multiple records. WHEN ‘F’ THEN ‘Female’
DECLARE @cnt INT = 0; ELSE ‘Unknown Value’
WHILE @cnt <cnt_total END
BEGIN {… statements …}
SET @cnt = @cnt +1; END
Parameters – Part 1
create procedure getSalesperson @sp varchar(25)
as select SalesPerson, Mon, amount from SalesData where SalesPerson = @sp; Go
USE AdventureWorks2012; GO IF OBJECT_ID('Sales.uspGetSalesYTD', 'P') IS NOT NULL DROP PROCEDURE Sales.uspGetSalesYTD; GO CREATE PROCEDURE Sales.us
Parameters – Part 3
USE AdventureWorks2012;