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".

1
  • 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 publishdate<GETDATE() AND depublishdate>GETDATE()' + [at]posselect + [at]catselect + ' ORDER BY [views] ASC' EXEC sp_executesql [at]SQL,[at]ParmDefinition,[at]bannerid out thanks! Commented Aug 5, 2011 at 21:41

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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.

Comments

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.