Lecture 2. MS SQL. Stored procedures.


Published on

My lecture notes, composed from different open sources from Internet. If you have copyright claims just tell me to remove.

Published in: Technology
1 Comment
  • http://dbmanagement.info/Tutorials/SQL_Server.htm
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Lecture 2. MS SQL. Stored procedures.

  1. 1. Database Development in SQL Server 2005Lecture 2Stored Procedures
  2. 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 providedby 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 extensionsthat are sent to SQL Server 2005 for execution as one
  3. 3. Statement Blocks• Blocks allow the production of units with one or more SQL statements– Each block starts with BEGIN and concludes with END statementsBEGINstatement_onestatement_two. . .END• Blocks can be placed inside an IF statement to allow the executionof more than one statement, depending on a set boolean condition
  4. 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) whena particular boolean expression, which follows the keyword IF, is true– An optional ELSE statement can be specified, in which case, a secondblock will be executed when the particular boolean expression is false
  5. 5. …cont• Count all the employees on project p1 and list them if there are three or lessIF (SELECT COUNT(*) FROM works_on WHERE project_no = ‘p1’GROUP BY project_no) > 3PRINT ‘the number of employees in the project p1 is 4 or more’-- this block will run and the text above will be printedELSEBEGINPRINT ‘the following employees work for project p1’SELECT emp_lnameFROM employee INNER JOIN works_onON employee.emp_no = works_on.emp_noWHERE project_no = ‘p1’END
  6. 6. WHILE Statement• The WHILE statement repetitively executes one or more T-SQLstatements over and over while a boolean expression is true– A block in a WHILE statement may contain statements used to controlthe 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. 7. …cont• Increase the budget of all projects by 10% until the sum of all budgets ismore than 500,000 or until one of the project’s budget exceeds 250,000WHILE (SELECT SUM(budget) FROM project) < 500000BEGINUPDATE project SET budget = (budget * 1.1)IF (SELECT MAX(budget) project) > 250000BREAKELSECONTINUEEND-- when run, all three projects are updated three times
  8. 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. 9. …cont• Calculate the average project budget and if p1’s budget is below, increase itDECLARE @avg MONEY, @extra MONEYSET @extra = 15000SELECT @avg = AVG(budget) FROM projectIF (SELECT budget FROM project WHERE project_no = ‘p1’) < @avgBEGINUPDATE projectSET budget = budget + @avg WHERE project_no = ‘p1’PRINT ‘budget for p1 increased by @extra’-- this block will run and the text above will be printedENDELSEPRINT ‘budget for p1 unchanged’
  10. 10. Stored Procedures• A stored procedure is a special kind of batch written in T-SQL usingSQL 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 canbe defined and the procedure accepts corresponding arguments– Stored procedures can optionally return a value, which displays userdefined 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. 11. …cont• Stored procedures are produced with the CREATE PROCEDURE as followsCREATE 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 valueCREATE PROCEDURE increase_budget (@percent INT = 5)ASUPDATE project SET budget = budget + budget * (@percent / 100)• This procedure defines a default value which is used whenno argument is specified with the EXECUTE statement
  12. 12. …cont• The EXECUTE statement executes an existing procedure, it has formEXECUTE [@return_status =] procedure_name{[@param1 = value | @param1 = @var1 [OUTPUT]] | DEFAULT} . . .[WITH RECOMPILE]• To increase all the project budgets by ten percent we can writeEXECUTE increase_budget 10-- is semantically comparable toEXECUTE increase_budget @percent = 10
  13. 13. …cont• Count the projects in which a specified employee works, delete any rowsrelated to that employee and return the project count to the local variableCREATE PROCEDURE delete_emp (@emp_no INT, @count INT OUTPUT)ASSELECT @count = COUNT(*) FROM works_on WHERE emp_no = @emp_noDELETE FROM employee WHERE emp_no = @emp_noDELETE FROM works_on WHERE emp_no = @emp_no• This stored procedure can be executed as followsDECLARE @quantity INTEXECUTE delete_emp @emp_no = 28559, @count = @quantity OUTPUTPRINT @quantity• SQL Server 2005 supports ALTER or DROP PROCEDURE
  14. 14. Other Procedural Statements• The procedural extensions to T-SQL also contain these statements– The RETURN statement has the same functionality insidea batch as the BREAK statement does inside WHILE– The GOTO statement branches to a label which isplaced in front of a T-SQL statement inside a batch– The RAISEERROR statement generates a user defined error message andsets a system error flag, a user defined error number must be over 50000– The WAITFOR statement defines either the time interval or aspecified time that the system has to wait before continuingWAITFOR {DELAY time | TIME time | TIMEOUT time}