Académique Documents
Professionnel Documents
Culture Documents
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).
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 grant permissions on a stored procedure. Grant Permissions on a Stored Procedure
Describes how to return data from a stored procedure to an Return Data from a Stored Procedure
application.
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 View the Dependencies of a Stored Procedure
procedure.
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.
Permissions
Requires CREATE PROCEDURE permission in the database and ALTER permission on the schema in which the
procedure is being created.
PARAMETER VALUE
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:
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
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.
See Also
CREATE PROCEDURE (Transact-SQL)
Modify a Stored Procedure
3/24/2017 3 min to read Edit Online
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.
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.
See Also
ALTER PROCEDURE (Transact-SQL)
Delete a Stored Procedure
3/24/2017 2 min to read Edit Online
5. Copy and paste the following example into the query editor and insert a stored procedure name to delete
from the current database.
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
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;
USE AdventureWorks2012;
GO
EXEC dbo.uspGetEmployeeManagers @BusinessEntityID = 50;
-Or-
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.
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
USE AdventureWorks2012;
GO
EXEC sp_procoption @ProcName = '<procedure name>'
, @OptionName = ] 'startup'
, @OptionValue = 'on';
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.
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
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.
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;
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.
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.
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).
See Also
CREATE PROCEDURE (Transact-SQL)
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
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. User-
defined 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
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
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
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.
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
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.
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.
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.
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
0 Successful execution.
The following example creates a program to handle the return codes that are returned from the usp_GetSalesYTD
procedure.
-- Declare the variables to receive the output value and return code
-- of the procedure.
DECLARE @SalesYTDForSalesPerson money, @ret_code int;
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
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;
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
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 .
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
USE AdventureWorks2012;
GO
EXEC sp_helptext N'AdventureWorks2012.dbo.uspLogError';
USE AdventureWorks2012;
GO
SELECT OBJECT_DEFINITION (OBJECT_ID(N'AdventureWorks2012.dbo.uspLogError'));
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.
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
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
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
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 CONVERT(binary(4), @hresult) 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.
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);
EXECUTE dbo.sp_HexToChar
@binvalue = @BinVariable,
@HexCharValue = @CharValue OUTPUT;
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.
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);
-- Set a property.
EXEC @HR = sp_OASetProperty @Object,
N'HostName',
N'SampleScript';
IF @HR <> 0 GOTO CLEANUP
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
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)