Upload
theodora-norman
View
228
Download
1
Embed Size (px)
Citation preview
Store ProceduresStore ProceduresLesson 9
Skills MatrixSkills Matrix
Stored ProceduresStored Procedures• Stored procedures in SQL Server are similar
to the procedures you write in other programming languages.
• Specifically, a stored procedure predefines a batch of code that you store as an object in the database to do work.
• A stored procedure has the ability to accept parameters, but it doesn’t necessarily need to use parameters.
• Within a stored procedure, you can use almost all Transact-SQL statements, except another CREATE PROCEDURE statement.
Stored ProceduresStored Procedures• SQL Server supports several types of
procedures:– System stored procedures that start with an
“sp_” (e.g., sp_help) and are stored in the Master and MSDB Databases.
– User stored procedures that can be written with either Transact-SQL or Common Language Runtime code and are usually stored with a specific database.
– Extended stored procedures that historically started with an “xp_” are implemented as dynamic linked libraries.
Stored ProceduresStored Procedures• You should familiarize yourself with at least this
list:– sp_add_job– sp_dboption– sp_executesql– sp_help– sp_helpdb– sp_configure– sp_who– sp_xml_preparedocument– xp_cmdshell– xp_sendmail
Using Procedure Option StatementsUsing Procedure Option Statements
• You learned that SQL Server stores the text used to create an object, and that anyone may run the sp_HelpText system stored procedure and view it.
• If you are a vendor and you wish to guard your intellectual property, consider adding the WITH ENCRYPTION option. This hides the text from copycats.
Using Procedure Option StatementsUsing Procedure Option Statements• The WITH RECOMPILE option indicates you
don’t want the execution plan cached in memory and that you want it recompiled each time called.
• The WITH EXECUTE AS clause permits the stored procedure to be run under any designated user’s security context. – Permission must be granted only on the
stored procedure itself, without having to grant explicit permissions on underlying or referenced objects.
Adding Input ParametersAdding Input Parameters
• When creating attributes in a table, you must follow naming convention guidelines, define a data type, and perhaps set a default value.
Adding Output and Handling ErrorsAdding Output and Handling Errors• Output parameters allow any changes to the
parameter that result from the execution of the stored procedure to be retained, even after the stored procedure completes execution.
• To use an output parameter, you must specify the OUTPUT keyword in both the CREATE PROCEDURE and the EXECUTE statements.
• If you omit the OUTPUT keyword when you execute the stored procedure, the stored procedure still completes but does not return the modified value.
Adding Output and Handling ErrorsAdding Output and Handling Errors• Consider these rules and guidelines when using
structured exception handing:– The CATCH block must immediately follow the TRY
block.– If a transaction specified in the TRY block (BEGIN
TRAN and COMMIT TRAN) generates an error, a jump to the CATCH block occurs, skipping the COMMIT TRAN statement. You probably need to put a ROLLBACK TRAN in the CATCH block to maintain data integrity.
– If a SET XACT_ABORT ON statement has been executed, the transaction automatically rolls back, except in the CATCH block. Here it changes status to uncommittable. Check for this condition using the XACT_STATE( ) function.
Adding Output and Handling ErrorsAdding Output and Handling Errors
• Capture error information with one or more system functions:– ERROR_LINE( )– ERROR_MESSAGE( )– ERROR_NUMBER( )– ERROR_PROCEDURE( )– ERROR_SEVERITY( )– ERROR_STATE( )
Changing Stored ProceduresChanging Stored Procedures
• You may delete (use the syntax DROP PROC Name) a stored procedure at any time and CREATE a replacement. – This also drops any associated
permissions.
• When changing something about the stored procedure, consider using the ALTER PROC syntax. – This retains the established security
context.
Common Language Runtime (CLR)Common Language Runtime (CLR)
• A common language runtime (CLR) procedure sets a reference to a method that supports parameters and becomes cataloged as a procedure in SQL Server.
• CLR procedures are written in a .NET CLR interpretable language such as Visual Basic .NET or C#.
• A .NET Framework CLR method exposes a SQL method defined in a .NET assembly.
Creating CLR Stored ProceduresCreating CLR Stored Procedures• To create a CLR stored procedure, you use
a development tool such as Visual Studio. • The actual syntax in Visual Studio then
depends on the language in which you program such as Visual Basic .NET or C#.
• When you deploy a project to SQL Server, the assembly or DLL file will be cataloged in the SQL database.
• These objects are displayable by querying the sys.assemblies system view.
Enabling the Server for CLR SupportEnabling the Server for CLR Support
• Before you can use CLR managed objects, you first need to enable the server for CLR support. sp_configure 'clr_enabled', 1reconfigure
• When a call to a CLR procedure is made without the CLR enabled, an error message that says the .NET Framework is not enabled appears.
Deployment GuidanceDeployment Guidance• Rules and considerations to keep in mind
when developing stored procedures:– Temporary stored procedures use the
resources of TEMPDB. Minimize their use.– SQL Server saves the connection string
parameters specified during stored procedure creation. These settings override any client settings during execution.
– Use a naming convention other than “sp_” for your procedures. Consider using “up_” standing for “user procedure.”
Deployment GuidanceDeployment Guidance– Create, test, and troubleshoot your stored
procedure code on your development workstation. Move it to your production environment during a minimal-use period when you can best afford some glitches. Test it from the client application using normal client permissions.
– Design each stored procedure to accomplish a single unit of work. Build a second or a third procedure rather than building one, hard-to-troubleshoot module.
– Qualify object names internal to the stored procedure by their two-part naming convention. This ensures other objects with different schemas remain accessible.
Processing Stored ProceduresProcessing Stored Procedures
• When SQL Server processes a stored procedure, the Query Optimizer first checks the procedure cache for an already in-memory execution plan. – If it finds one, it uses that plan to
complete the execution request. – Otherwise, it takes the time needed
to compile and cache a new execution plan prior to executing the query.
Compilation ProcessCompilation Process
• The compilation process consists of four stages:1. Parsing: SQL Server checks for
syntax errors and prepares it for optimization.
2. Normalization: SQL Server verifies that all object and column names in the query are correct.
Compilation ProcessCompilation Process
3. Compilation: SQL Server builds the execution plan for the stored procedure, creating query graphs for use by the Query Optimizer.
4. Optimization: A cost-based approach (number of CPU cycles, amount of RAM required, etc.) decides the expense of different possible processing options. The Query Optimizer normally uses the least cost approach. This behavior can be overridden by applying hints.
Recompile HintsRecompile Hints• Sometimes, SQL Server needs to recompile
(re-optimize) stored procedure execution plans
• When you examine the Execution Plan in Query Editor or suspect performance deficiency, you have three options:– The sp_recompile system stored procedure
forces a recompile next time run. – Use the WITH RECOMPILE option in the
CREATE PROCEDURE statement.– Use the WITH RECOMPILE option with the
EXECUTE statement:
SummarySummary– You learned that stored procedures:
•Provide a more secure method of accessing data than do direct calls from the client application.
•Reduce network traffic by processing on the server and delivering only the result set to the client application or user.
•Are compiled and stored in cache memory for rapid and efficient execution.
•Require recompilation when the code, parameters, or conditions change in your environment.
SummarySummary
– Package business functionality and create reusable application logic.
– Shield users from the details of the tables and other objects in the database.
– Provide additional security mechanisms.
– Reduce vulnerability to SQL injection attacks.
– Improve performance.
Summary for Certification ExaminationSummary for Certification Examination
• Be able to decide between various solutions. Is the stored procedure the best solution in a given situation?
• Consider the alternatives of a trigger, function, and client code in your analysis.
• As emphasized throughout this book, no one way or one right answer prevails.
• Administration balances competing alternatives.