SlideShare ist ein Scribd-Unternehmen logo
1 von 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}

Weitere ähnliche Inhalte

Was ist angesagt?

Triggers in SQL | Edureka
Triggers in SQL | EdurekaTriggers in SQL | Edureka
Triggers in SQL | EdurekaEdureka!
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps Hitesh-Java
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...rehaniltifat
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arraysHassan Dar
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)Sabana Maharjan
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Languagepandey3045_bit
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaEdureka!
 
Dimensional model | | Fact Tables | | Types
Dimensional model | | Fact Tables | | TypesDimensional model | | Fact Tables | | Types
Dimensional model | | Fact Tables | | Typesumair saeed
 
String function in my sql
String function in my sqlString function in my sql
String function in my sqlknowledgemart
 
07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Developmentrehaniltifat
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexingMahabubur Rahaman
 

Was ist angesagt? (20)

Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
PL/SQL TRIGGERS
PL/SQL TRIGGERSPL/SQL TRIGGERS
PL/SQL TRIGGERS
 
Triggers in SQL | Edureka
Triggers in SQL | EdurekaTriggers in SQL | Edureka
Triggers in SQL | Edureka
 
Store procedures
Store proceduresStore procedures
Store procedures
 
Oracle Index
Oracle IndexOracle Index
Oracle Index
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
 
MySql:Introduction
MySql:IntroductionMySql:Introduction
MySql:Introduction
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
SQL Joins With Examples | Edureka
SQL Joins With Examples | EdurekaSQL Joins With Examples | Edureka
SQL Joins With Examples | Edureka
 
Dimensional model | | Fact Tables | | Types
Dimensional model | | Fact Tables | | TypesDimensional model | | Fact Tables | | Types
Dimensional model | | Fact Tables | | Types
 
String function in my sql
String function in my sqlString function in my sql
String function in my sql
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
Oracle: Procedures
Oracle: ProceduresOracle: Procedures
Oracle: Procedures
 
07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development07 Using Oracle-Supported Package in Application Development
07 Using Oracle-Supported Package in Application Development
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 
PLSQL
PLSQLPLSQL
PLSQL
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Kürzlich hochgeladen (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

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}