将动态 SQL 的输出分配给变量(没有存储过程)
我有下面的代码,我想通过动态 SQL 获取行的 id。
请注意,变量 @posselect
和 @catselect
已填充,但我将其保留以进行概述。
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)
我收到错误:
必须声明标量变量“@id”。
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".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码未显示您正在设置 @id 字段
Your code doesn't show that you are setting your @id field
我可能遗漏了一些东西,但我看不到您在哪里声明
@id
(如错误消息所示)。尝试将其更改为这样:
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:
尝试一下
,我相信这是正确的语法。
Try
I believe that's the correct syntax.