SlideShare una empresa de Scribd logo
1 de 14
Database Development in SQL Server 2005
Lecture 2
Stored Procedures
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
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
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
…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
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
…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
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
…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’
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
…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
…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
…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
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}

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Sql Functions And Procedures
Sql Functions And ProceduresSql Functions And Procedures
Sql Functions And Procedures
 
PL SQL Quiz | PL SQL Examples
PL SQL Quiz |  PL SQL ExamplesPL SQL Quiz |  PL SQL Examples
PL SQL Quiz | PL SQL Examples
 
Procedure n functions
Procedure n functionsProcedure n functions
Procedure n functions
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
All About PL/SQL Collections
All About PL/SQL CollectionsAll About PL/SQL Collections
All About PL/SQL Collections
 
Plsql
PlsqlPlsql
Plsql
 
Oracle SQL, PL/SQL Performance tuning
Oracle SQL, PL/SQL Performance tuningOracle SQL, PL/SQL Performance tuning
Oracle SQL, PL/SQL Performance tuning
 
Packages - PL/SQL
Packages - PL/SQLPackages - PL/SQL
Packages - PL/SQL
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
PL/SQL Code for Sample Projects
PL/SQL Code for Sample ProjectsPL/SQL Code for Sample Projects
PL/SQL Code for Sample Projects
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
[Pgday.Seoul 2020] SQL Tuning
[Pgday.Seoul 2020] SQL Tuning[Pgday.Seoul 2020] SQL Tuning
[Pgday.Seoul 2020] SQL Tuning
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 
Mysql creating stored function
Mysql  creating stored function Mysql  creating stored function
Mysql creating stored function
 
JSON in Oracle 18c and 19c
JSON in Oracle 18c and 19cJSON in Oracle 18c and 19c
JSON in Oracle 18c and 19c
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
Oracle Index
Oracle IndexOracle Index
Oracle Index
 
Oracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step GuideOracle PLSQL Step By Step Guide
Oracle PLSQL Step By Step Guide
 

Destacado

Order by and join
Order by and joinOrder by and join
Order by and joinRiteshkiit
 
Sql server-integration-services-ssis-step-by-step-sample-chapters
Sql server-integration-services-ssis-step-by-step-sample-chaptersSql server-integration-services-ssis-step-by-step-sample-chapters
Sql server-integration-services-ssis-step-by-step-sample-chaptersNadinKa Karimou
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQLVikash Sharma
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slidesSmithss25
 
Best Practices - PHP and the Oracle Database
Best Practices - PHP and the Oracle DatabaseBest Practices - PHP and the Oracle Database
Best Practices - PHP and the Oracle DatabaseChristopher Jones
 
Good PowerPoint Design - for business presenters
Good PowerPoint Design - for business presentersGood PowerPoint Design - for business presenters
Good PowerPoint Design - for business presentersAlexander Osterwalder
 
Gva 13052015 smart media fokustransport&logistiek
Gva 13052015 smart media fokustransport&logistiekGva 13052015 smart media fokustransport&logistiek
Gva 13052015 smart media fokustransport&logistiekCombinant nv
 
教育部長
教育部長教育部長
教育部長family
 
Welcome to my power point
Welcome to my power pointWelcome to my power point
Welcome to my power pointsiata123
 

Destacado (17)

Order by and join
Order by and joinOrder by and join
Order by and join
 
Good sql server interview_questions
Good sql server interview_questionsGood sql server interview_questions
Good sql server interview_questions
 
SSIS Presentation
SSIS PresentationSSIS Presentation
SSIS Presentation
 
Sql server-integration-services-ssis-step-by-step-sample-chapters
Sql server-integration-services-ssis-step-by-step-sample-chaptersSql server-integration-services-ssis-step-by-step-sample-chapters
Sql server-integration-services-ssis-step-by-step-sample-chapters
 
Ajax Ppt 1
Ajax Ppt 1Ajax Ppt 1
Ajax Ppt 1
 
SSIS control flow
SSIS control flowSSIS control flow
SSIS control flow
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Best Practices - PHP and the Oracle Database
Best Practices - PHP and the Oracle DatabaseBest Practices - PHP and the Oracle Database
Best Practices - PHP and the Oracle Database
 
Good PowerPoint Design - for business presenters
Good PowerPoint Design - for business presentersGood PowerPoint Design - for business presenters
Good PowerPoint Design - for business presenters
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Gva 13052015 smart media fokustransport&logistiek
Gva 13052015 smart media fokustransport&logistiekGva 13052015 smart media fokustransport&logistiek
Gva 13052015 smart media fokustransport&logistiek
 
教育部長
教育部長教育部長
教育部長
 
Meeting minutes 8
Meeting minutes 8Meeting minutes 8
Meeting minutes 8
 
主日投影片
主日投影片主日投影片
主日投影片
 
Welcome to my power point
Welcome to my power pointWelcome to my power point
Welcome to my power point
 

Similar a Lecture 2. MS SQL. Stored procedures.

Similar a Lecture 2. MS SQL. Stored procedures. (20)

Stored procedure
Stored procedureStored procedure
Stored procedure
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
MS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And ProceduresMS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And Procedures
 
