The EXEC keyword in SQL is used to execute a stored procedure, dynamic SQL, or a system-defined procedure. It allows you to invoke a predefined set of SQL statements that are stored in the database or dynamically created at runtime.
Syntax
To execute a stored procedure:
EXEC procedure_name [parameter1, parameter2, ...];
or
EXECUTE procedure_name [parameter1, parameter2, ...];
To execute dynamic SQL:
EXEC ('dynamic SQL statement');
or
EXECUTE ('dynamic SQL statement');
Examples
Executing a Stored Procedure
Suppose you have a stored procedure named GetEmployeeDetails that accepts an EmployeeID parameter:
EXEC GetEmployeeDetails 123;
Using EXEC with Named Parameters
EXEC GetEmployeeDetails @EmployeeID = 123;
Executing Dynamic SQL
You can use EXEC to execute a string containing an SQL statement:
DECLARE @sql NVARCHAR(1000);
SET @sql = 'SELECT * FROM Employees WHERE Department = ''Sales''';
EXEC(@sql);
Notes
- The
EXECkeyword is supported in many SQL-based systems, including Microsoft SQL Server. In some databases (e.g., MySQL, PostgreSQL), the syntax or keyword might differ. - When using
EXECto execute dynamic SQL, ensure that input is sanitized to prevent SQL injection vulnerabilities. - Some database systems allow you to use other variations, such as
sp_executesqlin SQL Server, which offers additional flexibility with parameterized queries.
Would you like details on a specific use case?
No comments:
Post a Comment