2. Transact SQL Extensions
• There are some more T-SQL statements, called ‘SQL Extensions’
– These extensions can be used to develop stored procedures (scripts)
• Some stored procedures are written by users, others are provided
by SQL Server 2005 and are called ‘System Stored Procedures’
– Both kinds can be written in T-SQL or a CLR language such as C# or VB
• We have looked at most T-SQL statements found in DDL and DML
– A batch is a sequence of SQL statements and extensions
that are sent to SQL Server 2005 for execution as one
3. Statement Blocks
• Blocks allow the production of units with one or more SQL statements
– Each block starts with BEGIN and concludes with END statements
BEGIN
statement_one
statement_two
. . .
END
• Blocks can be placed inside an IF statement to allow the execution
of more than one statement, depending on a set boolean condition
4. IF Statement
• The T-SQL statement IF is the same in principle to any IF condition
– This statement executes one SQL statement (or more in a block) when
a particular boolean expression, which follows the keyword IF, is true
– An optional ELSE statement can be specified, in which case, a second
block will be executed when the particular boolean expression is false
5. …cont
• Count all the employees on project p1 and list them if there are three or less
IF (SELECT COUNT(*) FROM works_on WHERE project_no = ‘p1’
GROUP BY project_no) > 3
PRINT ‘the number of employees in the project p1 is 4 or more’
-- this block will run and the text above will be printed
ELSE
BEGIN
PRINT ‘the following employees work for project p1’
SELECT emp_lname
FROM employee INNER JOIN works_on
ON employee.emp_no = works_on.emp_no
WHERE project_no = ‘p1’
END
6. WHILE Statement
• The WHILE statement repetitively executes one or more T-SQL
statements over and over while a boolean expression is true
– A block in a WHILE statement may contain statements used to control
the execution of the other statements in the block, BREAK or CONTINUE
• BREAK halts execution and then drops out of the WHILE statement
• CONTINUE halts execution and then resumes the WHILE statement
7. …cont
• Increase the budget of all projects by 10% until the sum of all budgets is
more than 500,000 or until one of the project’s budget exceeds 250,000
WHILE (SELECT SUM(budget) FROM project) < 500000
BEGIN
UPDATE project SET budget = (budget * 1.1)
IF (SELECT MAX(budget) project) > 250000
BREAK
ELSE
CONTINUE
END
-- when run, all three projects are updated three times
8. Local Variables
• Local variables are an important extension to T-SQL
– They are used to store values of any data type in a batch
• Every local variable must be defined using the DECLARE statement
– The definition of each variable must contain it’s name and data type
– Variables are always referenced in a batch using the prefix @
• The assignment of a value to a local variable is performed with
– A special form of the SELECT statement or the SET statement
9. …cont
• Calculate the average project budget and if p1’s budget is below, increase it
DECLARE @avg MONEY, @extra MONEY
SET @extra = 15000
SELECT @avg = AVG(budget) FROM project
IF (SELECT budget FROM project WHERE project_no = ‘p1’) < @avg
BEGIN
UPDATE project
SET budget = budget + @avg WHERE project_no = ‘p1’
PRINT ‘budget for p1 increased by @extra’
-- this block will run and the text above will be printed
END
ELSE
PRINT ‘budget for p1 unchanged’
10. Stored Procedures
• A stored procedure is a special kind of batch written in T-SQL using
SQL statements and extensions which is then saved in the database
– Saving in the database server improves task performance and consistency
• SQL Server 2005 supports both stored and system procedures
– When a stored procedure is produced, an optional list of parameters can
be defined and the procedure accepts corresponding arguments
– Stored procedures can optionally return a value, which displays user
defined data or in the case of an exception, the exception message
• Stored procedures can be used to (amongst other tasks)
– Control access authorization
– Produce audit trails of database activity
– Separate T-SQL statements from client side applications
11. …cont
• Stored procedures are produced with the CREATE PROCEDURE as follows
CREATE PROCEDURE procedure_name
[({@param1} type1 [= default1] [OUTPUT])]
{[({ @param2} type2 [= default2] [OUTPUT])]} . . .
[WITH {RECOMPILE | ENCRYPTION | EXECUTE AS user_name}]
AS batch | EXTERNAL NAME method_name
• Increase the budgets of all projects for a user specified percentage value
CREATE PROCEDURE increase_budget (@percent INT = 5)
AS
UPDATE project SET budget = budget + budget * (@percent / 100)
• This procedure defines a default value which is used when
no argument is specified with the EXECUTE statement
12. …cont
• The EXECUTE statement executes an existing procedure, it has form
EXECUTE [@return_status =] procedure_name
{[@param1 = value | @param1 = @var1 [OUTPUT]] | DEFAULT} . . .
[WITH RECOMPILE]
• To increase all the project budgets by ten percent we can write
EXECUTE increase_budget 10
-- is semantically comparable to
EXECUTE increase_budget @percent = 10
13. …cont
• Count the projects in which a specified employee works, delete any rows
related to that employee and return the project count to the local variable
CREATE PROCEDURE delete_emp (@emp_no INT, @count INT OUTPUT)
AS
SELECT @count = COUNT(*) FROM works_on WHERE emp_no = @emp_no
DELETE FROM employee WHERE emp_no = @emp_no
DELETE FROM works_on WHERE emp_no = @emp_no
• This stored procedure can be executed as follows
DECLARE @quantity INT
EXECUTE delete_emp @emp_no = 28559, @count = @quantity OUTPUT
PRINT @quantity
• SQL Server 2005 supports ALTER or DROP PROCEDURE
14. Other Procedural Statements
• The procedural extensions to T-SQL also contain these statements
– The RETURN statement has the same functionality inside
a batch as the BREAK statement does inside WHILE
– The GOTO statement branches to a label which is
placed in front of a T-SQL statement inside a batch
– The RAISEERROR statement generates a user defined error message and
sets a system error flag, a user defined error number must be over 50000
– The WAITFOR statement defines either the time interval or a
specified time that the system has to wait before continuing
WAITFOR {DELAY time | TIME time | TIMEOUT time}