SlideShare uma empresa Scribd logo
1 de 19
Querying and Managing Data Using SQL Server 2005
Objectives


               In this session, you will learn to:
                  Implement stored procedures
                  Implement functions




    Ver. 1.0                        Session 13       Slide 1 of 19
Querying and Managing Data Using SQL Server 2005
Creating Stored Procedures


               Stored procedures:
                  Are created using the CREATE PROCEDURE statement
                  Are executed using the EXECUTE PROCEDURE statement
                  Syntax:
                   CREATE PROCEDURE proc_name
                   AS
                   BEGIN
                   sql_statement1
                   sql_statement2
                   END
               Let’s see how…




    Ver. 1.0                        Session 13                  Slide 2 of 19
Querying and Managing Data Using SQL Server 2005
Creating Stored Procedures (Contd.)


               Stored procedure:
                  Is modified using the ALTER PROCEDURE statement
                     Syntax:
                     ALTER PROCEDURE proc_name
                  Is deleted using the DROP PROCEDURE statement
                     Syntax:
                     DROP PROCEDURE proc_name
               Let’s see how…




    Ver. 1.0                       Session 13                       Slide 3 of 19
Querying and Managing Data Using SQL Server 2005
Just a minute


               Which command will you use to modify the procedure?




               Answer:
                  ALTER PROCEDURE




    Ver. 1.0                     Session 13                     Slide 4 of 19
Querying and Managing Data Using SQL Server 2005
Just a minute


               Which system-defined table stores the names of all the
               stored procedure?




               Answer:
                  sysobjects




    Ver. 1.0                     Session 13                       Slide 5 of 19
Querying and Managing Data Using SQL Server 2005
Creating Parameterized Stored Procedures


               Parameterized stored procedures:
                  Are used to pass values to the stored procedure during the run
                  time
                  Involve declaring variables and passing value to it, which is
                  defined as input parameter
               Let’s see how…




    Ver. 1.0                       Session 13                           Slide 6 of 19
Querying and Managing Data Using SQL Server 2005
Returning Values from Stored Procedures


               Stored procedure:
                  Can also return values as output
                  Uses the OUPUT keyword to specify the parameter as output
                  parameter
                  Syntax:
                   CREATE PROCEDURE procedure_name
                   [
                   {@parameter data_type}          [OUTPUT]
                   ]
                   AS
                   sql_statement [...n]
               Let’s see how…



    Ver. 1.0                       Session 13                        Slide 7 of 19
Querying and Managing Data Using SQL Server 2005
Calling a Procedure from Another Procedure


               Stored procedure:
                  Can use the values returned by a procedure inside another
                  procedure
                  That calls or executes another procedure is known as the
                  calling procedure
                  That is called or executed by the calling procedure is known as
                  the called procedure
               Let’s see how…




    Ver. 1.0                       Session 13                            Slide 8 of 19
Querying and Managing Data Using SQL Server 2005
Demo: Creating Stored Procedures


               Problem Statement:
                  You are a database developer of AdventureWorks, Inc. The
                  Human Resource department needs to revise the payment
                  details of the employees. You need to create a procedure that
                  obtains the percentage value by which you need to increase
                  the pay rate. In addition, you need to ensure that the pay is
                  revised for only those employees whose pay rate was not
                  revised in the last six months.




    Ver. 1.0                       Session 13                           Slide 9 of 19
Querying and Managing Data Using SQL Server 2005
Demo: Creating Stored Procedures (Contd.)


               Solution:
                  To solve the preceding problem, you need to perform the
                  following tasks:
                    1. Create a stored procedure.
                    2. Execute the stored procedure.
                    3. Verify the result.




    Ver. 1.0                         Session 13                        Slide 10 of 19
Querying and Managing Data Using SQL Server 2005
Creating UDFs


               Scalar functions include the following components:
                  Function name with optional schema/owner name
                  Input parameter name and data type
                  Options applicable to the input parameter
                  Return parameter data type and optional name
                  Options applicable to the return parameter
                  One or more T-SQL statements
               Scalar functions can be created by using the CREATE
               FUNCTION statement.




    Ver. 1.0                      Session 13                        Slide 11 of 19
