Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 98 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
98
Dung lượng
2,76 MB
Nội dung
356 Chapter 9 Creating Functions, Stored Procedures, and Triggers SET @ContactType = CASE Check for employee. WHEN EXISTS(SELECT * FROM [HumanResources].[Employee] e WHERE e.[ContactID] = @ContactID) THEN 'Employee' Check for vendor. WHEN EXISTS(SELECT * FROM [Purchasing].[VendorContact] vc INNER JOIN [Person].[ContactType] ct ON vc.[ContactTypeID] = ct.[ContactTypeID] WHERE vc.[ContactID] = @ContactID) THEN 'Vendor Contact' Check for store. WHEN EXISTS(SELECT * FROM [Sales].[StoreContact] sc INNER JOIN [Person].[ContactType] ct ON sc.[ContactTypeID] = ct.[ContactTypeID] WHERE sc.[ContactID] = @ContactID) THEN 'Store Contact' Check for individual consumer. WHEN EXISTS(SELECT * FROM [Sales].[Individual] i WHERE i.[ContactID] = @ContactID) THEN 'Consumer' END; Return the information to the caller. IF @ContactID IS NOT NULL BEGIN INSERT @retContactInformation SELECT @ContactID, @FirstName, @LastName, @JobTitle, @ContactType; END; RETURN; END; SELECT * FROM dbo.ufnGetContactInformation(1); Deterministic vs. Nondeterministic Functions When working with functions, it’s important to know whether the function you are using is deterministic or nondeterministic. Deterministic functions return, for the same set of input values, the same value every time you call them. The SQL Server built-in function COS, which returns the trigonometric cosine of the specified angle, is an example of a deterministic function. In contrast, a nondeterministic function can return a different result every time you call it. An example of a nondeterministic function is the SQL Server built-in function GETDATE(), which returns the current system time and date. SQL Server also considers a function nondeterministic if the C0962271X.fm Page 356 Friday, April 29, 2005 7:49 PM Lesson 1: Implementing Functions 357 function calls a nondeterministic function or if the function calls an extended stored procedure. Whether a function is deterministic or not also determines whether you can build an index on the results the function returns and whether you can define a clustered index on a view that references the function. If the function is nondeterministic, you cannot index the results of the function, either through indexes on computed col- umns that call the function or through indexed views that reference the function. Quick Check ■ What are the two types of UDFs, and how are they used? Quick Check Answer ■ Scalar functions return a single value and are generally used in column lists and WHERE clauses. ■ Table-valued functions return a table variable and are used in the FROM clause. PRACTICE Create a Function In this practice, you create a scalar function to return the model name for a product given a particular product ID. You then create a table-valued function to return the contents of the Product table for a given model ID. 1. Launch SQL Server Management Studio (SSMS), connect to your instance, open a new query window, and change the context to the AdventureWorks database. 2. Create and test the GetModelNameForProduct scalar function by executing the following code: CREATE FUNCTION dbo.GetModelNameForProduct (@ProductID int) RETURNS nvarchar(50) WITH EXECUTE AS CALLER AS BEGIN DECLARE @ModelName nvarchar(50) SELECT @ModelName = Production.ProductModel.Name FROM Production.Product INNER JOIN Production.ProductModel ON Production.Product.ProductModelID = Production.ProductModel.ProductModelID WHERE Production.Product.ProductID = @ProductID C0962271X.fm Page 357 Friday, April 29, 2005 7:49 PM 358 Chapter 9 Creating Functions, Stored Procedures, and Triggers RETURN(@ModelName) END; GO SELECT dbo.GetModelNameForProduct(717); 3. Create and test the table-valued function GetProductsForModelID by executing the following code: CREATE FUNCTION dbo.GetProductsForModelID (@ProductModelID int) RETURNS @Products TABLE ( ProductID int NOT NULL, Name dbo.Name NOT NULL, ProductNumber nvarchar(25) NOT NULL, MakeFlag dbo.Flag NOT NULL, FinishedGoodsFlag dbo.Flag NOT NULL, Color nvarchar(15) NULL, SafetyStockLevel smallint NOT NULL, ReorderPoint smallint NOT NULL, StandardCost money NOT NULL, ListPrice money NOT NULL, Size nvarchar(5) NULL, SizeUnitMeasureCode nchar(3) NULL, WeightUnitMeasureCode nchar(3) NULL, Weight decimal(8, 2) NULL, DaysToManufacture int NOT NULL, ProductLine nchar(2) NULL, Class nchar(2) NULL, Style nchar(2) NULL, ProductSubcategoryID int NULL, ProductModelID int NULL, SellStartDate datetime NOT NULL, SellEndDate datetime NULL, DiscontinuedDate datetime NULL, rowguid uniqueidentifier NOT NULL, ModifiedDate datetime NOT NULL ) WITH EXECUTE AS CALLER AS BEGIN INSERT INTO @Products SELECT ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate FROM Production.Product WHERE Production.Product.ProductModelID = @ProductModelID C0962271X.fm Page 358 Friday, April 29, 2005 7:49 PM Lesson 1: Implementing Functions 359 RETURN END; GO SELECT * FROM dbo.GetProductsForModelID(6); Lesson Summary ■ SQL Server lets you create two types of UDFs—scalar and table-valued—to encap- sulate complex queries for reuse. ■ Scalar functions return a single value. ■ Table-valued functions return a table variable. ■ Computed columns or views based on deterministic functions, which return the same value every time they are called, can be indexed. Those using nondeter- ministic functions, which can return different results every time they are called, cannot be indexed. Lesson Review The following questions are intended to reinforce key information presented in this lesson. The questions are also available on the companion CD if you prefer to review them in electronic form. NOTE Answers Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book. 1. Which of the following are valid commands to use within a function? A. UPDATE Table1 SET Column1 = 1 B. SELECT Column1 FROM Table2 WHERE Column2 = 5 C. EXEC sp_myproc D. INSERT INTO @var VALUES (1) C0962271X.fm Page 359 Friday, April 29, 2005 7:49 PM 360 Chapter 9 Creating Functions, Stored Procedures, and Triggers Lesson 2: Implementing Stored Procedures Stored procedures are the most-used programmatic structures within a database. A pro- cedure is simply a name associated with a batch of SQL code that is stored and exe- cuted on the server. Stored procedures, which can return scalar values or result sets, are the primary interface that applications should use to access any data within a data- base. Not only do stored procedures enable you to control access to the database, they also let you isolate database code for easy maintenance instead of requiring you to find hard-coded SQL statements throughout an application if you need to make changes. In this lesson, you see how to create a stored procedure, recompile a stored procedure, and assign permissions to a role for a stored procedure. After this lesson, you will be able to: ■ Create a stored procedure. ■ Recompile a stored procedure. ■ Assign permissions to a role for a stored procedure. Estimated lesson time: 20 minutes Creating a Stored Procedure Stored procedures can contain virtually any construct or command that is possible to execute within SQL Server. You can use procedures to modify data, return scalar val- ues, or return entire result sets. Stored procedures also provide a very important security function within a database. You can grant users permission to execute stored procedures that access data without having to grant them the ability to directly access the data. Even more important, stored procedures hide the structure of a database from a user as well as only permit users to perform operations that are coded within the stored procedure. The general Transact-SQL syntax for creating a stored procedure is the following: CREATE { PROC | PROCEDURE } [schema_name.] procedure_name [;number ] [{@parameter [ type_schema_name.]data_type } [ OUT | OUTPUT ] ] [ , n ] [ WITH <procedure_option> [ , n ] ] [ FOR REPLICATION ] AS { <sql_statement> [;][ n ] | <method_specifier> } [;] C0962271X.fm Page 360 Friday, April 29, 2005 7:49 PM Lesson 2: Implementing Stored Procedures 361 <procedure_option> ::= [ ENCRYPTION ] [ RECOMPILE ] [ EXECUTE_AS_Clause ] <sql_statement> ::= { [ BEGIN ] statements [ END ] } <method_specifier> ::= EXTERNAL NAME assembly_name.class_name.method_name Each procedure must have a name that is unique within the database and that con- forms to the rules for object identifiers. Procedures can accept any number of input parameters, which are used within the stored procedure as local variables. You can also specify output parameters, which let a stored procedure pass one or more scalar values back to the routine that called the procedure. You can create procedures with three options. When you create a procedure with the ENCRYPTION option, SQL Server encrypts the procedure definition. Specifying the RECOMPILE option forces SQL Server to recompile the stored procedure each time the procedure is executed. The EXECUTE AS option provides a security context for the procedure. BEST PRACTICES Recompilation Stored procedures are compiled into the query cache when executed. Compilation creates a query plan as well as an execution plan. SQL Server can reuse the query plan for subsequent executions, which conserves resources. But the RECOMPILE option forces SQL Server to discard the query plan each time the procedure is executed and create a new query plan. There are only a few extremely rare cases when recompiling at each execution is beneficial, such as if you add a new index from which the stored procedure might benefit. Thus, you typically should not add the RECOMPILE option to a procedure when you create it. The body of the stored procedure contains the batch of commands you want to exe- cute within the procedure. The following are the only commands that you cannot exe- cute within a stored procedure: ■ SET SHOWPLAN_TEXT ■ SET SHOWPLAN_ALL ■ USE <database> C0962271X.fm Page 361 Friday, April 29, 2005 7:49 PM 362 Chapter 9 Creating Functions, Stored Procedures, and Triggers The following code shows a sample stored procedure that logs errors in a table called ErrorLog: CREATE PROCEDURE [dbo].[uspLogError] @ErrorLogID [int] = 0 OUTPUT contains the ErrorLogID of the row inserted by uspLogError in the AS ErrorLog table. BEGIN SET NOCOUNT ON; Output parameter value of 0 indicates that error information was not logged. SET @ErrorLogID = 0; BEGIN TRY Return if there is no error information to log. IF ERROR_NUMBER() IS NULL RETURN; Return if inside an uncommittable transaction. Data insertion/modification is not allowed when a transaction is in an uncommittable state. IF XACT_STATE() = -1 BEGIN PRINT 'Cannot log error since the current transaction is in an uncommittable state. ' + 'Rollback the transaction before executing uspLogError in order to successfully log error information.'; RETURN; END INSERT [dbo].[ErrorLog] ( [UserName], [ErrorNumber], [ErrorSeverity], [ErrorState], [ErrorProcedure], [ErrorLine], [ErrorMessage] ) VALUES ( CONVERT(sysname, CURRENT_USER), ERROR_NUMBER(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_PROCEDURE(), ERROR_LINE(), ERROR_MESSAGE() ); C0962271X.fm Page 362 Friday, April 29, 2005 7:49 PM Lesson 2: Implementing Stored Procedures 363 Pass back the ErrorLogID of the row inserted SET @ErrorLogID = @@IDENTITY; END TRY BEGIN CATCH PRINT 'An error occurred in stored procedure uspLogError: '; EXECUTE [dbo].[uspPrintError]; RETURN -1; END CATCH END; Assign Permissions to a Role for a Stored Procedure As with all objects and operations in SQL Server, you must explicitly grant a user per- mission to use an object or execute an operation. To allow users to execute a stored procedure, you use the following general syntax: GRANT EXECUTE ON <stored procedure>TO<database principle> Chapter 2, “Configuring SQL Server 2005,” covers the GRANT statement and data- base principles. The use of permissions with stored procedures is an interesting security mechanism. Any user granted execute permissions on a stored procedure is automatically dele- gated permissions to the objects and commands referenced inside the stored proce- dure based on the permission set of the user who created the stored procedure. To understand this delegation behavior, consider the previous example code. The stored procedure dbo.uspLogError inserts rows into the dbo.ErrorLog table. UserA has insert permissions on dbo.ErrorLog and also created this stored procedure. UserB does not have any permissions on dbo.ErrorLog. However, when UserA grants EXE- CUTE permissions on the dbo.uspLogError procedure, UserB can execute this proce- dure without receiving any errors because the SELECT and INSERT permissions necessary to add the row to the dbo.ErrorLog table are delegated to UserB. However, UserB receives those permissions only when executing the stored procedure and still cannot directly access the dbo.ErrorLog table. The permission delegation possible with stored procedures provides a very powerful security mechanism within SQL Server. If all data access—insertions, deletions, updates, or selects—were performed through stored procedures, users could not directly access any table in the database. Only by executing the stored procedures would users be able to perform the actions necessary to manage the database. And although users would have the permissions delegated through the stored procedures, C0962271X.fm Page 363 Friday, April 29, 2005 7:49 PM 364 Chapter 9 Creating Functions, Stored Procedures, and Triggers they would still be bound to the code within the stored procedure, which can perform actions such as the following: ■ Allowing certain operations to be performed only by users who are on a speci- fied list, which is maintained in another table by a user functioning in an admin- istrative role ■ Validating input parameters to prevent security attacks such as SQL injection. Quick Check 1. What is a stored procedure? 2. Which operations can a stored procedure perform? Quick Check Answers 1. A stored procedure is a name for a batch of Transact-SQL or CLR code that is stored within SQL Server. 2. A procedure can execute any commands within the Transact-SQL language except USE, SET SHOWPLAN_TEXT ON, and SET SHOWPLAN_ALL ON. PRACTICE Create a Stored Procedure In this practice, you create two stored procedures that will update the hire date for all employees to today’s date and then compare the procedures. 1. If necessary, launch SSMS, connect to your instance, open a new query window, and change the context to the AdventureWorks database. 2. Create a stored procedure to update the hire date by executing the following code: CREATE PROCEDURE dbo.usp_UpdateEmployeeHireDateInefficiently AS DECLARE @EmployeeID int DECLARE curemp CURSOR FOR SELECT EmployeeID FROM HumanResources.Employee OPEN curemp FETCH curemp INTO @EmployeeID WHILE @@FETCH_STATUS = 0 BEGIN UPDATE HumanResources.Employee SET HireDate = GETDATE() WHERE EmployeeID = @EmployeeID C0962271X.fm Page 364 Friday, April 29, 2005 7:49 PM Lesson 2: Implementing Stored Procedures 365 FETCH curemp INTO @EmployeeID END CLOSE curemp DEALLOCATE curemp 3. Create a second stored procedure to update the hire date by executing the following code: CREATE PROCEDURE dbo.usp_UpdateEmployeeHireDateEfficiently AS DECLARE @now DATETIME SET @now = GETDATE() UPDATE HumanResources.Employee SET HireDate = @now 4. Compare the execution between the two procedures by executing each of the queries in the following code separately: EXEC dbo.usp_UpdateEmployeeHireDateInefficiently EXEC dbo.usp_UpdateEmployeeHireDateEfficiently BEST PRACTICES Code efficiency Databases are built and optimized for set-oriented processes instead of row-at-a-time processes. When constructing stored procedures, you always want to use the minimum amount of code that also minimizes the amount of work performed. Although both of the procedures in this practice accomplish the requirement to change all employees’ hire dates, the second procedure executes significantly faster. The first procedure not only reads in the entire list of employees, but it also exe- cutes an update as well as a call to a function for each employee. The second procedure executes the GETDATE() function only once and performs a single update operation. Lesson Summary ■ Stored procedures are stored batches of code that are compiled when executed. ■ Procedures can be used to execute almost any valid command while also provid- ing a security layer between a user and the tables within a database. Lesson Review The following questions are intended to reinforce key information presented in this lesson. The questions are also available on the companion CD if you prefer to review them in electronic form. C0962271X.fm Page 365 Friday, April 29, 2005 7:49 PM [...]... Friday, April 29, 20 05 7 :53 PM 388 Chapter 10 Working with Flat Files bcp Command-Line Syntax The syntax for the bcp command is as follows: bcp {[[database_name.][owner].]{table_name | view_name} | "query"} {in | out | queryout | format} data_file [-mmax_errors] [-fformat_file] [-x] [-eerr_file] [-Ffirst_row] [-Llast_row] [-bbatch_size] [-n] [-c] [-w] [-N] [-V (60 | 65 | 70 | 80)] [-6 ] [-q] [-C { ACP | OEM... parameters For a full description of all the parameters available for bcp, see the SQL Server 20 05 Books Online topic “bcp Utility.” SQL Server 20 05 Books Online is installed as part of SQL Server 20 05 Updates for SQL Server 20 05 Books Online are available for download at www .microsoft. com/technet/ prodtechnol /sql/ 20 05/ downloads/books.mspx Flat files can come in many formats: with or without header... [-Llast_row] [-bbatch_size] [-n] [-c] [-w] [-N] [-V (60 | 65 | 70 | 80)] [-6 ] [-q] [-C { ACP | OEM | RAW | code_page } ] [-tfield_term] [-rrow_term] [-iinput_file] [-ooutput_file] [-apacket_size] [-Sserver_name[\instance_name]] [-Ulogin_id] [-Ppassword] [-T] [-v] [-R] [-k] [-E] [-h"hint [, n]"] As you can see, there are many parameters and options The following discussion centers on the most frequently... C1062271X.fm Page 380 Friday, April 29, 20 05 7 :53 PM 380 Chapter 10 Working with Flat Files Before You Begin To complete the lessons in this chapter, you must have ■ A computer that meets the hardware and software requirements for Microsoft SQL Server 20 05 ■ SQL Server 20 05 Developer, Workgroup, Standard, or Enterprise Edition installed Real World Daren Bieniek My work since the mid-1990s has focused mostly on... to the Bulk-Logged recovery model Although you can switch the database to the Bulk-Logged recovery model during normal usage, certain recovery capabilities are lost, such as point-in-time recovery To switch to the Bulk-Logged recovery model, C1062271X.fm Page 384 Friday, April 29, 20 05 7 :53 PM 384 Chapter 10 Working with Flat Files use either the ALTER DATABASE Transact -SQL command or SQL Server Management... as Bulk-Logged, except that you do not need to back up the transaction log for space to be cleared and reused Therefore, when using the Simple recovery model, transaction log backups are unreliable For more information about recovery models, see Chapter 2, Configuring SQL Server 20 05. ” C1062271X.fm Page 3 85 Friday, April 29, 20 05 7 :53 PM Lesson 1: Preparing to Work with Flat Files PRACTICE 3 85 Change... backup SQL Server Recovery Models SQL Server provides three recovery models: Full, Bulk-Logged, and Simple For the most part, the recovery model affects the way SQL Server uses and manages a database’s transaction log The Full recovery model records every change caused by every transaction at a granular level, which allows for point-in-time recovery You must back up the transaction log to allow SQL Server. .. However, unlike SQL Server 2000, SQL Server 20 05 requires that the user have ALTER TABLE permissions to suspend trigger execution, to suspend constraint checking, or to use the KEEPIDENTITY option C1062271X.fm Page 390 Friday, April 29, 20 05 7 :53 PM 390 Chapter 10 Working with Flat Files Quick Check ■ What permissions are needed to run the following bcp command? bcp Table1 in c:\test.txt -T -c Quick Check... -t, -r, and -F IMPORTANT Parameters are case-sensitive Note that bcp parameters are case-sensitive Therefore, -t and -T are different and unrelated parameters -t defines the column delimiter or field “t”erminator The default for this parameter is \t (tab character), or tab delimited If you are familiar with importing and exporting files in Microsoft Office Excel, you are probably familiar with tab-delimited... any data-load operations It then covers the different methods you can use to efficiently import files into SQL Server, including bulk copy program (bcp), the BULK INSERT Transact -SQL command, the OPENROWSET Transact -SQL function, and the SQL Server Integration Services (SSIS) Import/Export Wizard Exam objectives in this chapter: ■ Import and export data from a file ❑ Set a database to the bulk-logged . and constructs that are not allowed within a trigger in the SQL Server 20 05 Books Online article “CREATE TRIGGER (Transact -SQL) .” SQL Server does not support triggers against system objects such. implementation of a Transact -SQL or CLR batch that auto- matically runs in response to an event within the database. You can create two types of triggers in SQL Server 20 05: data manipulation language. the SQL Server built-in function GETDATE(), which returns the current system time and date. SQL Server also considers a function nondeterministic if the C0962271X.fm Page 356 Friday, April 29, 2005