Você está na página 1de 31

Stored Procedure

and
User-Defined Functions

TCS Internal
1
Scope

 SQL Extension
 Stored Procedure
 User-Defined Functions

TCS Internal
2
SQL Extension

Batches:

 A batch is a set of SQL statements submitted


together and executed as a group.

 A batch is compiled only once, and is


terminated by an end-of-batch signal.

 The end-of-batch signal is ‘GO’ command

TCS Internal
3
SQL Extension

Scripts
 Scripts are a series of batches submitted together.

SELECT...
UPDATE... BATCH
GO

BEGIN TRAN
......... BATCH
SCRIPT
COMMIT TRAN
GO
...........
.......... BATCH
GO

TCS Internal
4
SQL Extension

Combining statements in a single batch

 When creating batches, certain statements can be combined


to create a batch and others cannot be combined.

 Statements that can be combined are CREATE DATABASE,


CREATE TABLE, CREATE INDEX.

 Statements that cannot be combined are CREATE


Procedure, CREATE RULE, CREATE DEFAULT, CREATE
TRIGGER,CREATE VIEW

TCS Internal
5
SQL Extension

Rules to be followed for batches

 Rules and defaults cannot be bound to columns and then


used within the same batch.

 CHECK constraints cannot be defined and used in the same


batch.

 An object cannot be dropped and then referenced or


recreated in the same batch.

 You cannot alter the table and reference the new columns in
the same batch.

TCS Internal
6
SQL Extension – Flow-Control

Using Flow-Control Statements

 Control the flow of execution of SQL statements


within a set of statements such as statement blocks
and stored procedures.

 Permit to organize statements to provide the


capabilities of a conventional programming language
such as C or COBOL.

TCS Internal
7
SQL Extension – Flow-Control

BEGIN…END

 A series of statements enclosed by BEGIN and END is called a


statement block. The statement block is executed as a unit.

Syntax:
BEGIN
[SQL statements | statement block]
END

If BEGIN and END are not used, only the first statement immediately
following the IF...ELSE or WHILE is executed.

TCS Internal
8
SQL Extension – Flow-Control

IF…ELSE BLOCK

 IF and ELSE keywords are used to control conditional


execution of SQL statements.
 The condition for testing is defined as an expression
following the keyword IF. The syntax of an IF...ELSE
statement is as follows:
Syntax:
IF expression
SQL_statement | statement_block
[ELSE]
[IF expression]
SQL_statement | statement_block

TCS Internal
9
SQL Extension – Flow-Control

WHILE Construct

 The WHILE construct defines a condition for the repeated


execution of a SQL statement or a statement block.
 The statements continue to execute as long as the condition
tested is true.
Syntax:
WHILE expression
SQL statement | statement block

TCS Internal
10
SQL Extension – Flow-Control

BREAK and CONTINUE

 BREAK causes an exit from the WHILE loop.

 The execution of a BREAK results in the first statement following the


end of the block to begin executing.

 CONTINUE causes WHILE loop to restart the loop.

TCS Internal
11
SQL Extension

EXECUTE Statement

 The EXECUTE statement can be used to execute the


following:
 A system procedure, a user-defined stored procedure
or an extended stored procedure can be executed.
 A command composed of character string within a
Transact-SQL batch can be executed.
 A string can be created with variables that are
resolved at execution time.

TCS Internal
12
SQL Extension

CASE Expression

 Provides a means of returning a value based on whether a


specific expression is true.
 A CASE statement is like a nested IF statement within a
SELECT statement
 As soon as one is found to be true, the CASE expression
returns the corresponding value to the SELECT statement
that contains it.

TCS Internal
13
SQL Extension

CASE Related System Function

 The NULLIF function


 It relates two values or expressions.
 If the two are equal, returns NULL.
Syntax
 NULLIF (expression1, expression2)
EXAMPLE
 SELECT NULLIF(3, 3)
OUTPUT
 Returns NULL.

TCS Internal
14
SQL Extension

Defining and Using Variables

 Variables in Transact-SQL can be either:


 Local Variables
 Global Variables

TCS Internal
15
SQL Extension

Local Variables

 Local variables are user-defined entities that are assigned


values.
 The variables are defined and assigned a datatype by using
a DECLARE statement.
 Initial value is assigned with a SELECT statement.

Syntax:

