I am trying to create a stored procedure that utilizes a variable number of parameters. As I am pretty new to writing stored procedures and TSQL in general, I decided to try and write it with only one parameter. However, I keep getting an error stating “Must declare scalar variable @FirstName” when I try to execute it. Right now, I am trying to store the SQL statement in another variable, @sql. My procedure looks like this:
ALTER PROCEDURE [dbo].[GetEmployeeByParameters]
(@FirstName varchar(50))
AS
BEGIN
DECLARE @sql AS NVARCHAR(4000)
SET @sql = 'SELECT e.* from Employee e
WHERE e.FirstName = @FirstName'
EXEC (@sql)
END
I’ve looked elsewhere and tried EXEC sp_execute @sql which didn’t work. Strangely, what does work is when I don’t declare the @sql variable and instead just write my query normally. Since that is the case, I’m assuming there is some error in my usage of the SET and EXEC functions. I’m also not 100% sure that I’m using BEGIN and END properly. The way I understood it is that BEGIN and END separate SQL statements into logical blocks, and thus are more commonly used when IF comes into play. Could anyone tell me what exactly is going on with my parameter here? It’s really confusing me as to why SQL Server thinks it’s not declared.
The variable parameter needs to be outside the quotes.
Or, better yet, run it without any dynamic SQL.