Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Extensible Storage Engine wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Clusterpoint wikipedia , lookup
Relational model wikipedia , lookup
Database model wikipedia , lookup
Table of Contents Overview Create Modify Delete Execute Specify parameters Grant permissions Parameters Properties Return Data Recompile Rename View definition View dependenced OLE Automation Objects in Transact-SQL OLE Automation Return Codes and Error Information OLE Automation Result Sets OLE Automation Sample Script Stored Procedures (Database Engine) 3/24/2017 • 5 min to read • Edit Online A stored procedure in SQL Server is a group of one or more Transact-SQL statements or a reference to a Microsoft .NET Framework common runtime language (CLR) method. Procedures resemble constructs in other programming languages because they can: Accept input parameters and return multiple values in the form of output parameters to the calling program. Contain programming statements that perform operations in the database. These include calling other procedures. Return a status value to a calling program to indicate success or failure (and the reason for failure). Benefits of Using Stored Procedures The following list describes some benefits of using procedures. Reduced server/client network traffic The commands in a procedure are executed as a single batch of code. This can significantly reduce network traffic between the server and client because only the call to execute the procedure is sent across the network. Without the code encapsulation provided by a procedure, every individual line of code would have to cross the network. Stronger security Multiple users and client programs can perform operations on underlying database objects through a procedure, even if the users and programs do not have direct permissions on those underlying objects. The procedure controls what processes and activities are performed and protects the underlying database objects. This eliminates the requirement to grant permissions at the individual object level and simplifies the security layers. The EXECUTE AS clause can be specified in the CREATE PROCEDURE statement to enable impersonating another user, or enable users or applications to perform certain database activities without needing direct permissions on the underlying objects and commands. For example, some actions such as TRUNCATE TABLE, do not have grantable permissions. To execute TRUNCATE TABLE, the user must have ALTER permissions on the specified table. Granting a user ALTER permissions on a table may not be ideal because the user will effectively have permissions well beyond the ability to truncate a table. By incorporating the TRUNCATE TABLE statement in a module and specifying that module execute as a user who has permissions to modify the table, you can extend the permissions to truncate the table to the user that you grant EXECUTE permissions on the module. When calling a procedure over the network, only the call to execute the procedure is visible. Therefore, malicious users cannot see table and database object names, embed Transact-SQL statements of their own, or search for critical data. Using procedure parameters helps guard against SQL injection attacks. Since parameter input is treated as a literal value and not as executable code, it is more difficult for an attacker to insert a command into the Transact-SQL statement(s) inside the procedure and compromise security. Procedures can be encrypted, helping to obfuscate the source code. For more information, see SQL Server Encryption. Reuse of code The code for any repetitious database operation is the perfect candidate for encapsulation in procedures. This eliminates needless rewrites of the same code, decreases code inconsistency, and allows the code to be accessed and executed by any user or application possessing the necessary permissions. Easier maintenance When client applications call procedures and keep database operations in the data tier, only the procedures must be updated for any changes in the underlying database. The application tier remains separate and does not have to know how about any changes to database layouts, relationships, or processes. Improved performance By default, a procedure compiles the first time it is executed and creates an execution plan that is reused for subsequent executions. Since the query processor does not have to create a new plan, it typically takes less time to process the procedure. If there has been significant change to the tables or data referenced by the procedure, the precompiled plan may actually cause the procedure to perform slower. In this case, recompiling the procedure and forcing a new execution plan can improve performance. Types of Stored Procedures User-defined A user-defined procedure can be created in a user-defined database or in all system databases except the Resource database. The procedure can be developed in either Transact-SQL or as a reference to a Microsoft .NET Framework common runtime language (CLR) method. Temporary Temporary procedures are a form of user-defined procedures. The temporary procedures are like a permanent procedure, except temporary procedures are stored in tempdb. There are two types of temporary procedures: local and global. They differ from each other in their names, their visibility, and their availability. Local temporary procedures have a single number sign (#) as the first character of their names; they are visible only to the current user connection, and they are deleted when the connection is closed. Global temporary procedures have two number signs (##) as the first two characters of their names; they are visible to any user after they are created, and they are deleted at the end of the last session using the procedure. System System procedures are included with SQL Server. They are physically stored in the internal, hidden Resource database and logically appear in the sys schema of every system- and user-defined database. In addition, the msdb database also contains system stored procedures in the dbo schema that are used for scheduling alerts and jobs. Because system procedures start with the prefix sp_, we recommend that you do not use this prefix when naming user-defined procedures. For a complete list of system procedures, see System Stored Procedures (Transact-SQL) SQL Server supports the system procedures that provide an interface from SQL Server to external programs for various maintenance activities. These extended procedures use the xp_ prefix. For a complete list of extended procedures, see General Extended Stored Procedures (Transact-SQL). Extended User-Defined Extended procedures enable creating external routines in a programming language such as C. These procedures are DLLs that an instance of SQL Server can dynamically load and run. NOTE Extended stored procedures will be removed in a future version of SQL Server. Do not use this feature in new development work, and modify applications that currently use this feature as soon as possible. Create CLR procedures instead. This method provides a more robust and secure alternative to writing extended procedures. Related Tasks Task Description Topic Describes how to create a stored procedure. Create a Stored Procedure Describes how to modify a stored procedure. Modify a Stored Procedure Describes how to delete a stored procedure. Delete a Stored Procedure Describes how to execute a stored procedure. Execute a Stored Procedure Describes how to grant permissions on a stored procedure. Grant Permissions on a Stored Procedure Describes how to return data from a stored procedure to an application. Return Data from a Stored Procedure Describes how to recompile a stored procedure. Recompile a Stored Procedure Describes how to rename a stored procedure. Rename a Stored Procedure Describes how to view the definition of a stored procedure. View the Definition of a Stored Procedure Describes how to view the dependencies on a stored procedure. View the Dependencies of a Stored Procedure Describes how Parameters are used in a stored procedure. Parameters Related Content CLR Stored Procedures Create a Stored Procedure 3/24/2017 • 2 min to read • Edit Online This topic describes how to create a Transact-SQL stored procedure by using SQL Server Management Studio and by using the Transact-SQL CREATE PROCEDURE statement. Before you begin: Permissions To create a procedure, using: SQL Server Management Studio, Transact-SQL Permissions Requires CREATE PROCEDURE permission in the database and ALTER permission on the schema in which the procedure is being created. How to Create a Stored Procedure You can use one of the following: SQL Server Management Studio Transact-SQL Using SQL Server Management Studio To create a procedure in Object Explorer 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the AdventureWorks2012 database, and then expand Programmability. 3. Right-click Stored Procedures, and then click New Stored Procedure. 4. On the Query menu, click Specify Values for Template Parameters. 5. In the Specify Values for Template Parameters dialog box, enter the following values for the parameters shown. PARAMETER VALUE Author Your name Create Date Today's date Description Returns employee data. Procedure_name HumanResources.uspGetEmployeesTest @Param1 @LastName @Datatype_For_Param1 nvarchar(50) Default_Value_For_Param1 NULL PARAMETER VALUE @Param2 @FirstName @Datatype_For_Param2 nvarchar(50) Default_Value_For_Param2 NULL 6. Click OK. 7. In the Query Editor, replace the SELECT statement with the following statement: SELECT FirstName, LastName, Department FROM HumanResources.vEmployeeDepartmentHistory WHERE FirstName = @FirstName AND LastName = @LastName AND EndDate IS NULL; 8. To test the syntax, on the Query menu, click Parse. If an error message is returned, compare the statements with the information above and correct as needed. 9. To create the procedure, from the Query menu, click Execute. The procedure is created as an object in the database. 10. To see the procedure listed in Object Explorer, right-click Stored Procedures and select Refresh. 11. To run the procedure, in Object Explorer, right-click the stored procedure name HumanResources.uspGetEmployeesTest and select Execute Stored Procedure. 12. In the Execute Procedure window, enter Margheim as the value for the parameter @LastName and enter the value Diane as the value for the parameter @FirstName. WARNING Validate all user input. Do not concatenate user input before you validate it. Never execute a command constructed from unvalidated user input. Using Transact-SQL To create a procedure in Query Editor 1. In Object Explorer, connect to an instance of Database Engine. 2. From the File menu, click New Query. 3. Copy and paste the following example into the query window and click Execute. This example creates the same stored procedure as above using a different procedure name. USE AdventureWorks2012; GO CREATE PROCEDURE HumanResources.uspGetEmployeesTest2 @LastName nvarchar(50), @FirstName nvarchar(50) AS SET NOCOUNT ON; SELECT FirstName, LastName, Department FROM HumanResources.vEmployeeDepartmentHistory WHERE FirstName = @FirstName AND LastName = @LastName AND EndDate IS NULL; GO 4. To run the procedure, copy and paste the following example into a new query window and click Execute. Notice that different methods of specifying the parameter values are shown. EXECUTE HumanResources.uspGetEmployeesTest2 N'Ackerman', N'Pilar'; -- Or EXEC HumanResources.uspGetEmployeesTest2 @LastName = N'Ackerman', @FirstName = N'Pilar'; GO -- Or EXECUTE HumanResources.uspGetEmployeesTest2 @FirstName = N'Pilar', @LastName = N'Ackerman'; GO See Also CREATE PROCEDURE (Transact-SQL) Modify a Stored Procedure 3/24/2017 • 3 min to read • Edit Online This topic describes how to modify a stored procedure in SQL Server 2016 by using SQL Server Management Studio or Transact-SQL. Before you begin: Limitations and Restrictions, Security To alter a procedure, using: SQL Server Management Studio, Transact-SQL Before You Begin Limitations and Restrictions Transact-SQL stored procedures cannot be modified to be CLR stored procedures and vice versa. If the previous procedure definition was created using WITH ENCRYPTION or WITH RECOMPILE, these options are enabled only if they are included in the ALTER PROCEDURE statement. Security Permissions Requires ALTER PROCEDURE permission on the procedure. How to Modify a Stored Procedure You can use one of the following: SQL Server Management Studio Transact-SQL Using SQL Server Management Studio To modify a procedure in Management Studio 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the database in which the procedure belongs, and then expand Programmability. 3. Expand Stored Procedures, right-click the procedure to modify, and then click Modify. 4. Modify the text of the stored procedure. 5. To test the syntax, on the Query menu, click Parse. 6. To save the modifications to the procedure definition, on the Query menu, click Execute. 7. To save the updated procedure definition as a Transact-SQL script, on the File menu, click Save As. Accept the file name or replace it with a new name, and then click Save. IMPORTANT Validate all user input. Do not concatenate user input before you validate it. Never execute a command constructed from unvalidated user input. Using Transact-SQL To modify a procedure in Query Editor 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the database in which the procedure belongs. Or, from the tool bar, select the database from the list of available databases. For this example, select the AdventureWorks2012 database. 3. On the File menu, click New Query. 4. Copy and paste the following example into the query editor. The example creates the uspVendorAllInfo procedure, which returns the names of all the vendors in the Adventure Works Cycles database, the products they supply, their credit ratings, and their availability. IF OBJECT_ID ( 'Purchasing.uspVendorAllInfo', 'P' ) IS NOT NULL DROP PROCEDURE Purchasing.uspVendorAllInfo; GO CREATE PROCEDURE Purchasing.uspVendorAllInfo WITH EXECUTE AS CALLER AS SET NOCOUNT ON; SELECT v.Name AS Vendor, p.Name AS 'Product name', v.CreditRating AS 'Rating', v.ActiveFlag AS Availability FROM Purchasing.Vendor v INNER JOIN Purchasing.ProductVendor pv ON v.BusinessEntityID = pv.BusinessEntityID INNER JOIN Production.Product p ON pv.ProductID = p.ProductID ORDER BY v.Name ASC; GO 5. On the File menu, click New Query. 6. Copy and paste the following example into the query editor. The example modifies the uspVendorAllInfo procedure. The EXECUTE AS CALLER clause is removed and the body of the procedure is modified to return only those vendors that supply the specified product. The LEFT and CASE functions customize the appearance of the result set. ALTER PROCEDURE Purchasing.uspVendorAllInfo @Product varchar(25) AS SET NOCOUNT ON; SELECT LEFT(v.Name, 25) AS Vendor, LEFT(p.Name, 25) AS 'Product name', 'Rating' = CASE v.CreditRating WHEN 1 THEN 'Superior' WHEN 2 THEN 'Excellent' WHEN 3 THEN 'Above average' WHEN 4 THEN 'Average' WHEN 5 THEN 'Below average' ELSE 'No rating' END , Availability = CASE v.ActiveFlag WHEN 1 THEN 'Yes' ELSE 'No' END FROM Purchasing.Vendor AS v INNER JOIN Purchasing.ProductVendor AS pv ON v.BusinessEntityID = pv.BusinessEntityID INNER JOIN Production.Product AS p ON pv.ProductID = p.ProductID WHERE p.Name LIKE @Product ORDER BY v.Name ASC; GO 7. To save the modifications to the procedure definition, on the Query menu, click Execute. 8. To save the updated procedure definition as a Transact-SQL script, on the File menu, click Save As. Accept the file name or replace it with a new name, and then click Save. 9. To run the modified stored procedure, execute the following example. EXEC Purchasing.uspVendorAllInfo N'LL Crankarm'; GO See Also ALTER PROCEDURE (Transact-SQL) Delete a Stored Procedure 3/24/2017 • 2 min to read • Edit Online This topic describes how to delete a stored procedure in SQL Server 2016 by using SQL Server Management Studio or Transact-SQL. Before you begin: Limitations and Restrictions, Security To delete a procedure, using: SQL Server Management Studio, Transact-SQL Before You Begin Limitations and Restrictions Deleting a procedure can cause dependent objects and scripts to fail when the objects and scripts are not updated to reflect the removal of the procedure. However, if a new procedure of the same name and the same parameters is created to replace the one that was deleted, other objects that reference it will still process successfully. For more information, see View the Dependencies of a Stored Procedure. Security Permissions Requires ALTER permission on the schema to which the procedure belongs, or CONTROL permission on the procedure. How to Delete a Stored Procedure You can use one of the following: SQL Server Management Studio Transact-SQL Using SQL Server Management Studio To delete a procedure in Object Explorer 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the database in which the procedure belongs, and then expand Programmability. 3. Expand Stored Procedures, right-click the procedure to remove, and then click Delete. 4. To view objects that depend on the procedure, click Show Dependencies. 5. Confirm the correct procedure is selected, and then click OK. 6. Remove references to the procedure from any dependent objects and scripts. Using Transact-SQL To delete a procedure in Query Editor 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the database in which the procedure belongs, or, from the tool bar, select the database from the list of available databases. 3. On the File menu, click New Query. 4. Obtain the name of stored procedure to remove in the current database. From Object Explorer, expand Programmability and then expand Stored Procedures. Alternatively, in the query editor, run the following statement. SELECT name AS procedure_name ,SCHEMA_NAME(schema_id) AS schema_name ,type_desc ,create_date ,modify_date FROM sys.procedures; 5. Copy and paste the following example into the query editor and insert a stored procedure name to delete from the current database. DROP PROCEDURE <stored procedure name>; GO 6. Remove references to the procedure from any dependent objects and scripts. See Also Create a Stored Procedure Modify a Stored Procedure Rename a Stored Procedure View the Definition of a Stored Procedure View the Dependencies of a Stored Procedure DROP PROCEDURE (Transact-SQL) Execute a Stored Procedure 3/24/2017 • 5 min to read • Edit Online This topic describes how to execute a stored procedure in SQL Server 2016 by using SQL Server Management Studio or Transact-SQL. There are two different ways to execute a stored procedure. The first and most common approach is for an application or user to call the procedure. The second approach is to set the procedure to run automatically when an instance of SQL Server starts. When a procedure is called by an application or user, the Transact-SQL EXECUTE or EXEC keyword is explicitly stated in the call. Alternatively, the procedure can be called and executed without the keyword if the procedure is the first statement in the Transact-SQL batch. In This Topic Before you begin: Limitations and Restrictions Recommendations Security To execute a stored procedure, using: SQL Server Management Studio Transact-SQL Before You Begin Limitations and Restrictions The calling database collation is used when matching system procedure names. Therefore, always use the exact case of system procedure names in procedure calls. For example, this code will fail if it is executed in the context of a database that has a case-sensitive collation: EXEC SP_heLP; -- Will fail to resolve because SP_heLP does not equal sp_help To display the exact system procedure names, query the sys.system_objects and sys.system_parameters catalog views. If a user-defined procedure has the same name as a system procedure, the user-defined procedure might not ever execute. Recommendations Executing System Stored Procedures System procedures begin with the prefix sp_. Because they logically appear in all user- and system- defined databases, they can be executed from any database without having to fully quality the procedure name. However, we recommend schema-qualifying all system procedure names with the sys schema name to prevent name conflicts. The following example demonstrates the recommended method of calling a system procedure. EXEC sys.sp_who; Executing User-defined Stored Procedures When executing a user-defined procedure, we recommend qualifying the procedure name with the schema name. This practice gives a small performance boost because the Database Engine does not have to search multiple schemas. It also prevents executing the wrong procedure if a database has procedures with the same name in multiple schemas. The following example demonstrates the recommended method to execute a user-defined procedure. Notice that the procedure accepts one input parameter. For information about specifying input and output parameters, see Specify Parameters. USE AdventureWorks2012; GO EXEC dbo.uspGetEmployeeManagers @BusinessEntityID = 50; -OrEXEC AdventureWorks2012.dbo.uspGetEmployeeManagers 50; GO If a nonqualified user-defined procedure is specified, the Database Engine searches for the procedure in the following order: 1. The sys schema of the current database. 2. The caller's default schema if it is executed in a batch or in dynamic SQL. Or, if the nonqualified procedure name appears inside the body of another procedure definition, the schema that contains this other procedure is searched next. 3. The dbo schema in the current database. Executing Stored Procedures Automatically Procedures marked for automatic execution are executed every time SQL Server starts and the master database is recovered during that startup process. Setting up procedures to execute automatically can be useful for performing database maintenance operations or for having procedures run continuously as background processes. Another use for automatic execution is to have the procedure perform system or maintenance tasks in tempdb, such as creating a global temporary table. This makes sure that such a temporary table will always exist when tempdb is re-created during SQL Server startup. A procedure that is automatically executed operates with the same permissions as members of the sysadmin fixed server role. Any error messages generated by the procedure are written to the SQL Server error log. There is no limit to the number of startup procedures you can have, but be aware that each consumes one worker thread while executing. If you must execute multiple procedures at startup but do not need to execute them in parallel, make one procedure the startup procedure and have that procedure call the other procedures. This uses only one worker thread. TIP Do not return any result sets from a procedure that is executed automatically. Because the procedure is being executed by SQL Server instead of an application or user, there is nowhere for the result sets to go. Setting, Clearing, and Controlling Automatic Execution Only the system administrator (sa) can mark a procedure to execute automatically. In addition, the procedure must be in the master database, owned by sa, and cannot have input or output parameters. Use sp_procoption to: 1. Designate an existing procedure as a startup procedure. 2. Stop a procedure from executing at SQL Server startup. Security For more information, see EXECUTE AS (Transact-SQL) and EXECUTE AS Clause (Transact-SQL). Permissions For more information, see the "Permissions" section in EXECUTE (Transact-SQL). Using SQL Server Management Studio To execute a stored procedure 1. In Object Explorer, connect to an instance of the SQL Server Database Engine, expand that instance, and then expand Databases. 2. Expand the database that you want, expand Programmability, and then expand Stored Procedures. 3. Right-click the user-defined stored procedure that you want and click Execute Stored Procedure. 4. In the Execute Procedure dialog box, specify a value for each parameter and whether it should pass a null value. Parameter Indicates the name of the parameter. Data Type Indicates the data type of the parameter. Output Parameter Indicates if this is an output parameter. Pass Null Value Pass a NULL as the value of the parameter. Value Type the value for the parameter when calling the procedure. 5. To execute the stored procedure, click OK. Using Transact-SQL To execute a stored procedure 1. Connect to the Database Engine. 2. From the Standard bar, click New Query. 3. Copy and paste the following example into the query window and click Execute. This example shows how to execute a stored procedure that expects one parameter. The example executes the uspGetEmployeeManagers stored procedure with the value 6 specified as the @EmployeeID parameter. USE AdventureWorks2012; GO EXEC dbo.uspGetEmployeeManagers 6; GO To set or clear a procedure for executing automatically 1. Connect to the Database Engine. 2. From the Standard bar, click New Query. 3. Copy and paste the following example into the query window and click Execute. This example shows how to use sp_procoption to set a procedure for automatic execution. USE AdventureWorks2012; GO EXEC sp_procoption @ProcName = '<procedure name>' , @OptionName = ] 'startup' , @OptionValue = 'on'; To stop a procedure from executing automatically 1. Connect to the Database Engine. 2. From the Standard bar, click New Query. 3. Copy and paste the following example into the query window and click Execute. This example shows how to use sp_procoption to stop a procedure from executing automatically. USE AdventureWorks2012; GO EXEC sp_procoption @ProcName = '<procedure name>' , @OptionValue = 'off'; Example (Transact-SQL ) See Also Specify Parameters Configure the scan for startup procs Server Configuration Option EXECUTE (Transact-SQL) CREATE PROCEDURE (Transact-SQL) Stored Procedures (Database Engine) Specify Parameters 3/24/2017 • 6 min to read • Edit Online By specifying procedure parameters, calling programs are able to pass values into the body of the procedure. Those values can be used for a variety of purposes during procedure execution. Procedure parameters can also return values to the calling program if the parameter is marked as an OUTPUT parameter. A procedure can have a maximum of 2100 parameters; each assigned a name, data type, and direction. Optionally, parameters can be assigned default values. The following section provides information about passing values into parameters and about how each of the parameter attributes is used during a procedure call. Passing Values into Parameters The parameter values supplied with a procedure call must be constants or a variable; a function name cannot be used as a parameter value. Variables can be user-defined or system variables such as @@spid. The following examples demonstrate passing parameter values to the procedure uspGetWhereUsedProductID . They illustrate how to pass parameters as constants and variables and also how to use a variable to pass the value of a function. USE AdventureWorks2012; GO -- Passing values as constants. EXEC dbo.uspGetWhereUsedProductID 819, '20050225'; GO -- Passing values as variables. DECLARE @ProductID int, @CheckDate datetime; SET @ProductID = 819; SET @CheckDate = '20050225'; EXEC dbo.uspGetWhereUsedProductID @ProductID, @CheckDate; GO -- Try to use a function as a parameter value. -- This produces an error message. EXEC dbo.uspGetWhereUsedProductID 819, GETDATE(); GO -- Passing the function value as a variable. DECLARE @CheckDate datetime; SET @CheckDate = GETDATE(); EXEC dbo.uspGetWhereUsedProductID 819, @CheckDate; GO Specifying Parameter Names When creating a procedure and declaring a parameter name, the parameter name must begin with a single @ character and must be unique in the scope of the procedure. Explicitly naming the parameters and assigning the appropriate values to each parameter in a procedure call allows the parameters to be supplied in any order. For example, if the procedure my_proc expects three parameters named @first, @second, and @third, the values passed to the procedure can be assigned to the parameter names, such as: EXECUTE my_proc @second = 2, @first = 1, @third = 3; NOTE If one parameter value is supplied in the form @parameter =value, all subsequent parameters must be supplied in this manner. If the parameter values are not passed in the form @parameter =value, the values must be supplied in the identical order (left to right) as the parameters are listed in the CREATE PROCEDURE statement. WARNING Any parameter passed in the form @parameter =value with the parameter misspelled, will cause SQL Server to generate an error and prevent procedure execution. Specifying Parameter Data Types Parameters must be defined with a data type when they are declared in a CREATE PROCEDURE statement. The data type of a parameter determines the type and range of values that are accepted for the parameter when the procedure is called. For example, if you define a parameter with a tinyint data type, only numeric values ranging from 0 to 255 are accepted when passed into that parameter. An error is returned if a procedure is executed with a value incompatible with the data type. Specifying Parameter Default Values A parameter is considered optional if the parameter has a default value specified when it is declared. It is not necessary to provide a value for an optional parameter in a procedure call. The default value of a parameter is used when: No value for the parameter is specified in the procedure call. The DEFAULT keyword is specified as the value in the procedure call. NOTE If the default value is a character string that contains embedded blanks or punctuation, or if it starts with a number (for example, 6xxx), it must be enclosed in single, straight quotation marks. If no value can be specified appropriately as a default for the parameter, specify NULL as the default. It is a good idea to have the procedure return a customized message if the procedure is executed without a value for the parameter. The following example creates the usp_GetSalesYTD procedure with one input parameter, @SalesPerson . NULL is assigned as the default value for the parameter and is used in error handling statements to return a custom error message for cases when the procedure is executed without a value for the @SalesPerson parameter. USE AdventureWorks2012; GO IF OBJECT_ID('Sales.uspGetSalesYTD', 'P') IS NOT NULL DROP PROCEDURE Sales.uspGetSalesYTD; GO CREATE PROCEDURE Sales.uspGetSalesYTD @SalesPerson nvarchar(50) = NULL -- NULL default value AS SET NOCOUNT ON; -- Validate the @SalesPerson parameter. IF @SalesPerson IS NULL BEGIN PRINT 'ERROR: You must specify the last name of the sales person.' RETURN END -- Get the sales for the specified sales person and -- assign it to the output parameter. SELECT SalesYTD FROM Sales.SalesPerson AS sp JOIN HumanResources.vEmployee AS e ON e.BusinessEntityID = sp.BusinessEntityID WHERE LastName = @SalesPerson; RETURN GO The following example executes the procedure. The first statement executes the procedure without specifying an input value. This causes the error handling statements in the procedure to return the custom error message. The second statement supplies an input value and returns the expected result set. -- Run the procedure without specifying an input value. EXEC Sales.usp_GetSalesYTD; GO -- Run the procedure with an input value. EXEC Sales.usp_GetSalesYTD N'Blythe'; GO Although parameters for which defaults have been supplied can be omitted, the list of parameters can only be truncated. For example, if a procedure has five parameters, both the fourth and the fifth parameters can be omitted. However the fourth parameter cannot be skipped as long as the fifth parameter is included, unless the parameters are supplied in the form @parameter =value. Specifying Parameter Direction The direction of a parameter is either input, a value is passed into the body of the procedure, or output, the procedure returns a value to the calling program. The default is an input parameter. To specify an output parameter, the OUTPUT keyword must be specified in the definition of the parameter in the CREATE PROCEDURE statement. The procedure returns the current value of the output parameter to the calling program when the procedure exits. The calling program must also use the OUTPUT keyword when executing the procedure to save the parameter's value in a variable that can be used in the calling program. The following example creates the Production.usp _ GetList procedure, which returns a list of products that have prices that do not exceed a specified amount. The example shows using multiple SELECT statements and multiple OUTPUT parameters. OUTPUT parameters allow an external procedure, a batch, or more than one Transact-SQL statement to access a value set during the procedure execution. USE AdventureWorks2012; GO IF OBJECT_ID ( 'Production.uspGetList', 'P' ) IS NOT NULL DROP PROCEDURE Production.uspGetList; GO CREATE PROCEDURE Production.uspGetList @Product varchar(40) , @MaxPrice money , @ComparePrice money OUTPUT , @ListPrice money OUT AS SET NOCOUNT ON; SELECT p.[Name] AS Product, p.ListPrice AS 'List Price' FROM Production.Product AS p JOIN Production.ProductSubcategory AS s ON p.ProductSubcategoryID = s.ProductSubcategoryID WHERE s.[Name] LIKE @Product AND p.ListPrice < @MaxPrice; -- Populate the output variable @ListPprice. SET @ListPrice = (SELECT MAX(p.ListPrice) FROM Production.Product AS p JOIN Production.ProductSubcategory AS s ON p.ProductSubcategoryID = s.ProductSubcategoryID WHERE s.[Name] LIKE @Product AND p.ListPrice < @MaxPrice); -- Populate the output variable @compareprice. SET @ComparePrice = @MaxPrice; GO Execute usp_GetList to return a list of Adventure Works products (Bikes) that cost less than $700. The OUTPUT parameters @cost and @compareprices are used with control-of-flow language to return a message in the Messages window. NOTE The OUTPUT variable must be defined during the procedure creation and also during the use of the variable. The parameter name and variable name do not have to match. However, the data type and parameter positioning must match (unless @listprice= variable is used). DECLARE @ComparePrice money, @Cost money ; EXECUTE Production.uspGetList '%Bikes%', 700, @ComparePrice OUT, @Cost OUTPUT IF @Cost <= @ComparePrice BEGIN PRINT 'These products can be purchased for less than $'+RTRIM(CAST(@ComparePrice AS varchar(20)))+'.' END ELSE PRINT 'The prices for all products in this category exceed $'+ RTRIM(CAST(@ComparePrice AS varchar(20)))+'.'; Here is the partial result set: Product -------------------------------------------------Road-750 Black, 58 Mountain-500 Silver, 40 Mountain-500 Silver, 42 ... Road-750 Black, 48 Road-750 Black, 52 (14 row(s) affected) These items can be purchased for less than $700.00. See Also CREATE PROCEDURE (Transact-SQL) List Price -----------------539.99 564.99 564.99 539.99 539.99 Grant Permissions on a Stored Procedure 3/24/2017 • 1 min to read • Edit Online This topic describes how to grant permissions on a stored procedure in SQL Server 2016 by using SQL Server Management Studio or Transact-SQL. Permissions can be granted to an existing user, database role, or application role in the database. In This Topic Before you begin: Limitations and Restrictions Security To grant permissions on a stored procedure, using: SQL Server Management Studio Transact-SQL Before You Begin Limitations and Restrictions You cannot use SQL Server Management Studio to grant permissions on system procedures or system functions. Use GRANT Object Permissions instead. Security Permissions The grantor (or the principal specified with the AS option) must have either the permission itself with GRANT OPTION, or a higher permission that implies the permission being granted. Requires ALTER permission on the schema to which the procedure belongs, or CONTROL permission on the procedure. For more information, see GRANT Object Permissions (Transact-SQL). Using SQL Server Management Studio To grant permissions on a stored procedure 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the database in which the procedure belongs, and then expand Programmability. 3. Expand Stored Procedures, right-click the procedure to grant permissions on, and then click Properties. 4. From Stored Procedure Properties, select the Permissions page. 5. To grant permissions to a user, database role, or application role, click Search. 6. In Select Users or Roles, click Object Types to add or clear the users and roles you want. 7. Click Browse to display the list of users or roles. Select the users or roles to whom permissions should be granted. 8. In the Explicit Permissions grid, select the permissions to grant to the specified user or role. For a description of the permissions, see Permissions (Database Engine). Selecting Grant indicates the grantee will be given the specified permission. Selecting Grant With indicates that the grantee will also be able to grant the specified permission to other principals. Using Transact-SQL To grant permissions on a stored procedure 1. Connect to the Database Engine. 2. From the Standard bar, click New Query. 3. Copy and paste the following example into the query window and click Execute. This example grants EXECUTE permission on the stored procedure HumanResources.uspUpdateEmployeeHireInfo to an application role named Recruiting11 . USE AdventureWorks2012; GRANT EXECUTE ON OBJECT::HumanResources.uspUpdateEmployeeHireInfo TO Recruiting11; GO See Also sys.fn_builtin_permissions (Transact-SQL) GRANT Object Permissions (Transact-SQL) Create a Stored Procedure Modify a Stored Procedure Delete a Stored Procedure Rename a Stored Procedure Parameters 3/24/2017 • 2 min to read • Edit Online Parameters are used to exchange data between stored procedures and functions and the application or tool that called the stored procedure or function: Input parameters allow the caller to pass a data value to the stored procedure or function. Output parameters allow the stored procedure to pass a data value or a cursor variable back to the caller. Userdefined functions cannot specify output parameters. Every stored procedure returns an integer return code to the caller. If the stored procedure does not explicitly set a value for the return code, the return code is 0. The following stored procedure shows the use of an input parameter, an output parameter, and a return code: -- Create a procedure that takes one input parameter and returns one output parameter and a return code. CREATE PROCEDURE SampleProcedure @EmployeeIDParm INT, @MaxTotal INT OUTPUT AS -- Declare and initialize a variable to hold @@ERROR. DECLARE @ErrorSave INT SET @ErrorSave = 0 -- Do a SELECT using the input parameter. SELECT FirstName, LastName, JobTitle FROM HumanResources.vEmployee WHERE EmployeeID = @EmployeeIDParm -- Save any nonzero @@ERROR value. IF (@@ERROR <> 0) SET @ErrorSave = @@ERROR -- Set a value in the output parameter. SELECT @MaxTotal = MAX(TotalDue) FROM Sales.SalesOrderHeader; IF (@@ERROR <> 0) SET @ErrorSave = @@ERROR -- Returns 0 if neither SELECT statement had an error; otherwise, returns the last error. RETURN @ErrorSave GO When a stored procedure or function is executed, input parameters can either have their value set to a constant or use the value of a variable. Output parameters and return codes must return their values into a variable. Parameters and return codes can exchange data values with either Transact-SQL variables or application variables. If a stored procedure is called from a batch or script, the parameters and return code values can use Transact-SQL variables defined in the same batch. The following example is a batch that executes the procedure created earlier. The input parameter is specified as a constant and the output parameter and return code place their values in Transact-SQL variables: -- Declare the variables for the return code and output parameter. DECLARE @ReturnCode INT DECLARE @MaxTotalVariable INT -- Execute the stored procedure and specify which variables -- are to receive the output parameter and return code values. EXEC @ReturnCode = SampleProcedure @EmployeeIDParm = 19, @MaxTotal = @MaxTotalVariable OUTPUT -- Show the values returned. PRINT ' ' PRINT 'Return code = ' + CAST(@ReturnCode AS CHAR(10)) PRINT 'Maximum Quantity = ' + CAST(@MaxTotalVariable AS CHAR(10)) GO An application can use parameter markers bound to program variables to exchange data between application variables, parameters, and return codes. See Also CREATE PROCEDURE (Transact-SQL) DECLARE @local_variable (Transact-SQL) CREATE FUNCTION (Transact-SQL) Parameters and Execution Plan Reuse section Variables (Transact-SQL) Stored Procedure Properties (General Page) 3/24/2017 • 1 min to read • Edit Online Displays information about a stored procedure. All information is read-only. Options Database The name of the database containing this stored procedure. Server The name of the current server instance. User The name of the user of this connection. Created date Displays the date the stored procedure was created. Name The name of the current stored procedure. Schema Displays the schema that owns the stored procedure. System object Indicates whether the stored procedure is a system object. Values are True and False. ANSI NULLs Indicates if the object was created with the ANSI NULLs option. Encrypted Indicates whether the stored procedure is encrypted. Values are True and False. For replication Indicates if the object was created with the FOR REPLICATION option. Quoted identifier Indicates if the object was created with the quoted identifier option. Recompile Indicates if the object was created with the RECOMPILE option. See Also Stored Procedures (Database Engine) CREATE PROCEDURE (Transact-SQL) ALTER PROCEDURE (Transact-SQL) Return Data from a Stored Procedure 3/24/2017 • 8 min to read • Edit Online There are two ways of returning result sets or data from a procedure to a calling program: output parameters and return codes. This topic provides information on both approaches. Returning Data Using an Output Parameter If you specify the OUTPUT keyword for a parameter in the procedure definition, the procedure can return the current value of the parameter to the calling program when the procedure exits. To save the value of the parameter in a variable that can be used in the calling program, the calling program must use the OUTPUT keyword when executing the procedure. For more information about what data types can be used as output parameters, see CREATE PROCEDURE (Transact-SQL). Examples of Output Parameter The following example shows a procedure with an input and an output parameter. The @SalesPerson parameter would receive an input value specified by the calling program. The SELECT statement uses the value passed into the input parameter to obtain the correct SalesYTD value. The SELECT statement also assigns the value to the @SalesYTD output parameter, which returns the value to the calling program when the procedure exits. USE AdventureWorks2012; GO IF OBJECT_ID('Sales.uspGetEmployeeSalesYTD', 'P') IS NOT NULL DROP PROCEDURE Sales.uspGetEmployeeSalesYTD; GO CREATE PROCEDURE Sales.uspGetEmployeeSalesYTD @SalesPerson nvarchar(50), @SalesYTD money OUTPUT AS SET NOCOUNT ON; SELECT @SalesYTD = SalesYTD FROM Sales.SalesPerson AS sp JOIN HumanResources.vEmployee AS e ON e.BusinessEntityID = sp.BusinessEntityID WHERE LastName = @SalesPerson; RETURN GO The following example calls the procedure created in the first example and saves the output value returned from the called procedure in the @SalesYTD variable, which is local to the calling program. -- Declare the variable to receive the output value of the procedure. DECLARE @SalesYTDBySalesPerson money; -- Execute the procedure specifying a last name for the input parameter -- and saving the output value in the variable @SalesYTDBySalesPerson EXECUTE Sales.uspGetEmployeeSalesYTD N'Blythe', @SalesYTD = @SalesYTDBySalesPerson OUTPUT; -- Display the value returned by the procedure. PRINT 'Year-to-date sales for this employee is ' + convert(varchar(10),@SalesYTDBySalesPerson); GO Input values can also be specified for OUTPUT parameters when the procedure is executed. This allows the procedure to receive a value from the calling program, change or perform operations with the value, and then return the new value to the calling program. In the previous example, the @SalesYTDBySalesPerson variable can be assigned a value before the program calls the Sales.uspGetEmployeeSalesYTD procedure. The execute statement would pass the @SalesYTDBySalesPerson variable value into the @SalesYTD OUTPUT parameter. Then in the procedure body, the value could be used for calculations that generate a new value. The new value would be passed back out of the procedure through the OUTPUT parameter, updating the value in the @SalesYTDBySalesPerson variable when the procedure exits. This is often referred to as "pass-by-reference capability." If you specify OUTPUT for a parameter when you call a procedure and that parameter is not defined by using OUTPUT in the procedure definition, you get an error message. However, you can execute a procedure with output parameters and not specify OUTPUT when executing the procedure. No error is returned, but you cannot use the output value in the calling program. Using the Cursor Data Type in OUTPUT Parameters Transact-SQL procedures can use the cursor data type only for OUTPUT parameters. If the cursor data type is specified for a parameter, both the VARYING and OUTPUT keywords must be specified for that parameter in the procedure definition. A parameter can be specified as only OUTPUT but if the VARYING keyword is specified in the parameter declaration, the data type must be cursor and the OUTPUT keyword must also be specified. NOTE The cursor data type cannot be bound to application variables through the database APIs such as OLE DB, ODBC, ADO, and DB-Library. Because OUTPUT parameters must be bound before an application can execute a procedure, procedures with cursor OUTPUT parameters cannot be called from the database APIs. These procedures can be called from Transact-SQL batches, procedures, or triggers only when the cursor OUTPUT variable is assigned to a Transact-SQL local cursor variable. Rules for Cursor Output Parameters The following rules pertain to cursor output parameters when the procedure is executed: For a forward-only cursor, the rows returned in the cursor's result set are only those rows at and beyond the position of the cursor at the conclusion of the procedure execution, for example: A nonscrollable cursor is opened in a procedure on a result set named RS of 100 rows. The procedure fetches the first 5 rows of result set RS. The procedure returns to its caller. The result set RS returned to the caller consists of rows from 6 through 100 of RS, and the cursor in the caller is positioned before the first row of RS. For a forward-only cursor, if the cursor is positioned before the first row when the procedure exits, the entire result set is returned to the calling batch, procedure, or trigger. When returned, the cursor position is set before the first row. For a forward-only cursor, if the cursor is positioned beyond the end of the last row when the procedure exits, an empty result set is returned to the calling batch, procedure, or trigger. NOTE An empty result set is not the same as a null value. For a scrollable cursor, all the rows in the result set are returned to the calling batch, procedure, or trigger when the procedure exits. When returned, the cursor position is left at the position of the last fetch executed in the procedure. For any type of cursor, if the cursor is closed, then a null value is passed back to the calling batch, procedure, or trigger. This will also be the case if a cursor is assigned to a parameter, but that cursor is never opened. NOTE The closed state matters only at return time. For example, it is valid to close a cursor part of the way through the procedure, to open it again later in the procedure, and return that cursor's result set to the calling batch, procedure, or trigger. Examples of Cursor Output Parameters In the following example, a procedure is created that specified an output parameter, cursor data type. The procedure is then called in a batch. @currency _ cursor using the First, create the procedure that declares and then opens a cursor on the Currency table. USE AdventureWorks2012; GO IF OBJECT_ID ( 'dbo.uspCurrencyCursor', 'P' ) IS NOT NULL DROP PROCEDURE dbo.uspCurrencyCursor; GO CREATE PROCEDURE dbo.uspCurrencyCursor @CurrencyCursor CURSOR VARYING OUTPUT AS SET NOCOUNT ON; SET @CurrencyCursor = CURSOR FORWARD_ONLY STATIC FOR SELECT CurrencyCode, Name FROM Sales.Currency; OPEN @CurrencyCursor; GO Next, execute a batch that declares a local cursor variable, executes the procedure to assign the cursor to the local variable, and then fetches the rows from the cursor. USE AdventureWorks2012; GO DECLARE @MyCursor CURSOR; EXEC dbo.uspCurrencyCursor @CurrencyCursor = @MyCursor OUTPUT; WHILE (@@FETCH_STATUS = 0) BEGIN; FETCH NEXT FROM @MyCursor; END; CLOSE @MyCursor; DEALLOCATE @MyCursor; GO Returning Data Using a Return Code A procedure can return an integer value called a return code to indicate the execution status of a procedure. You specify the return code for a procedure using the RETURN statement. As with OUTPUT parameters, you must save the return code in a variable when the procedure is executed in order to use the return code value in the calling program. For example, the assignment variable @result of data type int is used to store the return code from the procedure my_proc , such as: DECLARE @result int; EXECUTE @result = my_proc; Return codes are commonly used in control-of-flow blocks within procedures to set the return code value for each possible error situation. You can use the @@ERROR function after a Transact-SQL statement to detect whether an error occurred during the execution of the statement. Examples of Return Codes The following example shows the usp_GetSalesYTD procedure with error handling that sets special return code values for various errors. The following table shows the integer value that is assigned by the procedure to each possible error, and the corresponding meaning for each value. RETURN CODE VALUE MEANING 0 Successful execution. 1 Required parameter value is not specified. 2 Specified parameter value is not valid. 3 Error has occurred getting sales value. 4 NULL sales value found for the salesperson. USE AdventureWorks2012; GO IF OBJECT_ID('Sales.usp_GetSalesYTD', 'P') IS NOT NULL DROP PROCEDURE Sales.usp_GetSalesYTD; GO CREATE PROCEDURE Sales.usp_GetSalesYTD @SalesPerson nvarchar(50) = NULL, -- NULL default value @SalesYTD money = NULL OUTPUT AS -- Validate the @SalesPerson parameter. IF @SalesPerson IS NULL BEGIN PRINT 'ERROR: You must specify a last name for the sales person.' RETURN(1) END ELSE BEGIN -- Make sure the value is valid. IF (SELECT COUNT(*) FROM HumanResources.vEmployee WHERE LastName = @SalesPerson) = 0 RETURN(2) END -- Get the sales for the specified name and -- assign it to the output parameter. SELECT @SalesYTD = SalesYTD FROM Sales.SalesPerson AS sp JOIN HumanResources.vEmployee AS e ON e.BusinessEntityID = sp.BusinessEntityID WHERE LastName = @SalesPerson; -- Check for SQL Server errors. IF @@ERROR <> 0 BEGIN RETURN(3) END ELSE BEGIN -- Check to see if the ytd_sales value is NULL. IF @SalesYTD IS NULL RETURN(4) ELSE -- SUCCESS!! RETURN(0) END -- Run the stored procedure without specifying an input value. EXEC Sales.usp_GetSalesYTD; GO -- Run the stored procedure with an input value. DECLARE @SalesYTDForSalesPerson money, @ret_code int; -- Execute the procedure specifying a last name for the input parameter -- and saving the output value in the variable @SalesYTD EXECUTE Sales.usp_GetSalesYTD N'Blythe', @SalesYTD = @SalesYTDForSalesPerson OUTPUT; PRINT N'Year-to-date sales for this employee is ' + CONVERT(varchar(10), @SalesYTDForSalesPerson); The following example creates a program to handle the return codes that are returned from the procedure. usp_GetSalesYTD -- Declare the variables to receive the output value and return code -- of the procedure. DECLARE @SalesYTDForSalesPerson money, @ret_code int; -- Execute the procedure with a title_id value -- and save the output value and return code in variables. EXECUTE @ret_code = Sales.usp_GetSalesYTD N'Blythe', @SalesYTD = @SalesYTDForSalesPerson OUTPUT; -- Check the return codes. IF @ret_code = 0 BEGIN PRINT 'Procedure executed successfully' -- Display the value returned by the procedure. PRINT 'Year-to-date sales for this employee is ' + CONVERT(varchar(10),@SalesYTDForSalesPerson) END ELSE IF @ret_code = 1 PRINT 'ERROR: You must specify a last name for the sales person.' ELSE IF @ret_code = 2 PRINT 'EERROR: You must enter a valid last name for the sales person.' ELSE IF @ret_code = 3 PRINT 'ERROR: An error occurred getting sales value.' ELSE IF @ret_code = 4 PRINT 'ERROR: No sales recorded for this employee.' GO See Also DECLARE @local_variable (Transact-SQL) PRINT (Transact-SQL) SET @local_variable (Transact-SQL) Cursors RETURN (Transact-SQL) @@ERROR (Transact-SQL) Recompile a Stored Procedure 3/24/2017 • 4 min to read • Edit Online This topic describes how to recompile a stored procedure in SQL Server 2016 by using Transact-SQL. There are three ways to do this: WITH RECOMPILE option in the procedure definition or when the procedure is called, the RECOMPILE query hint on individual statements, or by using the sp_recompile system stored procedure. This topic describes using the WITH RECOMPILE option when creating a procedure definition and executing an existing procedure. It also describes using the sp_recompile system stored procedure to recompile an existing procedure. In This Topic Before you begin: Recommendations Security To recompile a stored procedure, using: Transact-SQL Before You Begin Recommendations When a procedure is compiled for the first time or recompiled, the procedure’s query plan is optimized for the current state of the database and its objects. If a database undergoes significant changes to its data or structure, recompiling a procedure updates and optimizes the procedure’s query plan for those changes. This can improve the procedure’s processing performance. There are times when procedure recompilation must be forced and other times when it occurs automatically. Automatic recompiling occurs whenever SQL Server is restarted. It also occurs if an underlying table referenced by the procedure has undergone physical design changes. Another reason to force a procedure to recompile is to counteract the "parameter sniffing" behavior of procedure compilation. When SQL Server executes procedures, any parameter values that are used by the procedure when it compiles are included as part of generating the query plan. If these values represent the typical ones with which the procedure is subsequently called, then the procedure benefits from the query plan every time that it compiles and executes. If parameter values on the procedure are frequently atypical, forcing a recompile of the procedure and a new plan based on different parameter values can improve performance. SQL Server features statement-level recompilation of procedures. When SQL Server recompiles stored procedures, only the statement that caused the recompilation is compiled, instead of the complete procedure. If certain queries in a procedure regularly use atypical or temporary values, procedure performance can be improved by using the RECOMPILE query hint inside those queries. Since only the queries using the query hint will be recompiled instead of the complete procedure, SQL Server's statement-level recompilation behavior is mimicked. But in addition to using the procedure's current parameter values, the RECOMPILE query hint also uses the values of any local variables inside the stored procedure when you compile the statement. For more information, see Query Hint (Transact-SQL). Security Permissions WITH RECOMPILE Option If this option is used when the procedure definition is created, it requires CREATE PROCEDURE permission in the database and ALTER permission on the schema in which the procedure is being created. If this option is used in an EXECUTE statement, it requires EXECUTE permissions on the procedure. Permissions are not required on the EXECUTE statement itself but execute permissions are required on the procedure referenced in the EXECUTE statement. For more information, see EXECUTE (Transact-SQL). RECOMPILE Query Hint This feature is used when the procedure is created and the hint is included in Transact-SQL statements in the procedure. Therefore, it requires CREATE PROCEDURE permission in the database and ALTER permission on the schema in which the procedure is being created. sp_recompile System Stored Procedure Requires ALTER permission on the specified procedure. Using Transact-SQL To recompile a stored procedure by using the WITH RECOMPILE option 1. Connect to the Database Engine. 2. From the Standard bar, click New Query. 3. Copy and paste the following example into the query window and click Execute. This example creates the procedure definition. USE AdventureWorks2012; GO IF OBJECT_ID ( 'dbo.uspProductByVendor', 'P' ) IS NOT NULL DROP PROCEDURE dbo.uspProductByVendor; GO CREATE PROCEDURE dbo.uspProductByVendor @Name varchar(30) = '%' WITH RECOMPILE AS SET NOCOUNT ON; SELECT v.Name AS 'Vendor name', p.Name AS 'Product name' FROM Purchasing.Vendor AS v JOIN Purchasing.ProductVendor AS pv ON v.BusinessEntityID = pv.BusinessEntityID JOIN Production.Product AS p ON pv.ProductID = p.ProductID WHERE v.Name LIKE @Name; To recompile a stored procedure by using the WITH RECOMPILE option 1. Connect to the Database Engine. 2. From the Standard bar, click New Query. 3. Copy and paste the following example into the query window and click Execute. This example creates a simple procedure that returns all employees (first and last names supplied), their job titles, and their department names from a view. And then copy and paste the second code example into the query window and click Execute. This executes the procedure and recompiles the procedure’s query plan. USE AdventureWorks2012; GO EXECUTE HumanResources.uspGetAllEmployees WITH RECOMPILE; GO To recompile a stored procedure by using sp_recompile 1. Connect to the Database Engine. 2. From the Standard bar, click New Query. 3. Copy and paste the following example into the query window and click Execute. This example creates a simple procedure that returns all employees (first and last names supplied), their job titles, and their department names from a view. Then, copy and paste the following example into the query window and click Execute. This does not execute the procedure but it does mark the procedure to be recompiled so that its query plan is updated the next time that the procedure is executed. USE AdventureWorks2012; GO EXEC sp_recompile N'HumanResources.uspGetAllEmployees'; GO See Also Create a Stored Procedure Modify a Stored Procedure Rename a Stored Procedure View the Definition of a Stored Procedure View the Dependencies of a Stored Procedure DROP PROCEDURE (Transact-SQL) Rename a Stored Procedure 3/24/2017 • 2 min to read • Edit Online This topic describes how to rename a stored procedure in SQL Server 2016 by using SQL Server Management Studio or Transact-SQL. In This Topic Before you begin: Limitations and Restrictions Security To rename a stored procedure, using: SQL Server Management Studio Transact-SQL Before You Begin Limitations and Restrictions Procedure names must comply with the rules for identifiers. Renaming a stored procedure will not change the name of the corresponding object name in the definition column of the sys.sql_modules catalog view. Therefore, we recommend that you do not rename this object type. Instead, drop and re-create the stored procedure with its new name. Changing the name or definition of a procedure can cause dependent objects to fail when the objects are not updated to reflect the changes that have been made to the procedure. For more information, see View the Dependencies of a Stored Procedure. Security Permissions CREATE PROCEDURE Requires CREATE PROCEDURE permission in the database and ALTER permission on the schema in which the procedure is being created, or requires membership in the db_ddladmin fixed database role. ALTER PROCEDURE Requires ALTER permission on the procedure or requires membership in the db_ddladmin fixed database role. Using SQL Server Management Studio To rename a stored procedure 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the database in which the procedure belongs, and then expand Programmability. 3. Determine the dependencies of the stored procedure. 4. Expand Stored Procedures, right-click the procedure to rename, and then click Rename. 5. Modify the procedure name. 6. Modify the procedure name referenced in any dependent objects or scripts. Using Transact-SQL To rename a stored procedure 1. Connect to the Database Engine. 2. From the Standard bar, click New Query. 3. Copy and paste the following example into the query window and click Execute. This example shows how to rename a procedure by dropping the procedure and re-creating the procedure with a new name. The first example creates the stored procedure 'HumanResources.uspGetAllEmployeesTest . The second example renames the stored procedure to HumanResources.uspEveryEmployeeTest . --Create the stored procedure. USE AdventureWorks2012; GO IF OBJECT_ID ( 'HumanResources.uspGetAllEmployeesTest', 'P' ) IS NOT NULL DROP PROCEDURE HumanResources.uspGetAllEmployeesTest; GO CREATE PROCEDURE HumanResources.uspGetAllEmployeesTest AS SET NOCOUNT ON; SELECT LastName, FirstName, Department FROM HumanResources.vEmployeeDepartmentHistory; GO --Rename the stored procedure. USE AdventureWorks2012; GO IF OBJECT_ID ( 'HumanResources.uspGetAllEmployeesTest', 'P' ) IS NOT NULL DROP PROCEDURE HumanResources.uspGetAllEmployeesTest; GO CREATE PROCEDURE HumanResources.uspEveryEmployeeTest AS SET NOCOUNT ON; SELECT LastName, FirstName, Department FROM HumanResources.vEmployeeDepartmentHistory; GO See Also ALTER PROCEDURE (Transact-SQL) CREATE PROCEDURE (Transact-SQL) Create a Stored Procedure Modify a Stored Procedure Delete a Stored Procedure View the Definition of a Stored Procedure View the Dependencies of a Stored Procedure View the Definition of a Stored Procedure 3/24/2017 • 2 min to read • Edit Online You can view the definition of a stored procedure in SQL Server Management Studio using Object Explorer menu options or in the Query Editor using Transact-SQL. This topic describes how to view the definition of procedure in Object Explorer and by using a system stored procedure, system function, and object catalog view in the Query Editor. Before you begin: Security To view the definition of a procedure, using: SQL Server Management Studio, Transact-SQL Before You Begin Security Permissions System Stored Procedure: sp_helptext Requires membership in the public role. System object definitions are publicly visible. The definition of user objects is visible to the object owner or grantees that have any one of the following permissions: ALTER, CONTROL, TAKE OWNERSHIP, or VIEW DEFINITION. System Function: OBJECT_DEFINITION System object definitions are publicly visible. The definition of user objects is visible to the object owner or grantees that have any one of the following permissions: ALTER, CONTROL, TAKE OWNERSHIP, or VIEW DEFINITION. These permissions are implicitly held by members of the db_owner, db_ddladmin, and db_securityadmin fixed database roles. Object Catalog View: sys.sql_modules The visibility of the metadata in catalog views is limited to securables that a user either owns or on which the user has been granted some permission. For more information, see Metadata Visibility Configuration. How to View the Definition of a Stored Procedure You can use one of the following: SQL Server Management Studio Transact-SQL Using SQL Server Management Studio To view the definition a procedure in Object Explorer 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the database in which the procedure belongs, and then expand Programmability. 3. Expand Stored Procedures, right-click the procedure and then click Script Stored Procedure as, and then click one of the following: Create To, Alter To, or Drop and Create To. 4. Select New Query Editor Window. This will display the procedure definition. Using Transact-SQL To view the definition of a procedure in Query Editor System Stored Procedure: sp_helptext 1. In Object Explorer, connect to an instance of the Database Engine. 1. On the toolbar, click New Query. 2. In the query window, enter the following statement that uses the sp_helptext system stored procedure. Change the database name and stored procedure name to reference the database and stored procedure that you want. USE AdventureWorks2012; GO EXEC sp_helptext N'AdventureWorks2012.dbo.uspLogError'; System Function: OBJECT_DEFINITION a. In Object Explorer, connect to an instance of the Database Engine. 3. On the toolbar, click New Query. 4. In the query window, enter the following statements that use the OBJECT_DEFINITION system function. Change the database name and stored procedure name to reference the database and stored procedure that you want. USE AdventureWorks2012; GO SELECT OBJECT_DEFINITION (OBJECT_ID(N'AdventureWorks2012.dbo.uspLogError')); Object Catalog View: sys.sql_modules a. In Object Explorer, connect to an instance of the Database Engine. 5. On the toolbar, click New Query. 6. In the query window, enter the following statements that use the sys.sql_modules catalog view. Change the database name and stored procedure name to reference the database and stored procedure that you want. USE AdventureWorks2012; GO SELECT definition FROM sys.sql_modules WHERE object_id = (OBJECT_ID(N'AdventureWorks2012.dbo.uspLogError')); See Also Create a Stored Procedure Modify a Stored Procedure Delete a Stored Procedure Rename a Stored Procedure OBJECT_DEFINITION (Transact-SQL) sys.sql_modules (Transact-SQL) sp_helptext (Transact-SQL) OBJECT_ID (Transact-SQL) View the Dependencies of a Stored Procedure 3/24/2017 • 5 min to read • Edit Online This topic describes how to view stored procedure dependencies in SQL Server 2016 by using SQL Server Management Studio or Transact-SQL. Before you begin: Limitations and Restrictions, Security To view the dependencies of a procedure, using: SQL Server Management Studio, Transact-SQL Before You Begin Limitations and Restrictions Security Permissions System Function: sys.dm_sql_referencing_entities Requires CONTROL permission on the referenced entity and SELECT permission on sys.dm_sql_referencing_entities. When the referenced entity is a partition function, CONTROL permission on the database is required. By default, SELECT permission is granted to public. System Function: sys.dm_sql_referenced_entities Requires SELECT permission on sys.dm_sql_referenced_entities and VIEW DEFINITION permission on the referencing entity. By default, SELECT permission is granted to public. Requires VIEW DEFINITION permission on the database or ALTER DATABASE DDL TRIGGER permission on the database when the referencing entity is a database-level DDL trigger. Requires VIEW ANY DEFINITION permission on the server when the referencing entity is a server-level DDL trigger. Object Catalog View: sys.sql_expression_dependencies Requires VIEW DEFINITION permission on the database and SELECT permission on sys.sql_expression_dependencies for the database. By default, SELECT permission is granted only to members of the db_owner fixed database role. When SELECT and VIEW DEFINITION permissions are granted to another user, the grantee can view all dependencies in the database. How to View the Dependencies of a Stored Procedure You can use one of the following: SQL Server Management Studio Transact-SQL Using SQL Server Management Studio To view the dependencies of a procedure in Object Explorer 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the database in which the procedure belongs, and then expand Programmability. 3. Expand Stored Procedures, right-click the procedure and then click View Dependencies. 4. View the list of objects that depend on the procedure. 5. View the list of objects on which the procedure depends. 6. Click OK. Using Transact-SQL To view the dependencies of a procedure in Query Editor System Function: sys.dm_sql_referencing_entities This function is used to display the objects that depend on a procedure. 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the database in which the procedure belongs. 3. Click on New Query under the File menu. 4. Copy and paste the following examples into the query editor. The first example creates the uspVendorAllInfo procedure, which returns the names of all the vendors in the Adventure Works Cycles database, the products they supply, their credit ratings, and their availability. USE AdventureWorks2008R2; GO IF OBJECT_ID ( 'Purchasing.uspVendorAllInfo', 'P' ) IS NOT NULL DROP PROCEDURE Purchasing.uspVendorAllInfo; GO CREATE PROCEDURE Purchasing.uspVendorAllInfo WITH EXECUTE AS CALLER AS SET NOCOUNT ON; SELECT v.Name AS Vendor, p.Name AS 'Product name', v.CreditRating AS 'Rating', v.ActiveFlag AS Availability FROM Purchasing.Vendor v INNER JOIN Purchasing.ProductVendor pv ON v.BusinessEntityID = pv.BusinessEntityID INNER JOIN Production.Product p ON pv.ProductID = p.ProductID ORDER BY v.Name ASC; GO 5. After the procedure is created, the second example uses the sys.dm_sql_referencing_entities function to display the objects that depend on the procedure. USE AdventureWorks2012; GO SELECT referencing_schema_name, referencing_entity_name, referencing_id, referencing_class_desc, is_caller_dependent FROM sys.dm_sql_referencing_entities ('Purchasing.uspVendorAllInfo', 'OBJECT'); GO System Function: sys.dm_sql_referenced_entities This function is used to display the objects a procedure depends on. 6. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 7. Expand Databases, expand the database in which the procedure belongs. 8. Click on New Query under the File menu. 9. Copy and paste the following examples into the query editor. The first example creates the uspVendorAllInfo procedure, which returns the names of all the vendors in the Adventure Works Cycles database, the products they supply, their credit ratings, and their availability. USE AdventureWorks2008R2; GO IF OBJECT_ID ( 'Purchasing.uspVendorAllInfo', 'P' ) IS NOT NULL DROP PROCEDURE Purchasing.uspVendorAllInfo; GO CREATE PROCEDURE Purchasing.uspVendorAllInfo WITH EXECUTE AS CALLER AS SET NOCOUNT ON; SELECT v.Name AS Vendor, p.Name AS 'Product name', v.CreditRating AS 'Rating', v.ActiveFlag AS Availability FROM Purchasing.Vendor v INNER JOIN Purchasing.ProductVendor pv ON v.BusinessEntityID = pv.BusinessEntityID INNER JOIN Production.Product p ON pv.ProductID = p.ProductID ORDER BY v.Name ASC; GO 10. After the procedure is created, the second example uses the sys.dm_sql_referenced_entities function to display the objects that the procedure depends on. USE AdventureWorks2012; GO SELECT referenced_schema_name, referenced_entity_name, referenced_minor_name,referenced_minor_id, referenced_class_desc, is_caller_dependent, is_ambiguous FROM sys.dm_sql_referencing_entities ('Purchasing.uspVendorAllInfo', 'OBJECT'); GO Object Catalog View: sys.sql_expression_dependencies This view can be used to display objects that a procedure depends on or that depend on a procedure. Displaying the objects that depend on a procedure. a. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 11. Expand Databases, expand the database in which the procedure belongs. 12. Click on New Query under the File menu. 13. Copy and paste the following examples into the query editor. The first example creates the uspVendorAllInfo procedure, which returns the names of all the vendors in the Adventure Works Cycles database, the products they supply, their credit ratings, and their availability. USE AdventureWorks2008R2; GO IF OBJECT_ID ( 'Purchasing.uspVendorAllInfo', 'P' ) IS NOT NULL DROP PROCEDURE Purchasing.uspVendorAllInfo; GO CREATE PROCEDURE Purchasing.uspVendorAllInfo WITH EXECUTE AS CALLER AS SET NOCOUNT ON; SELECT v.Name AS Vendor, p.Name AS 'Product name', v.CreditRating AS 'Rating', v.ActiveFlag AS Availability FROM Purchasing.Vendor v INNER JOIN Purchasing.ProductVendor pv ON v.BusinessEntityID = pv.BusinessEntityID INNER JOIN Production.Product p ON pv.ProductID = p.ProductID ORDER BY v.Name ASC; GO 14. After the procedure is created, the second example uses the sys.sql_expression_dependencies view to display the objects that depend on the procedure. USE AdventureWorks2012; GO SELECT OBJECT_SCHEMA_NAME ( referencing_id ) AS referencing_schema_name, OBJECT_NAME(referencing_id) AS referencing_entity_name, o.type_desc AS referencing_desciption, COALESCE(COL_NAME(referencing_id, referencing_minor_id), '(n/a)') AS referencing_minor_id, referencing_class_desc, referenced_class_desc, referenced_server_name, referenced_database_name, referenced_schema_name, referenced_entity_name, COALESCE(COL_NAME(referenced_id, referenced_minor_id), '(n/a)') AS referenced_column_name, is_caller_dependent, is_ambiguous FROM sys.sql_expression_dependencies AS sed INNER JOIN sys.objects AS o ON sed.referencing_id = o.object_id WHERE referenced_id = OBJECT_ID(N'Purchasing.uspVendorAllInfo') GO Displaying the objects a procedure depends on. a. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 15. Expand Databases, expand the database in which the procedure belongs. 16. Click on New Query under the File menu. 17. Copy and paste the following examples into the query editor. The first example creates the uspVendorAllInfo procedure, which returns the names of all the vendors in the Adventure Works Cycles database, the products they supply, their credit ratings, and their availability. USE AdventureWorks2008R2; GO IF OBJECT_ID ( 'Purchasing.uspVendorAllInfo', 'P' ) IS NOT NULL DROP PROCEDURE Purchasing.uspVendorAllInfo; GO CREATE PROCEDURE Purchasing.uspVendorAllInfo WITH EXECUTE AS CALLER AS SET NOCOUNT ON; SELECT v.Name AS Vendor, p.Name AS 'Product name', v.CreditRating AS 'Rating', v.ActiveFlag AS Availability FROM Purchasing.Vendor v INNER JOIN Purchasing.ProductVendor pv ON v.BusinessEntityID = pv.BusinessEntityID INNER JOIN Production.Product p ON pv.ProductID = p.ProductID ORDER BY v.Name ASC; GO 18. After the procedure is created, the second example uses the sys.sql_expression_dependencies view to display the objects the procedure depends on. USE AdventureWorks2012; GO SELECT OBJECT_NAME(referencing_id) AS referencing_entity_name, o.type_desc AS referencing_desciption, COALESCE(COL_NAME(referencing_id, referencing_minor_id), '(n/a)') AS referencing_minor_id, referencing_class_desc, referenced_class_desc, referenced_server_name, referenced_database_name, referenced_schema_name, referenced_entity_name, COALESCE(COL_NAME(referenced_id, referenced_minor_id), '(n/a)') AS referenced_column_name, is_caller_dependent, is_ambiguous FROM sys.sql_expression_dependencies AS sed INNER JOIN sys.objects AS o ON sed.referencing_id = o.object_id WHERE referencing_id = OBJECT_ID(N'Purchasing.uspVendorAllInfo'); GO See Also Rename a Stored Procedure sys.dm_sql_referencing_entities (Transact-SQL) sys.dm_sql_referenced_entities (Transact-SQL) sys.sql_expression_dependencies (Transact-SQL) OLE Automation Objects in Transact-SQL 3/24/2017 • 1 min to read • Edit Online Transact-SQL includes several system stored procedures that allow OLE Automation objects to be referenced in Transact-SQL batches, stored procedures, and triggers. These system stored procedures run as extended stored procedures, and the OLE Automation objects that are executed through the stored procedures run in the address space of an instance of the SQL Server Database Engine in the same way that an extended stored procedure runs. The OLE Automation stored procedures enable Transact-SQL batches to reference SQL-DMO objects and custom OLE Automation objects, such as objects that expose the IDispatch interface. A custom in-process OLE server that is created by using Microsoft Visual Basic must have an error handler (specified with the On Error GoTo statement) for the Class_Initialize and Class_Terminate subroutines. Unhandled errors in the Class_Initialize and Class_Terminate subroutines can cause unpredictable errors, such as an access violation in an instance of the Database Engine. Error handlers for other subroutines are also recommended. The first step when using an OLE Automation object in Transact-SQL is to call the sp_OACreate system stored procedure to create an instance of the object in the address space of the instance of the Database Engine. After an instance of the object has been created, call the following stored procedures to work with the properties, methods, and error information related to the object: sp_OAGetProperty obtains the value of a property. sp_OASetProperty sets the value of a property. sp_OAMethod calls a method. sp_OAGetErrorInfo obtains the most recent error information. When there is no more need for the object, call sp_OADestroy to deallocate the instance of the object created by using sp_OACreate. OLE Automation objects return data through property values and methods. sp_OAGetProperty and sp_OAMethod return these data values in the form of a result set. The scope of an OLE Automation object is a batch. All references to the object must be contained in a single batch, stored procedure, or trigger. When it references objects, the SQL Server OLE Automation objects support traversing the referenced object to other objects that it contains. For example, when using the SQL-DMO SQLServer object, references can be made to databases and tables contained on that server. Related Content Object Hierarchy Syntax (Transact-SQL) Surface Area Configuration Ole Automation Procedures Server Configuration Option sp_OACreate (Transact-SQL) sp_OAGetProperty (Transact-SQL) sp_OASetProperty (Transact-SQL) sp_OAMethod (Transact-SQL) sp_OAGetErrorInfo (Transact-SQL) sp_OADestroy (Transact-SQL) OLE Automation Return Codes and Error Information 3/24/2017 • 2 min to read • Edit Online The OLE Automation system stored procedures return an int return code that is the HRESULT returned by the underlying OLE Automation operation. An HRESULT of 0 indicates success. A nonzero HRESULT is an OLE error code of the hexadecimal form 0x800nnnnn, but when returned as an int value in a stored procedure return code, HRESULT has the form 214nnnnnnn. For example, passing an invalid object name (SQLDMO.Xyzzy) to sp_OACreate causes the procedure to return an int HRESULT of 2147221005, which is 0x800401f3 in hexadecimal. You can use to convert an int HRESULT to a binary value. However, using CONVERT(char(10), CONVERT(binary(4), @hresult)) results in an unreadable string, because each byte of the HRESULT is converted to a single ASCII character. You can use the following sample HexToChar stored procedure to convert an int HRESULT to a char value that contains a readable hexadecimal string. CONVERT(binary(4), @hresult) USE AdventureWorks2012; GO IF EXISTS(SELECT name FROM sys.objects WHERE name = N'dbo.sp_HexToChar') DROP PROCEDURE HexToChar; GO CREATE PROCEDURE dbo.sp_HexToChar @BinValue varbinary(255), @HexCharValue nvarchar(255) OUTPUT AS DECLARE @CharValue nvarchar(255); DECLARE @Position int; DECLARE @Length int; DECLARE @HexString nchar(16); SELECT @CharValue = N'0x'; SELECT @Position = 1; SELECT @Length = DATALENGTH(@BinValue); SELECT @HexString = N'0123456789ABCDEF'; WHILE (@Position <= @Length) BEGIN DECLARE @TempInt int; DECLARE @FirstInt int; DECLARE @SecondInt int; SELECT @TempInt = CONVERT(int, SUBSTRING(@BinValue,@Position,1)); SELECT @FirstInt = FLOOR(@TempInt/16); SELECT @SecondInt = @TempInt - (@FirstInt*16); SELECT @CharValue = @CharValue + SUBSTRING(@HexString, @FirstInt+1, 1) + SUBSTRING(@HexString, @SecondInt+1, 1); SELECT @Position = @Position + 1; END SELECT @HexCharValue = @CharValue; GO DECLARE @BinVariable varbinary(35); DECLARE @CharValue nvarchar(35); SET @BinVariable = 123456; EXECUTE dbo.sp_HexToChar @binvalue = @BinVariable, @HexCharValue = @CharValue OUTPUT; SELECT @BinVariable AS BinaryValue, @CharValue AS CharacterRep; GO You can use the following sample stored procedure, sp_displayoaerrorinfo to display OLE Automation error information when one of the OLE Automation procedures returns a nonzero HRESULT return code. This sample stored procedure uses HexToChar. CREATE PROCEDURE dbo.sp_DisplayOAErrorInfo @Object int, @HResult int AS DECLARE @Output nvarchar(255); DECLARE @HRHex nchar(10); DECLARE @HR int; DECLARE @Source nvarchar(255); DECLARE @Description nvarchar(255); PRINT N'OLE Automation Error Information'; EXEC HexToChar @HResult, @HRHex OUT; SELECT @Output = N' HRESULT: ' + @HRHex; PRINT @Output; EXEC @HR = sp_OAGetErrorInfo @Object, @Source OUT, @Description OUT; IF @HR = 0 BEGIN SELECT @Output = N' Source: ' + @Source; PRINT @Output; SELECT @Output = N' Description: ' + @Description; PRINT @Output; END ELSE BEGIN PRINT N' sp_OAGetErrorInfo failed.'; RETURN; END GO Related Content sp_OAGetErrorInfo (Transact-SQL) OLE Automation Result Sets 3/24/2017 • 1 min to read • Edit Online If an OLE Automation property or method returns data in an array with one or two dimensions, the array is returned to the client as a result set: A one-dimensional array is returned to the client as a single-row result set with as many columns as there are elements in the array. For example, an array(10) is returned as a single row of 10 columns. A two-dimensional array is returned to the client as a result set with as many columns as there are elements in the first dimension of the array and with as many rows as there are elements in the second dimension of the array. For example, an array(2,3) is returned as 2 columns in 3 rows. When a property return value or method return value is an array, sp_OAGetProperty or sp_OAMethod returns a result set to the client. (Method output parameters cannot be arrays.) These procedures scan all the data values in the array to determine the appropriate SQL Server data types and data lengths to use for each column in the result set. For a particular column, these procedures use the data type and length required to represent all data values in that column. When all data values in a column share the same data type, that data type is used for the whole column. When data values in a column are different data types, the data type of the whole column is chosen based on the following table. To use the following table, find one data type along the left row axis and a second data type along the top column axis. The intersection of the row and column describes the data type of the result set column. int float money datetime varchar nvarchar int int float money varchar varchar nvarchar float float float money varchar varchar nvarchar money money money money varchar varchar nvarchar datetime varchar varchar varchar datetime varchar nvarchar varchar varchar varchar varchar varchar varchar nvarchar nvarchar nvarchar nvarchar nvarchar nvarchar nvarchar nvarchar Related Content OLE Automation Stored Procedures (Transact-SQL) Ole Automation Procedures Server Configuration Option OLE Automation Sample Script 3/24/2017 • 1 min to read • Edit Online This topic contains an example of a Transact-SQL statement batch that uses the OLE Automation stored procedures to create and use an SQL-DMO SQLServer object in the local instance of the Database Engine. Parts of the code are used as examples in the reference topics for the OLE Automation system stored procedures. USE AdventureWorks2012; GO DECLARE @Object int; DECLARE @HR int; DECLARE @Property nvarchar(255); DECLARE @Return nvarchar(255); DECLARE @Source nvarchar(255), @Desc nvarchar(255); -- Create a SQLServer object. SET NOCOUNT ON; -- First, create the object. EXEC @HR = sp_OACreate N'SQLDMO.SQLServer', @Object OUT; IF @HR <> 0 BEGIN -- Report the error. EXEC sp_OAGetErrorInfo @Object, @Source OUT, @Desc OUT; SELECT HR = convert(varbinary(4),@HR), Source=@Source, Description=@Desc; GOTO END_ROUTINE END ELSE -- A DMO.SQLServer object has been successfully created. BEGIN -- Specify Windows Authentication for connections. EXEC @HR = sp_OASetProperty @Object, N'LoginSecure', N'TRUE'; IF @HR <> 0 GOTO CLEANUP -- Set a property. EXEC @HR = sp_OASetProperty @Object, N'HostName', N'SampleScript'; IF @HR <> 0 GOTO CLEANUP -- Get a property using an output parameter. EXEC @HR = sp_OAGetProperty @Object, N'HostName', @Property OUT; IF @HR <> 0 GOTO CLEANUP ELSE PRINT @Property; -- Get a property using a result set. EXEC @HR = sp_OAGetProperty @Object, N'HostName'; IF @HR <> 0 GOTO CLEANUP -- Get a property by calling the method. EXEC @HR = sp_OAMethod @Object, N'HostName', N'HostName', @Property OUT; IF @HR <> 0 GOTO CLEANUP ELSE PRINT @Property; -- Call the connect method. -- SECURITY NOTE - When possible, use Windows Authentication. EXEC @HR = sp_OAMethod @Object, N'Connect', NULL, N'localhost', NULL, NULL; IF @HR <> 0 GOTO CLEANUP -- Call a method that returns a value. EXEC @HR = sp_OAMethod @Object, N'VerifyConnection', @Return OUT; IF @HR <> 0 GOTO CLEANUP ELSE PRINT @Return; END CLEANUP: -- Check whether an error occurred. IF @HR <> 0 BEGIN -- Report the error. EXEC sp_OAGetErrorInfo @Object, @Source OUT, @Desc OUT; SELECT HR = convert(varbinary(4),@HR), Source=@Source, Description=@Desc; END -- Destroy the object. BEGIN EXEC @HR = sp_OADestroy @Object; -- Check if an error occurred. IF @HR <> 0 BEGIN -- Report the error. EXEC sp_OAGetErrorInfo @Object, @Source OUT, @Desc OUT; SELECT HR = convert(varbinary(4),@HR), Source=@Source, Description=@Desc; END END END_ROUTINE: RETURN; GO Related Content OLE Automation Objects in Transact-SQL sp_OACreate (Transact-SQL) sp_OAGetProperty (Transact-SQL) sp_OASetProperty (Transact-SQL) sp_OAMethod (Transact-SQL) sp_OADestroy (Transact-SQL)