EXECUTE Statement
Executes a Transact-SQL statement or a stored procedure.
Syntax
EXECUTE [] []
{ | | }
[ & ]
[ { , | ,& } ] [ ...n ]
[ WITH RECOMPILE | WITH EXECUTE ONLY ]
Where:
parameteris an optional parameter name.variableis an optional variable name.sql_batchis a Transact-SQL statement or batch.stored_procedureis a stored procedure name.extended_stored_procedureis an extended stored procedure name.variable_assignmentsis an assignment of a variable....nindicates that multiple parameters can be specified.
Description
The EXECUTE (or EXEC) statement runs a Transact-SQL statement, stored procedure, or extended stored procedure.
You can pass parameters to the statement or procedure being executed. If the statement or procedure returns a value, it can be captured into a variable.
Examples
Example 1: Executing a Stored Procedure
EXECUTE sp_who;
Example 2: Executing a Stored Procedure with Parameters
DECLARE @DatabaseName SYSNAME = 'AdventureWorks';
EXECUTE sp_spaceused @DatabaseName;
Example 3: Executing a Dynamic SQL Batch and Capturing Output
DECLARE @SQLStatement NVARCHAR(500);
DECLARE @Result INT;
SET @SQLStatement = N'SELECT COUNT(*) FROM Production.Product';
EXECUTE sp_executesql @SQLStatement, N'@OutputCount INT OUTPUT', @OutputCount = @Result OUTPUT;
SELECT @Result AS ProductCount;
Example 4: Executing a T-SQL Statement
EXECUTE ('USE master; SELECT DB_NAME() AS CurrentDatabase;');
Remarks
- The
EXECUTEstatement is often used to run dynamic SQL. - When executing dynamic SQL, it's recommended to use
sp_executesqlfor better performance and security (prevents SQL injection). - Extended stored procedures are system procedures that extend the functionality of SQL Server.
- The
WITH RECOMPILEoption recompiles the execution plan for the statement or procedure. - The
WITH EXECUTE ONLYoption restricts execution to the user executing it and does not allow re-execution without recompilation.