如何通过在 sql 服务器中执行另一个变量来打印变量值?

How do I get a print of a variable value by executing another variable in sql server?

我想打印 sql 服务器中的一些变量。我正在执行的代码如下:

declare @r varchar(max), @t char(4)
set @t = 'test'
set @r = '
--Some code that might effecting @t in different ways...

print ''Print value for @t: ''' + @t + '

--Some more code...
'
exec(@r)

当 运行 时,我收到消息 102 错误,显示 Incorrect syntax near 'test'..

我尝试了不同数量的撇号,有时这会有所帮助。但这似乎是我在这里缺少的其他东西。我只是无法让它与打印输出一起工作,现在我有相当多的打印输出并且不能再有效地使用我之前的“变通方法”了。所以我需要找到解决办法。

不要 将参数注入动态 SQL。 参数化他们:

DECLARE @r nvarchar(max), @t char(4);
SET @t = 'test';

SET @r = '
--Some code that might effecting @t in different ways...

PRINT ''Print value for @t: '' + @t;

--Some more code...
'
EXEC sys.sp_executesql @R, N'@t char(4)', @t;