Querying and Managing Data Using SQL Server 2005
Creating UDFs (Contd.)


                  Syntax:
                   CREATE FUNCTION [ schema_name. ] function_name
                   ( [ { @parameter_name [ AS ][ type_schema_name. ]
                     parameter_data_type
                   [ = default ] }
                   [ ,...n ]
                   ]
                   )
                   RETURNS return_data_type
                   [ WITH <function_option> [ ,...n ] ]
                   [ AS ]
                   BEGIN
                   function_body
                   RETURN scalar_expression
                   END
                   [ ; ]
               Let’s see how…

    Ver. 1.0                    Session 13                     Slide 12 of 19
Querying and Managing Data Using SQL Server 2005
Creating UDFs (Contd.)


               Table-valued functions:
                  Returns a table as an output, which can be derived as a part of
                  a SELECT statement
                  Uses the table data type to store the set of rows
                  Are of following two types:
                      Inline table-valued function
                      Multistatement table-valued function
               Let’s see how…




    Ver. 1.0                        Session 13                           Slide 13 of 19
Querying and Managing Data Using SQL Server 2005
Just a minute


               Which type of function returns a single value?




               Answer:
                   Scalar functions




    Ver. 1.0                          Session 13                Slide 14 of 19
Querying and Managing Data Using SQL Server 2005
Demo: Creating Functions


               Problem Statement:
                  As a database developer at AdventureWorks, Inc., you need to
                  create a function that accepts the employee ID of an employee
                  and returns the following details:
                   •   Employee ID
                   •   Name of the employee
                   •   Title of the employee
                   •   Number of other employees working under the employee
                  How will you create the function?




    Ver. 1.0                        Session 13                            Slide 15 of 19
Querying and Managing Data Using SQL Server 2005
Demo: Creating Functions (Contd.)


               Solution:
                   To solve the preceding problem, you need to perform the
                   following tasks:
                    1. Create a function.
                    2. Execute the function to verify the result.




    Ver. 1.0                          Session 13                       Slide 16 of 19
Querying and Managing Data Using SQL Server 2005
Summary


              In this session, you learned that:
                 A stored procedure is a collection of various T-SQL statements
                 that are stored under one name and are executed as a single
                 unit.
                 A stored procedure can be created using the CREATE
                 PROCEDURE statement.
                 A stored procedure allows you to declare parameters,
                 variables, and use T-SQL statements and programming logic.
                 A stored procedure provides better performance, security, and
                 accuracy, and reduces the network congestion.
                 A stored procedure is a collection of various T-SQL statements
                 that are stored under one name and are executed as a single
                 unit.
                 A stored procedure can be created using the CREATE
                 PROCEDURE statement.


   Ver. 1.0                       Session 13                           Slide 17 of 19
Querying and Managing Data Using SQL Server 2005
Summary (Contd.)


               A stored procedure allows you to declare parameters,
               variables, and use T-SQL statements and programming logic.
               A stored procedure provides better performance, security, and
               accuracy, and reduces the network congestion.
               A stored procedure accepts data through input parameters.
               A stored procedure returns data through the output parameters
               or return statements.
               A stored procedure can be executed by using the EXECUTE
               statement.
               A stored procedure can be altered by using the ALTER
               PROCEDURE statement.
               A user-defined function is a database object that contains a set
               of T-SQL statements.
               The user-defined functions can return either a single scalar
               value or a result set.

    Ver. 1.0                     Session 13                           Slide 18 of 19
Querying and Managing Data Using SQL Server 2005
Summary (Contd.)


               UDFs are of two types: scalar functions and table-valued
               functions.
               A scalar function accepts a single value and returns a single
               value.
               A table-valued function returns a table as an output, which can
               be derived as a part of a SELECT statement.




    Ver. 1.0                    Session 13                            Slide 19 of 19

Mais conteúdo relacionado

Destaque

Destaque (6)

Informe 720
Informe 720Informe 720
Informe 720
 
Third eye designers
Third eye designersThird eye designers
Third eye designers
 
Comunicato 30
Comunicato 30Comunicato 30
Comunicato 30
 
Sunscreen
SunscreenSunscreen
Sunscreen
 
06 qmds2005 session08
06 qmds2005 session0806 qmds2005 session08
06 qmds2005 session08
 
04 qmds2005 session05
04 qmds2005 session0504 qmds2005 session05
04 qmds2005 session05
 

