Use of sp_executesql
The "sp_executesql" is used for executing the sql statements that are build dynamically with or without parameters.
The below example shows how to execute by dynamically passing the employee id.
DECLARE @EmployeeNumber int;
DECLARE @SQLString nvarchar(500);
DECLARE @Parameter nvarchar(500);
SET @SQLString = 'SELECT * FROM EMPLOYEE WHERE EMPLOYEEID = @EmployeeID';
SET @Parameter = '@EmployeeID int';
SET @EmployeeNumber = 2;
EXECUTE sp_executesql @SQLString, @Parameter,
@EmployeeID = @EmployeeNumber;
The below example shows how to execute by dynamically passing the employee id.
DECLARE @EmployeeNumber int;
DECLARE @SQLString nvarchar(500);
DECLARE @Parameter nvarchar(500);
SET @SQLString = 'SELECT * FROM EMPLOYEE WHERE EMPLOYEEID = @EmployeeID';
SET @Parameter = '@EmployeeID int';
SET @EmployeeNumber = 2;
EXECUTE sp_executesql @SQLString, @Parameter,
@EmployeeID = @EmployeeNumber;
Comments