
Substituting Parameter Values
sp_executesql supports the substitution of parameter values for any parameters that are specified in the Transact-SQL string, but the EXECUTE statement does not. Therefore, the Transact-SQL strings that are generated by sp_executesql are more similar than those generated by the EXECUTE statement. The SQL Server query optimizer will probably match the Transact-SQL statements from sp_executesql with execution plans from the previously executed statements, saving the overhead of compiling a new execution plan.
With the EXECUTE statement, all parameter values must be converted to character or Unicode and made a part of the Transact-SQL string.
If the statement is executed repeatedly, a completely new Transact-SQL string must be built for each execution, even when the only differences are in the values supplied for the parameters. This generates additional overhead in the following ways:
-
The ability of the SQL Server query optimizer to match the new Transact-SQL string with an existing execution plan is hampered by the constantly changing parameter values in the text of the string, especially in complex Transact-SQL statements.
-
The whole string must be rebuilt for each execution.
-
Parameter values (other than character or Unicode values) must be cast to a character or Unicode format for each execution.
sp_executesql supports setting of parameter values separately from the Transact-SQL string:
DECLARE @IntVariable INT;
DECLARE @SQLString NVARCHAR(500);
DECLARE @ParmDefinition NVARCHAR(500);
/* Build the SQL string one time. */
SET @SQLString =
N'SELECT * FROM AdventureWorks.Sales.Store WHERE SalesPersonID = @SalesID';
/* Specify the parameter format one time. */
SET @ParmDefinition = N'@SalesID int';
/* Execute the string with the first parameter value. */
SET @IntVariable = 275;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@SalesID = @IntVariable;
/* Execute the same string with the second parameter value. */
SET @IntVariable = 276;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
@SalesID = @IntVariable;
sp_executesql offers the following additional benefits:
-
Because the actual text of the Transact-SQL statement does not change between executions, the query optimizer should match the Transact-SQL statement in the second execution with the execution plan generated for the first execution. Therefore, SQL Server does not have to compile the second statement.
-
The Transact-SQL string is built only one time.
-
The integer parameter is specified in its native format. Conversion to Unicode is not required.
Note: |
|---|
|
Object names in the statement string must be fully qualified for SQL Server to reuse the execution plan.
|