Advanced SQL- LAB 2
Subqueries,
DCL and TCL
Statements
Variables,
Selection,
and Iteration
Stored
Procedures
Tables and
Functions
Error
Handling
Using DDL Statements The Knowledge Academy
Advanced SQL – LAB 2
1. Overview.............................................................................................................................................................. 2
2. The Lab Contents ................................................................................................................................................. 2
3. Variables .............................................................................................................................................................. 3
3.1 Declaring Variables ............................................................................................................................................ 3
3.2 The OpenQuery Function ................................................................................................................................... 4
4. Conditions ............................................................................................................................................................ 4
4.1 Using If ............................................................................................................................................................... 4
4.2 Using If..Else ....................................................................................................................................................... 4
4.3 Nested If Else...................................................................................................................................................... 5
4.4 Using Case .......................................................................................................................................................... 6
4.4.1 Simple Use of CASE ..................................................................................................................................... 6
4.4.2 Providing Different Outputs with CASE....................................................................................................... 6
4.4.3 Using Case with AGGREGATE Functions ..................................................................................................... 7
5. LOOPS .................................................................................................................................................................. 7
5.1 Using the WHILE loop......................................................................................................................................... 7
6. Types & Rules ...................................................................................................................................................... 8
6.1 Creating a Simple Rule ....................................................................................................................................... 8
6.2 Creating a List Rule............................................................................................................................................. 9
6.3 Creating a Type .................................................................................................................................................. 9
6.4 Bind a Rule to a TYPE ......................................................................................................................................... 9
Page | 1
Using DDL Statements The Knowledge Academy
1. Overview
Lab 2 of Advanced SQL introduces the user to basic concepts of programming in the
SQL Server environment. This lab includes declaring variables, using loops, creating
rules etc.
2. The Lab Contents
Tasks
Variables
Conditions
Loops
Types
Rules
Page | 2
Using DDL Statements The Knowledge Academy
3. Variables
Variables form an integral part of programming in any language. The same is true for
programming in SQL Server also. SQL Server provides programming using procedures,
functions, triggers, and even anonymous blocks.
3.1 Declaring Variables
A variable is declared in a code block using the @ symbol and is followed by its data-
type, length, and default value (if any) as in the following code block
Declare @Country varchar (30) = 'A%'
Begin
Select * from Customer where Country Like @Country
End
Figure 1. Declaring Variables
Variables can also be used to store and use values in the code block that have been
fetched from the table’s columns.
Declare @Name varchar (30)
Begin
Select @Name=Customername from Customer where Customerid=5605
Set @Name= 'Customer Name:'+@Name
Print @Name
End
Figure 2. Storing Column Values in Variables
Page | 3
Using DDL Statements The Knowledge Academy
3.2 The OpenQuery Function
While writing such code, it is possible for the user to extract data using a query from a
linked server using the ROWSET functions as shown below
Select * from Openquery (LOCAL1,'Select * from ExampleDatabase.dbo].emp')
Figure 3. Using the Openquery Function
4. Conditions
While programming, it is required in a number of places to execute a piece of code only
if a condition is true. Conditions in a SQL Server Code Block are specified using the IF...
ELSE and the CASE constructs.
4.1 Using If
declare @Units numeric(15,0), @Amt numeric(18,0), @Amount numeric (18,0)
Begin
Select @Units=units_purchased, @Amt=Product_Amount from
order_details where OrderId=1011
Set @Amount = @Units * @Amt
If @Amount > 40000
Print 'Avail 5%Discount'
End
Figure 4. Using If
Try using a different orderid to check the results.
4.2 Using If...Else
Declare @Units numeric (15, 0), @Amt numeric (18, 0), @Amount numeric (18, 0)
Begin
Page | 4
Using DDL Statements The Knowledge Academy
Select @Units=units_purchased, @Amt=Product_Amount from
order_details where OrderId=1011
Set @Amount = @Units * @Amt
If @Amount > 10000
Print 'Avail 5%Discount'
Else
Print 'No Discount'
End
Figure 5. Using If.. Else
Try using a different orderid to check the results.
4.3 Nested If Else
Declare @Units numeric (15, 0), @Amt numeric (18, 0), @Amount numeric (18,0)
Begin
Select @Units=units_purchased, @Amt=Product_Amount from
order_details where OrderId=1011
Set @Amount = @Units * @Amt
If @Amount > 15000
Print 'Avail 5% Discount'
Else
Begin
If @Amount > 10000 and @Amount < 15000
Print 'Avail 2% Discount'
Else
Print 'No Discount'
Page | 5
Using DDL Statements The Knowledge Academy
End
End
Figure 6. Using Nested If.. Else
4.4 Using Case
CASE is used in a SQL statement to provide for the logic of IF … ELSE.
4.4.1 Simple Use of CASE
Select ProductName,"Availability"=
Case When Qty_Available = 0 Then 'N/A' Else 'Available'
End
From product
Figure 7. Simple Use of CASE
4.4.2 Adding multiple conditions to a CASE statement
Select ProductName, Price, "Range"=
CASE
WHEN Price = 0 Then 'Not For Sale'
WHEN Price < 3000 Then 'Rated Low'
WHEN Price > 3000 and Price < 4000 Then 'Rated Medium'
WHEN Price > 4000 Then 'Rated High'
End
From Product
Page | 6
Using DDL Statements The Knowledge Academy
Figure 8. Providing Different Options with CASE
4.4.3 Using Case with AGGREGATE Functions
Select ProductId, Count (*) as TimesSold, AvailDiscount =
Case
When Count (*) > 3 Then 'Discount'
Else
'No Discount'
End
From Order_Details Group By ProductId
Figure 9. CASE and AGGREGATE Functions
5. LOOPS
SQL Server uses only a single loop for performing iterations – the WHILE loop.
5.1 Using the WHILE loop
Declare
@PName varchar (30)
Begin
While (Select Avg (Price) from Product) < 8000
Begin
Page | 7
Using DDL Statements The Knowledge Academy
Select @PName=ProductName from Product where Price=
(Select max(Price) from Product)
Print 'Product '+@PName
Update Product
Set Price=Price+300 where Price < (Select Max(Price)
from Product)
End
End
Figure 10. Using the WHILE Loop
6. Types & Rules
It is possible to create USER DEFINED DATA-TYPES in SQL SERVER with the help of
TYPES and use them in a table. Further, SQL Server also allows the user to restrict data
entry for a user defined data type using Rules.
6.1 Creating a Simple Rule
Create a Rule which allows the user to enter a value between 2000 and 8000 only.
In the query window type the following code
Create Rule AllowedLimit
As
@Range >=2000 and @Range<8000
Page | 8
Using DDL Statements The Knowledge Academy
Figure 11.Creating a Simple Rule
6.2 Creating a List Rule
Create a Rule which allows the user to select from only a given list of cities.
In the query window type the following code
Create Rule ListCities
as
@City in ('New York', 'Perth',' Sydney', 'Wolverhampton', 'Johannesburg', 'Melbourne',
'Jalandhar')
Figure 12. Creating A List Based Rule
6.3 Creating a Type
A User can create his own type and relate it to a Rule as well
Create a Type based on bigint
CREATE TYPE [dbo].[PriceType] FROM [bigint] NOT NULL
CREATE TYPE [dbo].[MyCities] FROM [varchar](30) NOT NULL
6.4 Bind a Rule to a TYPE
To bind a Rule to a Type or a TYPE to a Rule use the sp_bind in-built stored procedure
sp_bindrule AllowedLimit, ‘PriceType’
AllowLimit: User Defined RULE
PriceType: User Defined Data-Type
Bind the Rule ListCities to the type MyCities
Page | 9
Using DDL Statements The Knowledge Academy
sp_bindrule ListCities, ‘MyCities’
Issue the following statement
Insert into Cust values (‘James’, 'London')
Figure 13S. Applying Rules
===================== End of Lab Session 2 =======================
Page | 10