I have a problem once I want to run the next query:
declare @j int = 1;
declare @column varchar(255);
set @column = 'last_name';
declare @tmp varchar(255);
declare @query nvarchar(255) = N'select ' + @column + N' from TEST where id = @j'
declare @tbl table(tmp varchar(255))
insert into @tbl
exec sp_executesql @query
select top 1 @tmp = tmp from @tbl
select @tmp
select * from @tbl;
The problem is that if I change the variable @j to a numeric value in the declaration of the @query variable, like this
declare @query nvarchar(255) = N'select ' + @column + N' from TEST where id = 1'
the query is running successfully, if I left the @j variable there, like this
declare @query nvarchar(255) = N'select ' + @column + N' from TEST where id = @j'
I got an error message:
"Must declare the scalar variable @j."
Why? And how can I solve that my query would work with the variable @j?