For defining a local variable

DECLARE @variable_name datatype [, @variable_name


datatype]

TCS Internal
16
SQL Extension

Global Variables

 Global variables are predefined and maintained by the


system.

 Global variables are not defined by your routines, they are


defined at the server level.

 Always referenced by preceding with ‘@@’ sign.

 Global variables can be referenced to have a report on


system activity or about your operations.

TCS Internal
17
SQL Extension

Miscellaneous Procedural Statements

 The Procedural extension of the Transact-SQL language also contain


the following statements

 RETURN
 GOTO
 RAISEERROR
 WAITFOR

TCS Internal
18
RETURN Statements

RETURN Statements

 It returns from a query or procedure unconditionally.


 Statements following the RETURN are not executed.
Syntax:
 RETURN [integer_expression]
 To capture a returned integer value, execute the stored
procedure in the following format:
EXECUTE @return_status = procedure_name

TCS Internal
19
GOTO Label

 Alter the flow of execution to a label.

 SQL statement following GOTO are slipped and processing continues


at the label.

 Can be used anywhere within a procedure, batch or statement block

 Label names must follow the rules of identifier.

Defining the label


label:
Altering the execution
GOTO label

TCS Internal
20
RAISERROR Statement

 RAISERROR returns a user-defined error message in the same form


that SQL Server returns errors. It sets a system flag to record that
an error has occurred.

Syntax:

RAISERROR ( { mess_id | ‘text of message’} , severity ,


state
[, argument1] [, argument2]
[ WITH LOG]

TCS Internal
21
WITH LOG

 Logs the error in the server error log and the event log.
 Generally required for messages with a severity level of 19 through
25

 Can be issued only by the system administrator.

 If severity is 19 to 25, the client connection will be terminated after


receiving the message and the error will be logged in the error log
and the event log.

TCS Internal
22
WAIT FOR

 Specifies a time, time interval that triggers execution of a


statement block, stored procedure or transaction.

Syntax:

WAITFOR { DELAY ‘time’ | TIME ‘time’ }

TCS Internal
23
Stored Procedure

 A Stored Procedure is precompiled statements.


 The execution plan of a procedure is stored in the database
and used whenever the stored procedure is executed.

 There are two types:


 System Stored procedure
 User-defined stored procedure

TCS Internal
24
System Stored Procedure

 System stored procedure are special types of stored procedure


that are automatically generated during installation and are
therefore and integral part of the SQL server system.

 Names of all system stored procedure begins with the prefix


“sp_”.

 System stored procedure are used for the following purpose:


 To directly access the system tables
 To retrieve and modify access privileges of a database
 To control and manage the memory used by each database .

TCS Internal
25
Create a Stored Procedure

 Example:

CREATE PROCEDURE sel_emp (@emp_no INTEGER)


AS
BEGIN
SELECT * FROM EMP WHERE EMP_NO =
@emp_no
END

TCS Internal
26
Execute the Stored Procedure

 Example:

EXECUTE sel_emp @emp_no = 10

TCS Internal
27
User-Defined Functions

 In programming languages, there are generally two types of


routines:

 Procedure
 Functions

Procedure

Procedures are made up of several statements that have


zero or more input parameters but do not return any output
parameters.

Functions

Function generally return one or more parameters.

TCS Internal
28
Creation of User-Defined Functions

 Syntax:

CREATE FUNCTION <Table_Function_Name, sysname, FunctionName>


(
<@param1, sysname, @p1> <data_type_for_param1, , int>,
<@param2, sysname, @p2> <data_type_for_param2, , char>
)
RETURNS
<@Table_Variable_Name, sysname, @Table_Var> TABLE
(
-- Add the column definitions for the TABLE variable here
<Column_1, sysname, c1> <Data_Type_For_Column1, , int>,
<Column_2, sysname, c2> <Data_Type_For_Column2, , int>
)
AS
BEGIN
RETURN
END

TCS Internal
29
Example of User-Defined Functions

Example

CREATE FUNCTION [dbo].[Fun_Emp] (@emp_no INTEGER)


RETURNS TABLE
AS RETURN (SELECT * FROM EMP WHERE EMP_NO = @EMP_NO)

TCS Internal
30
Summary

 SQL Extension
 Stored Procedure
 User-Defined Functions

TCS Internal
31

Você também pode gostar