为什么我在动态 SQL 中得到 "must declare scalar variable" 错误?

Why do I get a "must declare scalar variable" error in dynamic SQL?

我试图在为变量设置值时使用动态 SQL,但它不起作用。但是,相同的语句在常规 SQL 中确实有效。这是代码:

DECLARE @sqlcmd nchar(1024);
DECLARE @DBName nchar(30) = 'DB_1016a'
DECLARE @UserKey int = 0;
DECLARE @UserID nchar(30) = 'DBCLIENT\StudentA'
set @sqlcmd = 'set @UserKey = (SELECT [Key] from ' + rtrim(ltrim(@DBName)) + '.dbo.userlist where ID = ''' + rtrim(ltrim(@UserID)) + ''')'
print(@sqlcmd)
exec(@sqlcmd)
print('stuff1')
print('['+rtrim(ltrim(cast(@UserKey as nchar(4))))+']')
print('stuff2')

这就是它 returns:

set @UserKey = (SELECT [Key] from DB_1016a.dbo.userlist where ID = 'DBCLIENT\StudentA')                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
*Msg 137, Level 15, State 1, Line 30
Must declare the scalar variable "@UserKey".*    
stuff1
[0]
stuff2

我做错了什么?

您正在处理范围问题。 @sqlcmd 中包含的语句与您使用 exec.

运行 声明 @UserKey 时的执行范围不同

您需要在动态 SQL 批处理中绑定一个输出参数,并将局部变量分配给该参数。像这样:

DECLARE @sqlcmd nchar(1024);
DECLARE @DBName nchar(30) = 'DB_1016a'
DECLARE @UserKey int;
DECLARE @UserID nchar(30) = 'DBCLIENT\StudentA'
set @sqlcmd = 'set @UserKey = (SELECT [Key] from ' + rtrim(ltrim(@DBName)) + '.dbo.userlist where ID = ''' + rtrim(ltrim(@UserID)) + ''')'
print(@sqlcmd)
exec sp_executesql @sqlcmd, N'@UserKey int out', @UserKey = @UserKey output
print('stuff1')
print('['+rtrim(ltrim(cast(@UserKey as nchar(4))))+']')
print('stuff2')