1

I am having problems running sql server stored procedure. I using a dynamic sql. I get the error "Must declare the scalar variable "@EmployeeId".

SQL QUERY

ALTER PROCEDURE [dbo].[GetLeaveDays] -- Add the parameters for the stored 
procedure here
@LeaveType varchar(5000), 
@AdminId int,
@EmployeeId int

AS 
BEGIN

SET NOCOUNT ON;

DECLARE 
@queryString nvarchar(MAX);

SET @queryString = 'SELECT ' + @LeaveType + ' FROM CompulsoryLeave WHERE 
AdminId = @AdminId AND Id=(SELECT LeaveStructureId FROM Employee WHERE 
Id=@EmployeeId)';

EXECUTE sp_executesql @queryString,
    N'@AdminId int',
    N'@EmployeeId int',
     @AdminId = @AdminId,
     @EmployeeId=@EmployeeId

END
1
  • 1
    Bobby Tables can't wait to get a hold of @LeaveType. You might want to validate it against the columns in the table unless you need something more interesting, e.g. expressions. If it is a list of columns then you can split it and validate them individually. Commented Jan 21, 2018 at 4:20

1 Answer 1

2

The second sp_executesql parameter should be a single string with all parameter definitions. Try:

EXECUTE sp_executesql @queryString,
    N'@AdminId int, @EmployeeId int',
     @AdminId = @AdminId,
     @EmployeeId = @EmployeeId;
Sign up to request clarification or add additional context in comments.

2 Comments

While you respect the order of the parameters, you can just pass the value directly without set it to the parameters as ... @AdminId, @EmployeeId;
@Sami, it is true one can specify parameters by ordinal position rather than name with sp_executesql (and any stored procedure) but IMHO the named syntax is more maintainable, especially when the outer reference is named differently.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.