How do you use the SP_EXECUTESQL stored procedure to execute dynamic SQL?
Posted by FrankMl
Last Updated: July 09, 2024
The SP_EXECUTESQL stored procedure is a system stored procedure in SQL Server that allows you to execute a dynamically built SQL statement. It provides a way to run parameterized queries, which helps prevent SQL injection and improves performance by caching execution plans.
Syntax
The basic syntax for using SP_EXECUTESQL is as follows:
EXEC sp_executesql 
    @stmt = N'SQL statement here', 
    @params = N'@param1 datatype, @param2 datatype', 
    @param1 = Value1, 
    @param2 = Value2;
Parameters
- @stmt: This is a Unicode string that contains the SQL statement to be executed. - @params: This optional parameter defines the parameters that will be used in the SQL statement. It defines parameter names and their types. - @param1, @param2, ...: These are the actual values that will be substituted for the parameters defined in @params.
Example
Here's an example to illustrate how to use SP_EXECUTESQL:
DECLARE @SQL NVARCHAR(MAX);
DECLARE @Category NVARCHAR(50) = 'Beverages';
DECLARE @MinPrice DECIMAL(10, 2) = 10.00;

SET @SQL = N'SELECT ProductName, Price 
             FROM Products 
             WHERE Category = @Category AND Price > @MinPrice';

EXEC sp_executesql 
    @stmt = @SQL, 
    @params = N'@Category NVARCHAR(50), @MinPrice DECIMAL(10, 2)', 
    @Category = @Category, 
    @MinPrice = @MinPrice;
Key Points
1. Parameterized Queries: Using parameters within the SQL statement helps avoid SQL injection and can enhance performance through plan reuse. 2. Dynamic SQL: You can build SQL statements dynamically and execute them using SP_EXECUTESQL. 3. Returns Results: The statement executed can return results just like any other SQL query.
Advantages of SP_EXECUTESQL
- Security: Helps protect against SQL injection attacks. - Reusability: Execution plans can be reused, improving performance when the same query is executed multiple times with different parameters. - Flexibility: Allows for complex queries and conditional logic in SQL execution. Using SP_EXECUTESQL is preferred over EXEC for executing dynamic SQL when you need to use parameters because of the advantages mentioned above.