Session 4
description
Transcript of Session 4
Session 4Working with SQL Server Database Objects
Faculty: Nguyen Ngoc Tu
Stored Procedures / Session 4/ 2 of 41
Review
A view is a virtual table generated using selected columns from one or more tables.
There are three types of views namely, Standard, Indexed and Partitioned.
Views are used to grant users limited access to database tables depending on individual user requirements.
System views are predefined created views for extracting SQL Server metadata.
Stored Procedures / Session 4/ 3 of 41
Review A view can be indexed by defining a UNIQUE
CLUSTERED index on it. The CHECK OPTION prevents data in a view
from being modified such that the modified data violates the view definition condition (that makes records disappear from the view!).
The SCHEMABINDING option is used to bind the view to the schema of the base table.(When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition)
Data can be modified through a view using the UPDATE, INSERT and DELETE statements.
For modifying data through a view, all important columns in the base table must be included in the view.
Module 7: Introducing stored proceduresObjectives
Stored Procedures / Session 4/ 5 of 41
Stored Procedures Stored procedures in Microsoft SQL Server are
similar to procedures in other programming languages in that they can: Accept input parameters and return multiple values in
the form of output parameters to the calling procedure or batch.
Contain programming statements that perform operations in the database, including calling other procedures.
Return a status value to a calling procedure or batch to indicate success or failure (and the reason for failure).
Stored Procedures / Session 4/ 6 of 41
Advantages – 1 Database developers or administrators write
stored procedures to perform a variety of tasks related to database access and management.
Using stored procedures offer numerous advantages over using Transact-SQL statements. These are: Improved Security Precompiled Execution Reduced Client/Server Traffic Reuse of Code
Stored Procedures / Session 4/ 7 of 41
Advantages – 2 Improved Security: by associating database
privileges with stored procedures. Users can be given permission to execute a stored procedure even if the user does not have permission to access the tables or views.
Precompiled Execution: stored procedures are compiled during the first execution. For every subsequent execution, SQL Server reuses this precompiled version. This reduces the time and resources required for compilation.
Stored Procedures / Session 4/ 8 of 41
Advantages – 3 Reduced Client/Server Traffic: stored
procedures help in reducing network traffic. Reuse of Code: stored procedures can be used
multiple times. This eliminates the need to repetitively type out hundreds of Transact-SQL statements every time a similar task is to be performed.
Stored Procedures / Session 4/ 9 of 41
Types of Stored Procedures There are many types of stored
procedures available in Microsoft SQL Server 2005: User-defined Stored Procedures Extended Stored Procedures (not use) System Stored Procedures
Others type: Temporary Stored Procedures Remote Stored Procedures Local Stored Procedures
Stored Procedures / Session 4/ 10 of 41
System Stored Procedures System stored procedures are used in database
administrative and informational activities. These procedures provide easy access to the
metadata information about database objects such as system tables, user-defined tables, views, and indexes.
System stored procedures logically appear in the sys schema of system and user-defined databases. When referencing a system stored procedure, the sys schema identifier is used.
The system stored procedures are stored physically in the Resource database and have the ‘sp_’ prefix.
Stored Procedures / Session 4/ 11 of 41
Extended Stored Procedures The extended stored procedures are not
residents of SQL Server. They are procedures that are implemented as dynamic-link libraries (DLL) executed outside the SQL Server environment.
Extended stored procedures use the ‘xp_’ prefix. Tasks that are complicated or cannot be executed using Transact-SQL statements are performed using extended stored procedures.
Stored Procedures / Session 4/ 12 of 41
Extended Stored Procedures-2 These stored procedures are contained in the dbo
schema of the master database. Extended stored procedures can be executed
under the security limitations specified by the SQL Server.
Extended stored procedures execute in the process space of the SQL Server.
When an extended stored procedure is executed, the extended stored procedure’s DLL remains in the address space of the server unless it is unloaded by the administrator.
Stored Procedures / Session 4/ 13 of 41
Temporary Stored Procedures Stored procedures created for temporary
use within a session are called temporary stored procedures. These procedures are stored in the tempdb database.
The tempdb system database is a global resource available to all users connected to an instance of SQL Server. It holds all temporary tables and temporary stored procedures.
Stored Procedures / Session 4/ 14 of 41
Temporary Stored Procedures - 2
SQL Server 2005 supports two types of temporary stored procedures namely, local and global. The differences are:
Stored Procedures / Session 4/ 15 of 41
Remote Stored Procedures Stored procedures that run on remote SQL Server
are known as remote stored procedures. Remote stored procedures can be used only when the remote server allows remote access.
When a remote stored procedure is executed from a local instance of SQL Server to a client computer, a statement abort error might be encountered. When such an error occurs, the statement that caused the error is terminated but the remote procedure continues to be executed.
Stored Procedures / Session 4/ 16 of 41
Local Stored Procedures
Local stored procedures are created in individual user databases. A local stored procedure cannot be accessed by any user other than the one who has created it.
If the local procedure is a temporary procedure, it is dropped at the end of the session.
Stored Procedures / Session 4/ 17 of 41
User-defined Stored Procedures – 1 In SQL Server 2005, users are allowed to create customized
stored procedures for performance of various tasks. Syntax:CREATE {PROC|PROCEDURE} procedure_name
[{@parameter data_type}] AS <sql_statement>
where: @parameter: specifies the input/output parameters in the
procedure. data_type: specifies the data types of parameters. sql_statement: specifies one or more Transact-SQL statements
to be included in the procedure.
Stored Procedures / Session 4/ 18 of 41
User-defined Stored Procedures – 2 Example:CREATE PROCEDURE Show_Customers
AS
SELECT * FROM Customer_Details
To execute the stored procedureEXECUTE Show_Customers
Custom stored procedures can be set to override the default system procedures.
Stored Procedures / Session 4/ 19 of 41
Deferred Name Resolution You can create stored procedures that reference
tables that do not yet exist. At creation time: only syntax checking is
performed. The stored procedure is not compiled until it is executed for the first time.
At first instance of the stored procedure execution: the query processor reads the statements in the stored procedure from the sys.sql_modules catalog view. The processor then checks for the name of all objects used by the procedure. This check is known as deferred name resolution. If a referenced object is missing, the execution stops.
Stored Procedures / Session 4/ 20 of 41
Deferred Name Resolution Example:CREATE PROCEDURE usp_proc1 AS SELECT column1, column2 FROM table_does_not_exist
--
SELECT definition FROM sys.sql_modules
WHERE object_id = OBJECT_ID('dbo.usp_proc1');
Stored Procedures / Session 4/ 21 of 41
Deferred Name Resolution Process
Validation activities other than checking for referenced objects are also carried out in the deferred name resolution stage. For example, variables are checked for compatibility with the column data types. If an error is found in the resolution stage, SQL Server returns an error.
If the resolution stage of the execution process is successfully completed, the procedure is compiled. For every subsequent call to the procedure, this compiled version is used.
User-defined Stored Procedures
Transact-SQL Stored Procedures
CLR Stored Procedures
Stored Procedures / Session 4/ 23 of 41
Transact-SQL Stored Procedures – 1 A Transact-SQL stored procedure is a
saved collection of Transact-SQL statements that can take and return user-supplied parameters
A stored procedure can be created either for permanent use or for temporary use.
A stored procedure is created using the CREATE PROCEDURE statement.
Stored Procedures / Session 4/ 24 of 41
Transact-SQL Stored Procedures – 2 Syntax:CREATE {PROC|PROCEDURE} procedure_name [{@parameter data_type} [=DEFAULT] [OUTPUT] ] [WITH ENCRYPTION]
AS <sql_statement>
where DEFAULT: specifies a default value for the parameter. OUTPUT: specifies that the parameter is an output
parameter.
Stored Procedures / Session 4/ 25 of 41
Transact-SQL Stored Procedures – 3 Example:CREATE PROCEDURE Display_Customers
AS
SELECT CustID, AccNo, AccName, City, State, Country FROM Customer_Details
To execute:EXECUTE Display_Customers
Stored Procedures / Session 4/ 26 of 41
Using “OUTPUT” Clause The OUTPUT clause returns information from each row on which the
INSERT, UPDATE and DELETE statements have been executed. This clause is useful to retrieve the value of an identity or computed column after an INSERT or UPDATE operation.
Example:CREATE PROCEDURE Display_Customers
@max_sal int OUTPUT
AS SELECT @max_sal = MAX(Salary) FROM Employee_Details
---
DECLARE @max_sal int;
EXECUTE Display_Customers @max_sal OUTPUT;
PRINT @max_sal;
Stored Procedures / Session 4/ 27 of 41
Guidelines When a local temporary table is created inside a stored
procedure, the table disappears when the procedure is exited.
Stored procedures can reference tables, views, user-defined functions and other stored procedures.
When a stored procedure calls another stored procedure, the called procedure can access all objects created by the calling procedure.
Changes made by a remote stored procedure on a remote instance of Microsoft SQL Server 2005 cannot be rolled back.
A stored procedure can have a maximum of 2100 parameters.
The number of local variables in a stored procedure depends upon available memory.
Stored Procedures / Session 4/ 28 of 41
Module 7 - Summary A stored procedure is a group of Transact-SQL
statements executed as a single block of code. SQL Server 2005 provides various system
stored procedures that assist in database administrative activities.
User can create custom stored procedures for performing various tasks.
Deferred name resolution is the stage where the processor checks for names of the objects referenced by the procedure. This check is done during the execution of the procedure.
When a procedure is executed, parameters can be passed between the calling program and the stored procedure.
Module 8: More About Stored proceduresObjectives
Stored Procedures / Session 4/ 30 of 41
Viewing Definitions A stored procedure is defined using a set of
Transact-SQL statements. This definition consists of two parts: Name, input and output parameters. Body
You can view the definition of a stored procedure using one of the following: sp_helptext system stored procedure. sys.sql_modules system view OBJECT_DEFINITION function
Stored Procedures / Session 4/ 31 of 41
Viewing Definitions Using “OBJECT_DEFINITION”
Syntax:OBJECT_DEFINITION ‘<object_id>’
where,object_id: specifies the ID of the stored procedure.
Example: SELECT OBJECT_DEFINITION (OBJECT_ID
(‘Display_Customers’) ) AS Definition
where, OBJECT_ID: is the system function that returns ID of
the specified object.
Stored Procedures / Session 4/ 32 of 41
Viewing Definitions Using “sys.sql_modules”
Example: SELECT definition FROM sys.sql_modules WHERE
object_id = OBJECT_ID (‘Display_Customers’)
where, definition: is the column in the
sys.sql_modules system view that display the definition of the specified object.
Stored Procedures / Session 4/ 33 of 41
Viewing Dependencies In SQL Server 2005, the dependencies
of a stored procedure can be viewed using the sp_depends system stored procedure.
Syntax: sp_depends ‘<procedure_name>’
Example: sp_depends ‘Display_Customers’
Stored Procedures / Session 4/ 34 of 41
Modifying and Dropping Stored Procedures
A stored procedure can be modified to change the procedure name as well as the procedure definition. You can change the procedure statements or parameters by either re-creating the stored procedure or by altering the existing procedure.
To modify or rename a procedure, you must either own the procedure or have the required permissions to carry out the modifications.
The database owner can modify or rename all procedures.
Stored Procedures / Session 4/ 35 of 41
Modifying Stored Procedures Syntax:ALTER PROCEDURE <procedure_name>
@parameter <data_type> [OUTPUT][WITH { ENCRYPTION|RECOMPILE }]
AS <sql_statement>
where RECOMPILE: indicates that the procedure is compiled at run time.
Example:ALTER PROCEDURE Display_Customers AS
SELECT CustID, AccNo, AccName, City, State, Country
FROM Customer_Details
WHERE City=‘New York’
Stored Procedures / Session 4/ 36 of 41
Guidelines When a stored procedure is created using
options such as the WITH ENCRYPTION option, these options should be also be included in the ALTER PROCEDURE statement.
The ALTER PROCEDURE statement alters a single procedure. When a stored procedure calls other stored procedures, the nested stored procedures are not affected by altering the calling procedure.
The creators of the stored procedure, members of the sysadmin server role and members of the db_owner and db_ddladmin fixed database roles have the permission to execute the ALTER PROCEDURE statement.
Stored Procedures / Session 4/ 37 of 41
Dropping Stored Procedures
Stored procedures can be dropped if they are no longer needed. If another stored procedure calls a deleted procedure, an error message is displayed.
Before dropping a stored procedure, execute the sp_depends system stored procedure to determine which objects depend on the procedure.
A procedure is dropped using the DROP PROCEDURE statement.
Syntax: DROP PROCEDURE <procedure_name> Example: DROP PROCEDURE Display_Customers
Stored Procedures / Session 4/ 38 of 41
Returning Values
Stored Procedures / Session 4/ 39 of 41
“RETURN” Statement Example:CREATE PROCEDURE Cal_Square @num int = 0
AS
BEGIN
RETURN (@num * @num);
END Executing the stored procedure:DECLARE @square int;
EXECUTE @square = Cal_Square 10;
PRINT @square;
Stored Procedures / Session 4/ 40 of 41
Input Parameters Example:CREATE PROCEDURE StateWise_Customers
@statename varchar(40)
AS
SELECT AccNo, AccName, City, State
FROM Customer_Details
WHERE State= @statename
To execute the stored procedure and pass values as input parameters:
EXECUTE StateWise_Customers ‘California’
Stored Procedures / Session 4/ 41 of 41
Output Parameters Syntax:CREATE PROCEDURE <procedure_name>
@parameter <data_type>,
@parameter <data_type> OUTPUT
AS <sql_statement>
To execute:EXECUTE <procedure_name>< parameters> [OUTPUT]
Stored Procedures / Session 4/ 42 of 41
Nested Stored Procedures
In SQL Server 2005, you can call stored procedures from inside othe stored procedures. This architecture of calling one procedure from another procedure is referred to as nested stored procedure architecture.
The maximum level of nesting supported by SQL Server 2005 is 32. If the level of nesting exceeds 32, the calling process fails.
Example:CREATE PROCEDURE NestedProcedure
AS
EXECUTE Display_Customers
EXECUTE CityWise_Customers ‘New York’
Stored Procedures / Session 4/ 43 of 41
Handling Error Messages SQL Server 2005 introduces the TRY…CATCH
construct for handling errors in stored procedures. The TRY…CATCH construct consists of two blocks of code, the TRY block and the CATCH block.
When an error is detected in an SQL statement inside a TRY block, control is passed to the CATCH block, where the error can be processed. After the error is processed in the CATCH block, the control is transferred to the SQL statement that is written after the END CATCH statement. The SQL statements in the TRY block written after the statement that generates the error are not executed.
Stored Procedures / Session 4/ 44 of 41
TRY…CATCH ConstructBEGIN TRY
.
{Error detected}
.
END TRY
BEGIN CATCH
{Error detected}
END CATCH
If there are no errors inside the TRY block, control passes to the statement written after the END CATCH statement of the corresponding CATCH block.
Stored Procedures / Session 4/ 45 of 41
“@@ERROR” Function Error handling in stored procedures can also be assisted
by the @@ERROR function. The @@ERROR function returns the error number for the error occurring in the last Transact-SQL statement (returns 0 if no errors).
Example:INSERT INTO Employee_Details
VALUES (16,’David’,’Johnson’,’1981/12/29’,’M’,’Miami’,’12000’);
IF @@ERROR <> 0
PRINT ‘An error occurred while inserting the record.’;
GO
Stored Procedures / Session 4/ 46 of 41
Module 8 - Summary The sp_helptext procedure can be used to
display the stored procedure definition. An object that references another object is
considered dependent on that object. The sp_depends procedure is used to display the information about database object dependencies.
In a stored procedure, statements or parameters can be changed by either re-creating the stored procedure or by altering an existing stored procedure.
A stored procedure can be dropped if it is not needed anymore.
Stored procedures can be nested; that is, a stored procedure can be called from within another stored procedure.
In stored procedures, error handling is done using the TRY…CATCH construct.
Stored Procedures / Session 4/ 47 of 41
programming statements The Transact-SQL control-of-flow language
keywords are: BEGIN...END RETURN BREAK TRY...CATCH CONTINUE WAITFOR GOTO label WHILE IF...ELSE
Stored Procedures / Session 4/ 48 of 41
programming statementsBEGIN
{sql_statement | statement_block}
END
--Define the label:
label : Alter the execution:
GOTO label
Stored Procedures / Session 4/ 49 of 41
programming statements
Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.
RETURN [ integer_expression ]
Stored Procedures / Session 4/ 50 of 41
programming statementsIF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]
The Transact-SQL statement that follows an IF keyword and its condition is executed if the condition is satisfied: the Boolean expression returns TRUE. The optional ELSE keyword introduces another Transact-SQL statement that is executed when the IF condition is not satisfied: the Boolean expression returns FALSE.
Stored Procedures / Session 4/ 51 of 41
programming statementsSimple CASE function:
CASE input_expression
WHEN when_expression THEN result_expression
[ ...n ]
[ELSE else_result_expression ] END
Searched CASE function:
CASE
WHEN Boolean_expression THEN result_expression
[ ...n ]
[ELSE else_result_expression] END
Stored Procedures / Session 4/ 52 of 41
programming statementsWHILE Boolean_expression
{ sql_statement | statement_block }
[ BREAK ]
{ sql_statement | statement_block }
[ CONTINUE ]
{ sql_statement | statement_block }
WAITFOR { DELAY 'time_to_pass' | TIME 'time_to_execute' | ( receive_statement ) [ , TIMEOUT timeout ] } WAITFOR { DELAY 'time_to_pass' | TIME 'time_to_execute' | ( receive_statement ) [ , TIMEOUT timeout ] }
The statements are executed repeatedly as long as the specified condition is true. The execution of statements in the WHILE loop can be controlled from inside the loop with the BREAK and CONTINUE keywords.
Stored Procedures / Session 4/ 53 of 41
programming statements
BEGIN TRY { sql_statement | statement_block } END TRY BEGIN CATCH { sql_statement | statement_block } END CATCH [ ; ]
BEGIN TRY
{ sql_statement | statement_block }
END TRY
BEGIN CATCH
{ sql_statement | statement_block }
END CATCH [ ; ]
Implements error handling for Transact-SQL that is similar to the exception handling in the C# and C++ languages. A group of Transact-SQL statements can be enclosed in a TRY block. If an error occurs within the TRY block, control is passed to another group of statements enclosed in a CATCH block.
Stored Procedures / Session 4/ 54 of 41
programming statementsWAITFOR
{
DELAY 'time_to_pass'
| TIME 'time_to_execute'
| ( receive_statement ) [ , TIMEOUT timeout ]
}
Blocks the execution of a batch, stored procedure, or transaction until a specified time or time interval is reached, or a specified statement modifies or returns at least one row.