sp_executesql (Transact-SQL)

Post date: Apr 21, 2011 8:35:55 AM

sp_executesql has the same behavior as EXECUTE with regard to batches, the scope of names, and database context. The Transact-SQL statement or batch in the sp_executesql stmt parameter is not compiled until the sp_executesql statement is executed. The contents of stmt are then compiled and executed as an execution plan separate from the execution plan of the batch that called sp_executesql. The sp_executesql batch cannot reference variables declared in the batch that calls sp_executesql. Local cursors or variables in the sp_executesql batch are not visible to the batch that calls sp_executesql. Changes in database context last only to the end of the sp_executesql statement.

sp_executesql can be used instead of stored procedures to execute a Transact-SQL statement many times when the change in parameter values to the statement is the only variation. Because the Transact-SQL statement itself remains constant and only the parameter values change, the SQL Server query optimizer is likely to reuse the execution plan it generates for the first execution.

Note

To improve performance use fully qualified object names in the statement string.

sp_executesql supports the setting of parameter values separately from the Transact-SQL string as shown in the following example.

DECLARE @IntVariable int; DECLARE @SQLString nvarchar(500); DECLARE @ParmDefinition nvarchar(500);  /* Build the SQL string one time.*/ SET @SQLString =      N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID        FROM AdventureWorks2008R2.HumanResources.Employee         WHERE BusinessEntityID = @BusinessEntityID';

 SET @ParmDefinition = N'@BusinessEntityID tinyint';

 /* Execute the string with the first parameter value. */ SET @IntVariable = 197;

EXECUTE sp_executesql @SQLString, @ParmDefinition,                       @BusinessEntityID = @IntVariable; 

/* Execute the same string with the second parameter value. */ SET @IntVariable = 109; 

EXECUTE sp_executesql @SQLString, @ParmDefinition, @BusinessEntityID = @IntVariable;

Output parameters can also be used with sp_executesql. The following example retrieves a job title from the AdventureWorks2008R2.HumanResources.Employee table and returns it in the output parameter @max_title.

DECLARE @IntVariable int; DECLARE @SQLString nvarchar(500); DECLARE @ParmDefinition nvarchar(500); DECLARE @max_title varchar(30);  SET @IntVariable = 197; SET @SQLString = N'SELECT @max_titleOUT = max(JobTitle)     FROM AdventureWorks2008R2.HumanResources.Employee    WHERE BusinessEntityID = @level'; SET @ParmDefinition = N'@level tinyint, @max_titleOUT varchar(30) OUTPUT';  EXECUTE sp_executesql @SQLString, @ParmDefinition, @level = @IntVariable, 

@max_titleOUT=@max_title 

OUTPUT; SELECT @max_title;

Being able to substitute parameters in sp_executesql offers the following advantages to using the EXECUTE statement to execute a string:

A. Executing a simple SELECT statement

The following example creates and executes a simple SELECT statement that contains an embedded parameter named @level.

EXECUTE sp_executesql            N'SELECT * FROM AdventureWorks2008R2.HumanResources.Employee            WHERE BusinessEntityID = @level',           N'@level tinyint',           @level = 109;

B. Executing a dynamically built string

The following example shows using sp_executesql to execute a dynamically built string. The example stored procedure is used to insert data into a set of tables that are used to partition sales data for a year. There is one table for each month of the year that has the following format:

CREATE TABLE May1998Sales     (OrderID int PRIMARY KEY,     CustomerID int NOT NULL,     OrderDate  datetime NULL         CHECK (DATEPART(yy, OrderDate) = 1998),     OrderMonth int         CHECK (OrderMonth = 5),     DeliveryDate datetime  NULL,         CHECK (DATEPART(mm, OrderDate) = OrderMonth)     )

This sample stored procedure dynamically builds and executes an INSERT statement to insert new orders into the correct table. The example uses the order date to build the name of the table that should contain the data, and then incorporates that name into an INSERT statement.

Note

This is a simple example for sp_executesql. The example does not contain error checking and does not include checks for business rules, such as guaranteeing that order numbers are not duplicated between tables.

CREATE PROCEDURE InsertSales @PrmOrderID INT, @PrmCustomerID INT,                  @PrmOrderDate DATETIME, @PrmDeliveryDate DATETIME AS DECLARE @InsertString NVARCHAR(500) DECLARE @OrderMonth INT  -- Build the INSERT statement. SET @InsertString = 'INSERT INTO ' +        /* Build the name of the table. */        SUBSTRING( DATENAME(mm, @PrmOrderDate), 1, 3) +        CAST(DATEPART(yy, @PrmOrderDate) AS CHAR(4) ) +        'Sales' +        /* Build a VALUES clause. */        ' VALUES (@InsOrderID, @InsCustID, @InsOrdDate,' +        ' @InsOrdMonth, @InsDelDate)'  /* Set the value to use for the order month because    functions are not allowed in the sp_executesql parameter    list. */ SET @OrderMonth = DATEPART(mm, @PrmOrderDate)  EXEC sp_executesql @InsertString,      N'@InsOrderID INT, @InsCustID INT, @InsOrdDate DATETIME,        @InsOrdMonth INT, @InsDelDate DATETIME',      @PrmOrderID, @PrmCustomerID, @PrmOrderDate,      @OrderMonth, @PrmDeliveryDate  GO

Using sp_executesql in this procedure is more efficient than using EXECUTE to execute a string. When sp_executesql is used, there are only 12 versions of the INSERT string that are generated, one for each monthly table. With EXECUTE, each INSERT string is unique because the parameter values are different. Although both methods generate the same number of batches, the similarity of the INSERT strings generated by sp_executesql makes it more likely that the query optimizer will reuse execution plans.

C. Using the OUTPUT Parameter

The following example uses an OUTPUT parameter to store the result set generated by the SELECT statement in the @SQLString parameter.Two SELECT statements are then executed that use the value of the OUTPUT parameter.

USE AdventureWorks2008R2; GO DECLARE @SQLString nvarchar(500); DECLARE @ParmDefinition nvarchar(500); DECLARE @SalesOrderNumber nvarchar(25); DECLARE @IntVariable int; SET @SQLString = N'SELECT @SalesOrderOUT = MAX(SalesOrderNumber)     FROM Sales.SalesOrderHeader     WHERE CustomerID = @CustomerID'; SET @ParmDefinition = N'@CustomerID int,     @SalesOrderOUT nvarchar(25) OUTPUT'; SET @IntVariable = 22276; EXECUTE sp_executesql     @SQLString     ,@ParmDefinition     ,@CustomerID = @IntVariable     ,@SalesOrderOUT = @SalesOrderNumber OUTPUT; -- This SELECT statement returns the value of the OUTPUT parameter. SELECT @SalesOrderNumber; -- This SELECT statement uses the value of the OUTPUT parameter in -- the WHERE clause. SELECT OrderDate, TotalDue FROM Sales.SalesOrderHeader WHERE SalesOrderNumber = @SalesOrderNumber;

-Reference Microsoft