cMi*_*nor 42 sql-server string
我正在做动态SQL来将表中的所有列转换为字符串
所以毕竟我做了
EXEC(@template);
Run Code Online (Sandbox Code Playgroud)
其中@template是动态生成的查询,因此:
col1 col2 col3
---------------
1 7 13
2 8 14
3 9 15
4 10 16
5 11 17
6 12 18
Run Code Online (Sandbox Code Playgroud)
(结果:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18)
如何为变量分配结果字符串
就像是?
DECLARE @result AS varchar(max);
SET @result = EXEC(@template);
Run Code Online (Sandbox Code Playgroud)
Mik*_*son 64
您可以将sp_executesql与输出参数一起使用.
declare @S nvarchar(max) = 'select @x = 1'
declare @xx int
set @xx = 0
exec sp_executesql @S, N'@x int out', @xx out
select @xx
Run Code Online (Sandbox Code Playgroud)
结果:
(No column name)
1
Run Code Online (Sandbox Code Playgroud)
编辑
在我的样本@S
中而不是你的@template
.正如您所看到的,我分配了一个值,@x
因此您需要进行修改,@template
以便在内部将逗号分隔的字符串分配给您在第二个参数中定义的变量sp_executesql
.在我的样本中N'@x int out'
.您可能需要varchar(max)
输出参数.就像是N'@Result varchar(max) out'
这是另一个从master..spt_values构建逗号分隔字符串的示例
declare @template nvarchar(max)
set @template =
'select @Result += cast(number as varchar(10))+'',''
from master..spt_values
where type = ''P''
'
declare @CommaString varchar(max)
set @CommaString = ''
exec sp_executesql @template, N'@Result varchar(max) out', @CommaString out
select @CommaString
Run Code Online (Sandbox Code Playgroud)
And*_*mar 14
你可以用sp_executesql
而不是exec
.这允许您指定输出参数.
declare @out_var varchar(max);
execute sp_executesql
N'select @out_var = ''hello world''',
N'@out_var varchar(max) OUTPUT',
@out_var = @out_var output;
select @out_var;
Run Code Online (Sandbox Code Playgroud)
这打印出"你好世界".
小智 12
这些答案中的大多数使用sp_executesql作为此问题的解决方案.我发现使用sp_executesql时存在一些限制,我不会介绍,但我想使用EXEC()提供替代方法.我正在使用SQL Server 2008,我知道我在此脚本中使用的某些对象在早期版本的SQL Server中不可用,所以要小心.
DECLARE @CountResults TABLE (CountReturned INT)
DECLARE
@SqlStatement VARCHAR(8000) = 'SELECT COUNT(*) FROM table'
, @Count INT
INSERT @CountResults
EXEC(@SqlStatement)
SET @Count = (SELECT CountReturned FROM @CountResults)
SELECT @Count
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
134825 次 |
最近记录: |