SQL & Programming
Basics
Database Programming
Declarative & Procedural Languages
In a procedural language
You define the whole process
i.e. provide the step-by-step instruction on how to do something
In a Declarative Language
You just set the command and pass it on to the system
The system knows how to complete that order
SQL is a Declarative Language
You write a SQL statement, and
The DBMS comes up with an execution plan
2
Transact SQL
Most RDBMSs have a Procedural Language extensions
to the standard SQL
SQL Server - T-SQL
ORACLE - PL/SQL
T-SQL
Stands for Transact SQL
T-SQL = SQL + Procedural Programming Language
T-SQL extends SQL by adding constructs found in other
procedural languages, such as
Variables, data types and operators
Flow Control Structures
Procedures
Functions (user-defined and built-in), etc.
3
Batches
A batch is a grouping of T-SQL statements into one
logical unit
Batches are used when something has to happen either
before or after some other task in your script
All statements in a batch are compiled into one
execution plan
Batches are delimited by the GO statement
The GO statement
The GO statement must be on its own line
Is not a T-SQL command
It is a command recognized by the SQL Server command utilities
4
The Query Window – SQL Server
5
Batches (cont.)
All statements in the same batch
Are parsed together
Must pass a validation of the syntax as a unit
The statements in the batch are compiled into a single execution plan
Runtime errors may result in the partial execution of statements
in a batch
Summary
If a statement fails at parse-time (syntax error), then none of the
statements in the batch are executed.
If a statement fails at runtime, all statements in the batch before
the error happened have already run.
Each batch is processed independently
An error in one batch does not prevent another batch from running
6
Statements in a Batches
You cannot create and object (eg. a table) and use the
table in the same batch
If you want to combine any of these statements with
other statements in a single script
You will need to break them up by using GO statements
Exceptions
Some commands must be in their own batch:
Example
CREATE PROCEDURE
CREATE TRIGGER
CREATE VIEW
7
Scripts
A script is one or more SQL statement(s) stored in a
FILE
Scripts generally have a unified goal
All the statements within a script have one overall purpose
SQL scripts are stored as text files (.txt or .sql)
Scripts are usually treated as a unit
You normally execute the entire script
SQL script - Summary
a collection of SQL commands
Can include multiple batches
It is stored in a text file
All the statements in a script have one unified goal
8
Scripts (cont.)
Scripts are usually used for repetitive Tasks
Tasks that get executed over and over on a regular basis
Example: Backing up a database
Advantages of using a script
Ease of Use - The scripts can be saved and loaded when
needed.
Consistent Operation
The same task is performed in the same manner
The statements are tested and therefore they are free from errors
Scheduled Operation
Scripts can be scheduled to run at a time when it is convenient
Can be automated
9
Review
Procedural & Declarative programming languages
SQL and T-SQL
SQL and PL/SQL
Batch
GO statement
Script
10
Programming
in
T-SQL
Basic Symbols
End of statement [ ; ]
This is optional
Comments
Single line [ -- ]
Multi-line [ /*…*/ ]
String [ '…’ ]
12
Operators
Arithmetic Operators [ + , - , * , / , % ]
Comparison Operators
>, <, >=, <=, =, <> (or !=, which is the standard)
BETWEEN … AND …
IN (…)
LIKE, IS NULL
Logical Operators
AND
OR
NOT
EXISTS
Concatenation Operator [ + ]
13
Data Types
Data types used in scripts are the same as column data
types
Examples
VARCHAR(50)
INT
DECIMAL(6,2)
Other Data Types
TABLE
CURSOR
14
LOCAL Variables
The scope of a local variable is the current batch
Syntax:
DECLARE @<variable name> <variable type> [= <value>]
[, @<variable name> <variable type> [= <value>] ]]
Example
DECLARE @price decimal(4,1)
DECLARE @product varchar(50), @UnitPrice decimal(6,2)
A variable cannot be of text, ntext, or image data type
15
GLOBAL Variables
Global variables represent a special type of variable
Also referred as SYSTEM-DEFINED Functions
The server always maintains the values of these variables
Global variables represent
information specific to the server or
information on the current user session
Global variable names begin with a @@ prefix
You cannot declare global variables
You do not need to declare them
You simple READ what the system stores in the global variables
16
GLOBAL Variables - Examples
@@ERROR
Returns the error number for the last Transact-SQL statement
executed
@@IDENTITY
Returns the last-inserted identity value
@@ROWCOUNT
Returns the number of rows affected by the last statement
@@SERVERNAME
Returns the name of the local server that is running SQL Server
@@VERSION
Returns system and build information for the current installation
of SQL Server
17
Review
Variable Declaration
Local Variable
Global Variable
NEXT - Variable Assignment
18
Variables Assignment
The value of a variable will be NULL until it is initialized
Two ways to set the value in a variable
Use the SELECT or SET statement
Assignment Operator [ = ]
Compound assignment operator [ +=, *=, etc. ]
Example
Variable declaration and assignment
DECLARE @price decimal(4,1) = 9.9
Variable Assignment
SET @price = 12.50
Multiple Values
SET @price = 12.50 , @quantity = 12
19
Variables - Example
USE MyDB
GO
DECLARE @MyMsg VARCHAR(50)
SELECT @MyMsg = 'Hello, World.'
GO -- @MyMsg is not valid after this GO ends the batch.
PRINT @MyMsg
-- Error because @MyMsg not declared in this batch
GO
SELECT @@VERSION;
-- Error: Must be EXEC sp_who if not first statement
sp_who
GO
sp_who - Provides information about current users, sessions, and
processes
20
SELECT and SET
Use SET
When you are performing a simple assignment of a variable
Where the value is known (explicit value or from other variable)
Use SELECT
When you are basing the assignment of your variable on a
query
A SELECT statement that assigns a value to a variable must not
be combined with data-retrieval operations
Use Variables with Queries
DECLARE @product varchar(10) = ‘screw’
SELECT *
FROM Products
WHERE ProductName LIKE '%’ + @product + '%';
21
Example
DECLARE @product varchar(50)
, @UnitPrice decimal(6,2)
, @QntyPerUnit varchar(20)
DECLARE @proID int = 15;
SELECT @product = ProductName,
@QntyPerUnit = QuantityPerUnit,
@UnitPrice = UnitPrice
FROM Products
WHERE ProductID = @ proID
Print @product + ' is ‘ + convert(varchar(20)
, @UnitPrice) + ‘ BIRR per ‘ + @QntyPerUnit
22
Example - Using SET
1. SET @price = 9.9
2. SET @TotalCost = @UnitCost * 1.1
3. DECLARE @MaxSalary money;
SET @MaxSalary = ( SELECT MAX(Salary)
FROM Employee )
SELECT @MaxSalary = MAX(Salary)
FROM Employee
23
SELECT or SET - Examples
DECLARE @cat int=7
SELECT *
FROM Products
WHERE CategoryID = @cat
Assigning a value from a query
DECLARE @rows INT
SELECT @rows = COUNT(*) FROM Products
PRINT @rows
SET @rows = ( SELECT COUNT(*) FROM Products )
PRINT @rows
24
Table Data Type
DECLARE @MyTableVar table
(
FN varchar(50)
, LN varchar(50)
)
INSERT @MyTableVar (FN, LN)
SELECT FirstName , FatherName
FROM Student
SELECT FN, LN
FROM @MyTableVar
25
Table Data Type (cont.)
We can UPDATE records in our table variable as well as
DELETE records
UPDATE @ProductTotals
SET Revenue = Revenue * 1.15
WHERE ProductID = 62
Update data in the table variable
DELETE FROM @ProductTotals
WHERE ProductID = 60
26
Table Data Type (cont.)
Constraints can be used with table variables
DECLARE @MyTable TABLE
(
ProductID int UNIQUE,
Price money CHECK(Price < 10.0)
)
You can also declare primary keys, identity columns, and
default values
DECLARE @MyTable TABLE
(
ProductID int IDENTITY(1,1) PRIMARY KEY,
Name varchar(10) NOT NULL DEFAULT('Unknown')
)
27
Table Data Type (cont.)
The table definition of a table variable cannot change
after the DECLARE statement
If you are using a table variable in a join, you will need to
alias the table in order to execute the query
SELECT ProductName, Revenue
FROM Products P JOIN @ProductTotals PT
ON P.ProductID = PT.ProductID
28
Review : Main Topics
Declarative vs Procedural Programming
Batch
Script
Variable declaration
Scope of a variable
Global variable
Assignment statement
SET
SELECT
TABLE variable
29
Control-of-Flow
Statements
Database Programming
Overview
T-SQL has the following control of flow statement:
IF ... ELSE
WHILE
GOTO
RETURN
CASE Expression ( not a Control of Flow statement )
31
Conditional Statement (IF…ELSE)
Syntax
IF <Boolean Expression>
<SQL statement> | BEGIN <code series> END
[ ELSE
<SQL statement> | BEGIN <code series> END ]
The test condition can be any expression that return a
Boolean value
Basic structures
if …
if … else
if … else if … else
32
Conditional Statement (cont.)
The IF statement controls the conditional execution of
one ore more statements
An IF statement will execute only the very next
statement after it if a statement block is not used
Statements blocks
Created by using BEGIN … END
ALL or NONE of the statements in a block are executed
33
Conditional Statement (cont.)
Conditional execution of a statement
IF @myvar IS NULL
-- Do something
Checking existence of a table
IF NOT EXISTS ( SELECT T.name
FROM sys.tables T
WHERE T.name = 'Employee' )
-- CREATE the table 'Employee’
ELSE PRINT 'The table already exists’
34
The WHILE Statement
The WHILE statement tests a condition and executes
the statement(s) as long as the test condition is TRUE
The syntax:
WHILE <Boolean expression>
[ BEGIN
<statement block>
[BREAK]
<statement block>
[CONTINUE]
END ]
35
WHILE Statement - Example
DECLARE @counter int = 1
DECLARE @max int = 10
WHILE @counter <= @max
BEGIN
PRINT @counter
SET @counter = @counter + 1
END
36
BREAK and CONTINUE
The BREAK statement is a way of exiting the loop
without waiting for the bottom of the loop
The CONTINUE statement tells the WHILE loop to go
back to the beginning of the loop-control regardless of
where you are in the loop
you immediately go back to the top and re-evaluate the
expression (exiting if the expression is no longer TRUE)
37
WHILE Statement - Example
What is the result of the following loop?
WHILE (SELECT SUM(Salary) FROM Employee) < 150000
BEGIN
UPDATE Employee
SET Salary += 100
IF ( SELECT MIN(Salary) FROM Employee ) > 7000
BREAK
ELSE
CONTINUE
END
38
The GOTO Statement
Causes the flow of execution to a LABEL
The LABEL is an identifier followed by a colon
The statements that follow GOTO are skipped and
processing continues at the label
GOTO statements and labels can be used anywhere
within a procedure, batch, or statement block
The GOTO statements and the Label must be in the
same Batch
39
GOTO Statement - Example
DECLARE @Counter int;
SET @Counter = 1;
WHILE @Counter < 10
BEGIN
SELECT @Counter
SET @Counter = @Counter + 1
IF @Counter = 4 GOTO BranchOne --Jumps to the first branch.
IF @Counter = 5 GOTO BranchTwo --This will never execute.
END
BranchOne:
SELECT 'Jumping To Branch One.'
GOTO BranchThree; --This will prevent BranchTwo from executing.
BranchTwo:
SELECT 'Jumping To Branch Two.'
BranchThree:
SELECT 'Jumping To Branch Three.' 40
The RETURN Statement
Exits unconditionally from a query or procedure
RETURN can be used at any point to exit from a
procedure, batch, or statement block
Statements that follow RETURN are not executed
41
Exercise
Rewrite the following code using variables
WHILE (SELECT SUM(Salary) FROM Employee) < 150000
BEGIN
UPDATE Employee
SET Salary += 100
IF ( SELECT MIN(Salary) FROM Employee ) > 7000
BREAK
ELSE
CONTINUE
END
42
The CASE Expression
The CASE Expression evaluates several conditions and
return a single value
When two conditions evaluate to TRUE, only the first
condition is used
ELSE can be included as a default option
Two type of the CASE expression exist
The simple CASE expression
The Search CASE expression
43
The Simple CASE Expression
CASE …
WHEN … THEN …
WHEN … THEN …
END
A simple CASE expression
Needs a condition to be specified after the “CASE” keyword
The CASE block returns a value or expression
The return value can be used with other statements.
DECLARE @x int = 20
PRINT
CASE @x % 2
WHEN 0 THEN ‘EVEN number’
WHEN 1 THEN ‘ODD number’
END
44
Simple CASE Expression (cont.)
Example
DECLARE @x int = 20
PRINT
CASE @x % 2
WHEN 0 THEN ‘EVEN number’
WHEN 1 THEN ‘ODD number’
END
45
The Search CASE
Same as a simple CASE, except:
There is no input expression
Each of the WHEN expressions must evaluate to a Boolean
value
The ELSE can still be included as a default option
Note
You can use different expressions for each condition
Any expression that evaluates to a Boolean value can be used
46
The Search CASE (cont.)
Example
DECLARE @x int = 20
CASE
WHEN @x % 2 = 0 THEN ‘EVEN number’
WHEN @x % 2 = 1 THEN ‘ODD number’
END
47
Uses of CASE Expr
Replacing codes or abbreviation to more readable
values
Example
SELECT ProductName
, Status = CASE Discontinued
WHEN 0 THEN ‘Discontinued’
WHEN 1 THEN ‘Active’
END
FROM Products
ORDER BY Status
48
Uses of CASE Expr (cont.)
Example - Categorizing data
SELECT ProductName
, CASE
WHEN UnitPrice < 10 THEN ‘Cheap‘
WHEN UnitPrice BETWEEN 10 AND 20 THEN
‘Normal‘
ELSE ‘Expensive’
FROM Products
49
Use the following table definitions for the following questions
CREATE TABLE Department
(
DepID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
DepName varchar(50) NOT NULL,
City varchar(50) NOT NULL
(
GO
CREATE TABLE Employee
(
EmpID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
FName varchar(50) NOT NULL,
LName varchar(50) NULL,
EmptDate Date NOT NULL DEFAULT GetDate(),
dID int References Department(DepID)
(
50
Exercise
1. GetDate() is a built-in function that returns the current
date from the system.
1. Declare a variable and assign the value returned from GetDate()
into the variable.
2. Display the value stored in the variable that you declared
2. Write a SINGLE statement to change all the FName and
LName of the employees to upper case in the Employee
table.
3. Use a Table variable to store the full names of the
Employees along with their department names
51