0

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 @SQL, @bannerid = @id output  'on this line I get the error

print '@bannerid:'+STR(@bannerid)

I get the error:

Must declare the scalar variable "@id".

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Adam
  • 6,041
  • 36
  • 120
  • 208
  • Having difficulties posting code, dont know the tag usage. Replaced @ with [at] Fixed it like this: declare [at]ParmDefinition nvarchar(250) set [at]ParmDefinition = '[at]bannerid int out' set [at]SQL='SELECT TOP 1 [at]bannerid=id FROM banners WHERE publishdateGETDATE()' + [at]posselect + [at]catselect + ' ORDER BY [views] ASC' EXEC sp_executesql [at]SQL,[at]ParmDefinition,[at]bannerid out thanks! – Adam Aug 05 '11 at 21:41

3 Answers3

2

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)
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
2

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)
Taryn
  • 242,637
  • 56
  • 362
  • 405
1

Try

DECLARE @params NVARCHAR(128) = N'@id int output';

EXEC sp_executesql @SQL, @params, @id=@bannerid output   

I believe that's the correct syntax.

Sam DeHaan
  • 10,246
  • 2
  • 40
  • 48