100 Days of SQL

sql

Day 71 – SQL EXEC Keyword

SQL EXEC keyword is used to execute a stored procedure or a dynamically constructed SQL statement within a stored procedure in SQL Server. The basic syntax for using the EXEC keyword is as follows:

EXEC procedure_name

Here, procedure_name is the name of the stored procedure that you want to execute. The EXEC keyword can also be used to execute a dynamically constructed SQL statement within a stored procedure. In this case, the SQL statement is passed as a string to the EXEC keyword, and the string is executed as a separate batch.

For example, to execute a stored procedure named “GetCustomerByID” that takes a customer ID as a parameter, the SQL statement would be:

EXEC GetCustomerByID 1234;

This would execute the “GetCustomerByID” stored procedure with a customer ID of 1234.

Alternatively, to execute a dynamically constructed SQL statement within a stored procedure, the SQL statement would be constructed as a string and passed as a parameter to the EXEC keyword, as follows:

DECLARE @sql VARCHAR(MAX);
SET @sql = 'SELECT * FROM Customers WHERE CustomerID = 1234';
EXEC (@sql);

This would execute a SELECT statement that retrieves all columns from the “Customers” table where the customer ID is equal to 1234. The SQL statement is constructed as a string and passed as a parameter to the EXEC keyword, which executes the statement as a separate batch.