我正在尝试编写e proc,它将列值转换为以字符(例如)分隔的字符串。
它停留在此行exec @maxcount = sp_executesql @temp
上,并返回@maxxount的任何建议值,我如何设置动态查询执行的值,以便它继续处理所有函数并执行正确的答案。
ALTER procedure [dbo].[usp_stringConvert](
@table_name varchar(101),
@column_name varchar(100),
@separator varchar(20)
)
as
declare @maxcount int, @temp nvarchar(1000)
declare @count int
declare @result varchar(1000)
set @result =''
set @count =1
set @temp= Concat('select count(', @column_Name ,') from ', @table_name)
exec @maxcount = sp_executesql @temp
while (@count<@maxcount)
begin
if @count!=1
set @result+=@separator
set @temp=Concat('select ' , @column_name ,' from ' , @table_name , 'where @count = row_number() over(order by (select (100)))')
exec @temp = sp_executesql @temp
set @result =CONCAT(@result, @temp)
set @count+=1;
end
select @result;
答案 0 :(得分:0)
在SQL Server中使用常规SQL,您可以使用以下方式连接字符串:
select stuff( (select concat(separator, column_name)
from table_name
for xml path ('', type)
).value('.', nvarchar(max)
), 1, len(separator), ''
)
您应该可以使用以下方法将其转换为动态SQL:
declare @sql nvarchar(max);
declare @result nvarchar(max);
set @sql = N'
select @result = stuff( (select concat(@separator + [column_name]
from [table_name]
for xml path ('''', type)
).value(''.'', nvarchar(max)
), 1, len(@separator), ''
)
';
set @sql = replace(@sql, '[table_name]', quotename(@table_name));
set @sql = replace(@sql, '[column_name]', quotename(@column_name));
exec sp_executesql @sql,
N'@result nvarchar(max) output',
@result=@result output;
select @result;