Assign output of dynamic SQL to a variable (without stored proc)
I have the code below, where I want to get the id of a row via dynamic SQL.
Please note that variables @posselect
and @catselect
are filled, but I left that out for overview.
declare @SQL nvarchar(1000)
declare @posselect nvarchar(50)
declare @catselect nvarchar(100)
declare @bannerid int
SET @SQL = 'SELECT TOP 1 @id = id FROM banners
WHERE publishdate < GETDATE()
AND depublishdate > GETDATE()' + @posselect + @catselect +
'ORDER BY [views] ASC'
EXEC sp_executesql @SQ开发者_开发百科L, @bannerid = @id output 'on this line I get the error
print '@bannerid:'+STR(@bannerid)
I get the error:
Must declare the scalar variable "@id".
Your code doesn't show that you are setting your @id field
declare @SQL nvarchar(1000)
declare @posselect nvarchar(50)
declare @catselect nvarchar(100)
declare @id int
declare @bannerid int
set @SQL='SELECT TOP 1 @id=id FROM banners
WHERE publishdate<GETDATE() AND depublishdate>GETDATE()' + @posselect + @catselect + '
ORDER BY [views] asc'
EXEC sp_executesql @SQL,@bannerid=@id output 'on this line I get the error
print '@bannerid:'+STR(@bannerid)
I might be missing something but I don't see where you are declaring @id
(as the error message suggests).
Try changing it to this:
declare @SQL nvarchar(1000) declare @posselect nvarchar(50) declare @catselect nvarchar(100)
declare @bannerid int
declare @id int
set @SQL='SELECT TOP 1 @id=id FROM banners WHERE publishdateGETDATE()' + @posselect + @catselect + ' ORDER BY [views] asc'
EXEC sp_executesql @SQL,@bannerid=@id output 'on this line I get the error
print '@bannerid:'+STR(@bannerid)
Try
DECLARE @params NVARCHAR(128) = N'@id int output';
EXEC sp_executesql @SQL, @params, @id=@bannerid output
I believe that's the correct syntax.
精彩评论