gpt4 book ai didi

sql-server - 如何在 t-sql 中使用 'execute' 为变量设置值?

转载 作者:行者123 更新时间:2023-12-01 17:56:52 29 4
gpt4 key购买 nike

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId int
exec ('SELECT TOP 1 @siteId = Id FROM ' + @dbName + '..myTbl')
select @siteId

当我运行上面的脚本时,出现以下错误

Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@siteId".

(1 row(s) affected)

为什么以及如何解决它?

谢谢

最佳答案

您可以将输出参数与 sp_executesql 一起使用。

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId int
DECLARE @SQL nvarchar(max) = N'SELECT TOP 1 @outputFromExec = Id FROM ' + quotename(@dbName) + N'..myTbl'
exec sp_executesql @SQL, N'@outputFromExec int out', @siteId out
select @siteId

关于sql-server - 如何在 t-sql 中使用 'execute' 为变量设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7229070/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com