Semelhante a 09 qmds2005 session13

10 qmds2005 session14
10 qmds2005 session1410 qmds2005 session14
10 qmds2005 session14Niit Care
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL IISankhya_Analytics
 
07 qmds2005 session10
07 qmds2005 session1007 qmds2005 session10
07 qmds2005 session10Niit Care
 
Session 2: SQL Server 2012 with Christian Malbeuf
Session 2: SQL Server 2012 with Christian MalbeufSession 2: SQL Server 2012 with Christian Malbeuf
Session 2: SQL Server 2012 with Christian MalbeufCTE Solutions Inc.
 
MS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And ProceduresMS SQLSERVER:Sql Functions And Procedures
MS SQLSERVER:Sql Functions And Proceduressqlserver content
 
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 Proceduressqlserver content
 
New features of sql server 2005
New features of sql server 2005New features of sql server 2005
New features of sql server 2005Govind Raj
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Netwebhostingguy
 
OTech magazine article - Principle of Least Privilege
OTech magazine article - Principle of Least PrivilegeOTech magazine article - Principle of Least Privilege
OTech magazine article - Principle of Least PrivilegeBiju Thomas
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...Jürgen Ambrosi
 
13 qmds2005 session18
13 qmds2005 session1813 qmds2005 session18
13 qmds2005 session18Niit Care
 
SQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptxSQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptxKashifManzoorMeo
 
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...onlinetraining24
 

Semelhante a 09 qmds2005 session13 (20)

10 qmds2005 session14
10 qmds2005 session1410 qmds2005 session14
10 qmds2005 session14
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
07 qmds2005 session10
07 qmds2005 session1007 qmds2005 session10
07 qmds2005 session10
 
Session 2: SQL Server 2012 with Christian Malbeuf
Session 2: SQL Server 2012 with Christian MalbeufSession 2: SQL Server 2012 with Christian Malbeuf
Session 2: SQL Server 2012 with Christian Malbeuf
 
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
 
Sql Functions And Procedures
Sql Functions And ProceduresSql Functions And Procedures
Sql Functions And Procedures
 
Mysql
MysqlMysql
Mysql
 
New features of sql server 2005
New features of sql server 2005New features of sql server 2005
New features of sql server 2005
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
 
MariaDB training
MariaDB trainingMariaDB training
MariaDB training
 
OTech magazine article - Principle of Least Privilege
OTech magazine article - Principle of Least PrivilegeOTech magazine article - Principle of Least Privilege
OTech magazine article - Principle of Least Privilege
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
 
13 qmds2005 session18
13 qmds2005 session1813 qmds2005 session18
13 qmds2005 session18
 
SQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptxSQL_SERVER_BASIC_1_Training.pptx
SQL_SERVER_BASIC_1_Training.pptx
 
Store procedures
Store proceduresStore procedures
Store procedures
 
Sql views
Sql viewsSql views
Sql views
 
Online Datastage Training
Online Datastage TrainingOnline Datastage Training
Online Datastage Training
 
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
Datastage Online Training|IBM Infosphere Datastage Training|Datastage 8.7 onl...
 
Datastage Online Training
Datastage Online TrainingDatastage Online Training
Datastage Online Training
 

Mais de Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 

Último

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Último (20)

Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

