Professional Documents
Culture Documents
09 Ch9 SQLinServerEnvironment
09 Ch9 SQLinServerEnvironment
09 Ch9 SQLinServerEnvironment
TO
DATABASE
L E A R N B Y E X A M P L E S
SQL IN A SERVER
ENVIRONMENT
Objectives
installation
Three different, interacting functions
Web servers
Application servers
Database servers
Database
I2DB: SQL in Server Environment
Database Database
Server Server
Internet
Client Client
The Webserver Tier
tier
The processes can be in one or many machines
The database tier executes queries that are
requested from the application tier
I2DB: SQL in Server Environment
STORED PROCEDURES
Introduction
Procedure declaration
I2DB: SQL in Server Environment
The call-statement
The form of a procedure call is
I2DB: SQL in Server Environment
The return-statement
RETURN <expression>;
Some Simple Statement Forms in
PSM
Assignment Statements
SET <variable> = <expression>;
Statement groups
BEGIN … END;
Statement label
LABEL:
Branching Statements
<statement list>
Ends with keyword END IF ELSEIF <condition> THEN
used in PSM
Subqueries can be used in conditions, or in general, any
<statement list>
END LOOP;
It is possible to break out of the loop
LEAVE <loop label>;
Example
loop1: LOOP
...
LEAVE loop1;
...
END LOOP;
Other Loop Constructs
WHILE <condition> DO
I2DB: SQL in Server Environment
<statement list>
END WHILE;
EXIT
UNDO
Using PSM Functions and
Procedures
AS
sql_statement1
sql_statement2
Example 1:
I2DB: SQL in Server Environment
Example
I2DB: SQL in Server Environment
Example
Using Cursor in MS SQL Server
1. Declare cursor
DECLARE cursor_name CURSOR FOR SELECT Statement
I2DB: SQL in Server Environment
2. Open cursor
OPEN cursor_name
3. Loop and get values of each tuple in cursor with FETCH statement
FETCH NEXT | PRIOR | FIRST | LAST
FROM cursor_name INTO @var1, @var2
4. Using @@FETCH_STATUS to check fetch status. The 0 value mean
FETCH statement was successful.
5. CLOSE cursor_name
6. DEALLOCATE cursor_name
I2DB: SQL in Server Environment
Example
I2DB: SQL in Server Environment
Example
I2DB: SQL in Server Environment
Example
Advantages of using Stored
Procedure
Reuse of Code
Maintainability
Precompiled Execution
Improved Security