MS SQL SERVER: Sql Functions And Procedures
MS SQL SERVER: Sql Functions And ProceduresMS SQL SERVER: Sql Functions And Procedures
MS SQL SERVER: Sql Functions And Procedures
 
Erik_van_Roon.pdf
Erik_van_Roon.pdfErik_van_Roon.pdf
Erik_van_Roon.pdf
 
lecture13.ppt
lecture13.pptlecture13.ppt
lecture13.ppt
 
Introduction to PLSQL.PPT
Introduction to PLSQL.PPTIntroduction to PLSQL.PPT
Introduction to PLSQL.PPT
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
Assignment#08
Assignment#08Assignment#08
Assignment#08
 
Unit 3
Unit 3Unit 3
Unit 3
 
Simple ETL Solution - Marco Kiesewetter
Simple ETL Solution - Marco KiesewetterSimple ETL Solution - Marco Kiesewetter
Simple ETL Solution - Marco Kiesewetter
 
stored.ppt
stored.pptstored.ppt
stored.ppt
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
Module04
Module04Module04
Module04
 
Tips Tricks and Little known features in SAP ASE
Tips Tricks and Little known features in SAP ASETips Tricks and Little known features in SAP ASE
Tips Tricks and Little known features in SAP ASE
 
Dynamic websites lec3
Dynamic websites lec3Dynamic websites lec3
Dynamic websites lec3
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 

Más de Alexey Furmanov

Лекция 9. Основы HTML. Часть 2.
Лекция 9. Основы HTML. Часть 2.Лекция 9. Основы HTML. Часть 2.
Лекция 9. Основы HTML. Часть 2.Alexey Furmanov
 
Лекция 8. HTML основы. Часть 1.
Лекция 8. HTML основы. Часть 1.Лекция 8. HTML основы. Часть 1.
Лекция 8. HTML основы. Часть 1.Alexey Furmanov
 
Лекция 5. Поисковые системы.
Лекция 5. Поисковые системы.Лекция 5. Поисковые системы.
Лекция 5. Поисковые системы.Alexey Furmanov
 
Лекция 4. Почтовая система. Outlook.
Лекция 4. Почтовая система. Outlook.Лекция 4. Почтовая система. Outlook.
Лекция 4. Почтовая система. Outlook.Alexey Furmanov
 
Лекция 2. IP-адресация.
Лекция 2. IP-адресация.Лекция 2. IP-адресация.
Лекция 2. IP-адресация.Alexey Furmanov
 
Лекция 3. Браузеры (2009)
Лекция 3. Браузеры (2009)Лекция 3. Браузеры (2009)
Лекция 3. Браузеры (2009)Alexey Furmanov
 
Лекция 10. Основы CSS.
Лекция 10. Основы CSS.Лекция 10. Основы CSS.
Лекция 10. Основы CSS.Alexey Furmanov
 
Лекция 1. Модель OSI.
Лекция 1. Модель OSI.Лекция 1. Модель OSI.
Лекция 1. Модель OSI.Alexey Furmanov
 
Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Alexey Furmanov
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersAlexey Furmanov
 
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.Alexey Furmanov
 
Lecture 5. MS SQL. Transactions
Lecture 5. MS SQL. TransactionsLecture 5. MS SQL. Transactions
Lecture 5. MS SQL. TransactionsAlexey Furmanov
 

Más de Alexey Furmanov (12)

Лекция 9. Основы HTML. Часть 2.
Лекция 9. Основы HTML. Часть 2.Лекция 9. Основы HTML. Часть 2.
Лекция 9. Основы HTML. Часть 2.
 
Лекция 8. HTML основы. Часть 1.
Лекция 8. HTML основы. Часть 1.Лекция 8. HTML основы. Часть 1.
Лекция 8. HTML основы. Часть 1.
 
Лекция 5. Поисковые системы.
Лекция 5. Поисковые системы.Лекция 5. Поисковые системы.
Лекция 5. Поисковые системы.
 
Лекция 4. Почтовая система. Outlook.
Лекция 4. Почтовая система. Outlook.Лекция 4. Почтовая система. Outlook.
Лекция 4. Почтовая система. Outlook.
 
Лекция 2. IP-адресация.
Лекция 2. IP-адресация.Лекция 2. IP-адресация.
Лекция 2. IP-адресация.
 
Лекция 3. Браузеры (2009)
Лекция 3. Браузеры (2009)Лекция 3. Браузеры (2009)
Лекция 3. Браузеры (2009)
 
Лекция 10. Основы CSS.
Лекция 10. Основы CSS.Лекция 10. Основы CSS.
Лекция 10. Основы CSS.
 
Лекция 1. Модель OSI.
Лекция 1. Модель OSI.Лекция 1. Модель OSI.
Лекция 1. Модель OSI.
 
Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.Lecture 6. ADO.NET Overview.
Lecture 6. ADO.NET Overview.
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.Lecture 3. MS SQL. Cursors.
Lecture 3. MS SQL. Cursors.
 
Lecture 5. MS SQL. Transactions
Lecture 5. MS SQL. TransactionsLecture 5. MS SQL. Transactions
Lecture 5. MS SQL. Transactions
 

Último

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 

Último (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 

Lecture 2. MS SQL. Stored procedures.

  • 1. Database Development in SQL Server 2005 Lecture 2 Stored Procedures
  • 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}