09 qmds2005 session13

  • 1. Querying and Managing Data Using SQL Server 2005 Objectives In this session, you will learn to: Implement stored procedures Implement functions Ver. 1.0 Session 13 Slide 1 of 19
  • 2. Querying and Managing Data Using SQL Server 2005 Creating Stored Procedures Stored procedures: Are created using the CREATE PROCEDURE statement Are executed using the EXECUTE PROCEDURE statement Syntax: CREATE PROCEDURE proc_name AS BEGIN sql_statement1 sql_statement2 END Let’s see how… Ver. 1.0 Session 13 Slide 2 of 19
  • 3. Querying and Managing Data Using SQL Server 2005 Creating Stored Procedures (Contd.) Stored procedure: Is modified using the ALTER PROCEDURE statement Syntax: ALTER PROCEDURE proc_name Is deleted using the DROP PROCEDURE statement Syntax: DROP PROCEDURE proc_name Let’s see how… Ver. 1.0 Session 13 Slide 3 of 19
  • 4. Querying and Managing Data Using SQL Server 2005 Just a minute Which command will you use to modify the procedure? Answer: ALTER PROCEDURE Ver. 1.0 Session 13 Slide 4 of 19
  • 5. Querying and Managing Data Using SQL Server 2005 Just a minute Which system-defined table stores the names of all the stored procedure? Answer: sysobjects Ver. 1.0 Session 13 Slide 5 of 19
  • 6. Querying and Managing Data Using SQL Server 2005 Creating Parameterized Stored Procedures Parameterized stored procedures: Are used to pass values to the stored procedure during the run time Involve declaring variables and passing value to it, which is defined as input parameter Let’s see how… Ver. 1.0 Session 13 Slide 6 of 19
  • 7. Querying and Managing Data Using SQL Server 2005 Returning Values from Stored Procedures Stored procedure: Can also return values as output Uses the OUPUT keyword to specify the parameter as output parameter Syntax: CREATE PROCEDURE procedure_name [ {@parameter data_type} [OUTPUT] ] AS sql_statement [...n] Let’s see how… Ver. 1.0 Session 13 Slide 7 of 19
  • 8. Querying and Managing Data Using SQL Server 2005 Calling a Procedure from Another Procedure Stored procedure: Can use the values returned by a procedure inside another procedure That calls or executes another procedure is known as the calling procedure That is called or executed by the calling procedure is known as the called procedure Let’s see how… Ver. 1.0 Session 13 Slide 8 of 19
  • 9. Querying and Managing Data Using SQL Server 2005 Demo: Creating Stored Procedures Problem Statement: You are a database developer of AdventureWorks, Inc. The Human Resource department needs to revise the payment details of the employees. You need to create a procedure that obtains the percentage value by which you need to increase the pay rate. In addition, you need to ensure that the pay is revised for only those employees whose pay rate was not revised in the last six months. Ver. 1.0 Session 13 Slide 9 of 19
  • 10. Querying and Managing Data Using SQL Server 2005 Demo: Creating Stored Procedures (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Create a stored procedure. 2. Execute the stored procedure. 3. Verify the result. Ver. 1.0 Session 13 Slide 10 of 19
  • 11. Querying and Managing Data Using SQL Server 2005 Creating UDFs Scalar functions include the following components: Function name with optional schema/owner name Input parameter name and data type Options applicable to the input parameter Return parameter data type and optional name Options applicable to the return parameter One or more T-SQL statements Scalar functions can be created by using the CREATE FUNCTION statement. Ver. 1.0 Session 13 Slide 11 of 19
  • 12. Querying and Managing Data Using SQL Server 2005 Creating UDFs (Contd.) Syntax: CREATE FUNCTION [ schema_name. ] function_name ( [ { @parameter_name [ AS ][ type_schema_name. ] parameter_data_type [ = default ] } [ ,...n ] ] ) RETURNS return_data_type [ WITH <function_option> [ ,...n ] ] [ AS ] BEGIN function_body RETURN scalar_expression END [ ; ] Let’s see how… Ver. 1.0 Session 13 Slide 12 of 19
  • 13. Querying and Managing Data Using SQL Server 2005 Creating UDFs (Contd.) Table-valued functions: Returns a table as an output, which can be derived as a part of a SELECT statement Uses the table data type to store the set of rows Are of following two types: Inline table-valued function Multistatement table-valued function Let’s see how… Ver. 1.0 Session 13 Slide 13 of 19
  • 14. Querying and Managing Data Using SQL Server 2005 Just a minute Which type of function returns a single value? Answer: Scalar functions Ver. 1.0 Session 13 Slide 14 of 19
  • 15. Querying and Managing Data Using SQL Server 2005 Demo: Creating Functions Problem Statement: As a database developer at AdventureWorks, Inc., you need to create a function that accepts the employee ID of an employee and returns the following details: • Employee ID • Name of the employee • Title of the employee • Number of other employees working under the employee How will you create the function? Ver. 1.0 Session 13 Slide 15 of 19
  • 16. Querying and Managing Data Using SQL Server 2005 Demo: Creating Functions (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Create a function. 2. Execute the function to verify the result. Ver. 1.0 Session 13 Slide 16 of 19
  • 17. Querying and Managing Data Using SQL Server 2005 Summary In this session, you learned that: A stored procedure is a collection of various T-SQL statements that are stored under one name and are executed as a single unit. A stored procedure can be created using the CREATE PROCEDURE statement. A stored procedure allows you to declare parameters, variables, and use T-SQL statements and programming logic. A stored procedure provides better performance, security, and accuracy, and reduces the network congestion. A stored procedure is a collection of various T-SQL statements that are stored under one name and are executed as a single unit. A stored procedure can be created using the CREATE PROCEDURE statement. Ver. 1.0 Session 13 Slide 17 of 19
  • 18. Querying and Managing Data Using SQL Server 2005 Summary (Contd.) A stored procedure allows you to declare parameters, variables, and use T-SQL statements and programming logic. A stored procedure provides better performance, security, and accuracy, and reduces the network congestion. A stored procedure accepts data through input parameters. A stored procedure returns data through the output parameters or return statements. A stored procedure can be executed by using the EXECUTE statement. A stored procedure can be altered by using the ALTER PROCEDURE statement. A user-defined function is a database object that contains a set of T-SQL statements. The user-defined functions can return either a single scalar value or a result set. Ver. 1.0 Session 13 Slide 18 of 19
  • 19. Querying and Managing Data Using SQL Server 2005 Summary (Contd.) UDFs are of two types: scalar functions and table-valued functions. A scalar function accepts a single value and returns a single value. A table-valued function returns a table as an output, which can be derived as a part of a SELECT statement. Ver. 1.0 Session 13 Slide 19 of 19

Notas do Editor

  1. Start the session by sharing the objectives with the students.
  2. In this slide, you need to explain the concept of Stored Procedures to the students. Further, you will discuss the benefits of procedures – modularity, speed, security, reduced network congestion and consistency of usage across applications and users. Tell the students that since stored procedures have so many benefits, all operations and transactions from the client such as queries, updation, insertion, and deletion of rows are done using stored procedures. Even if the insert, update, delete, or query operation is very simple, a stored procedure must be created. This improves performance of the application. Hence, programmers simply execute the stored procedures, which are stored at the backend instead of sending SQL statements from the client. If the definition of the stored procedure needs to be modified, then use the ALTER PROCEDURE statement. You can use the examples given in the Student Guide to clarify the concept to the students. Further, you can execute the following statements to explain the concept: Example: CREATE PROCEDURE prcDept AS BEGIN SELECT Name FROM HumanResources.Department END Executing the procedure EXECUTE prcDept Additional Inputs When designing an application, stored procedures can significantly reduce the network requirements. Use stored procedures for long, complicated, and frequently repeated queries. This reduces the traffic from the client to the server because only the stored procedure name and its associated parameters are passed across the network to the server, where it is executed. In addition, multi-step queries that perform additional filtering or processing based upon the response to initial queries, run much more efficiently as a stored procedure. By using a stored procedure, it is not necessary to pass the results of the initial query to the client in order that a second query can be passed to the server. The sp_depends stored procedure can be used to find out the dependencies of a stored procedure. The syntax is as given below: sp_depends object_name
  3. In this slide, you will tell the students about altering and dropping a stored procedure. You can use the examples given in the Student Guide to clarify the concept to the students. Further, you can execute the following statements to explain the concept: Example: (ALTER) ALTER PROCEDURE prcDept AS BEGIN SELECT DepartmentID, Name FROM HumanResources.Department END Example: (DROP) DROP PROCEDURE pcrDept
  4. Reiterate the concepts taught in the preceding slides by asking the question.
  5. Reiterate the concepts taught in the preceding slides by asking the question.
  6. In this slide, you need to explain about parameterized stored procedures. After explaining the two types of parameters, tell the students that a procedure with output parameters is typically executed from another calling procedure. Mention that the ‘return’ keyword is used when a single value needs to be returned to the calling program. Output parameters are used when multiple values of any data type have to be returned. Tell the students that apart from explicitly executing a stored procedure it can be executed automatically, for example, at the start-up of SQL Server. This can be done by using a system stored procedure called sp_procoption for only objects of master database, which are owned by dbo. The syntax for sp_procoption procedure is shown below: sp_procoption @ProcName = &apos; procedure &apos;, @OptionName = &apos; option &apos;, @OptionValue = &apos; value &apos; where, @ProcName defines the procedure for which to set the option @OptionName defines the option to set for the procedure that can only be ‘startup’, which will set the procedure for autoexecution @OptionValue defines whether to set the option as true or false Procedure Usage Mention in the class that if data changes and indexes are updated, the execution plan for the SQL statements in a stored procedure will become outdated. In this kind of a situation, the SQL statement needs to be recompiled every time the stored procedure gets executed. This is done using the WITH RECOMPILE option of the CREATE PROCEDURE statement. Remember to use naming conventions while creating procedures. Refer SG for explanation Example: CREATE PROC prcListEmployee @title char(50) AS BEGIN PRINT &apos;List of Employees&apos; SELECT EmployeeID, LoginID, Title FROM HumanResources.Employee WHERE Title = @title END Execute by passing a parameter EXECUTE prcListEmployee &apos;Tool Designer&apos;
  7. Example: CREATE PROCEDURE prcGetEmployeeDetail @EmpId int, @DepId int OUTPUT, @DepName char(50) OUTPUT, @ShiftId int OUTPUT AS BEGIN IF EXISTS(SELECT * FROM HumanResources.Employee WHERE EmployeeID = @EmpId) BEGIN SELECT @DepId = d.DepartmentID, @DepName = Name, @ShiftId = ShiftID FROM HumanResources.Department d JOIN HumanResources.EmployeeDepartmentHistory h ON d.DepartmentID = h.DepartmentID WHERE EmployeeID = @EmpId RETURN 0 END ELSE RETURN 1 END
  8. In this slide, you need to tell the students about calling a procedure from another. Additional Inputs Notice that whenever a procedure gets called from within another procedure you have to use the EXEC keyword. Example: CREATE PROCEDURE prcDisplayEmployeeStatus @EmpId int AS BEGIN DECLARE @DepId int DECLARE @DepName char(50) DECLARE @ShiftId int DECLARE @ReturnValue int EXEC @ReturnValue = prcGetEmployeeDetail @EmpId, @DepId output, @DepName output, @ShiftId output IF (@ReturnValue = 0) BEGIN PRINT &apos;The Details of an Employee having ID: &apos; + CONVERT(char(10), @EmpId) PRINT &apos;Department ID: &apos; + CONVERT( char(10), @DepId) PRINT &apos;Department Name: &apos; + @DepName PRINT &apos;Shift ID: &apos; + CONVERT( char(10), @ShiftId) Select ManagerID, Title from HumanResources.Employee Where EmployeeID = @EmpID END ELSE PRINT &apos;No records found for the given Employee&apos; END Executing the procedure: To execute the above procedure, you need to execute the following statement: EXEC PrcDisplayEmployeeStatus 2
  9. You need to ensure that after this demo, students are able to create and execute stored procedure.
  10. In this slide, you need to explain the user-defined functions first. In addition, state that User-Defined functions are of two types, Scalar Functions and Table-Valued Functions. In addition, you need to explain about Scalar Functions and creating Scalar Function.
  11. Example: CREATE FUNCTION HumanResources.MonthlySal ( @PayRate float) RETURNS float AS BEGIN RETURN (@PayRate * 8 * 30) END DECLARE @PayRate float SET @PayRate = HumanResources.MonthlySal(12.25) PRINT @PayRate
  12. In this slide, you need to explain the students about Table-Value Functions. Example: (inline table-valued function) USE AdventureWorks go CREATE FUNCTION fx_Department_GName ( @GrName nvarchar(20) ) RETURNS table AS RETURN ( SELECT * FROM HumanResources.Department WHERE GroupName=@GrName ) go After creating the function, calling the function with specified argument. SELECT * FROM fx_Department_GName(&apos;Manufacturing&apos;) Example: (multistatement table-valued function) CREATE FUNCTION PayRate (@rate money) RETURNS @table TABLE (EmployeeID int not null, RateChangeDate datetime not null, Rate money not null, PayFrequency tinyint not null, ModifiedDate datetime not null) AS BEGIN INSERT @table SELECT * FROM HumanResources.EmployeePayHistory WHERE Rate &gt; @rate RETURN END Select * from PayRate(45)
  13. Reiterate the learning by asking the given question.
  14. You need to ensure that after this demo, the students are able to create and execute user-defined functions.
  15. You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  16. You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  17. You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.