declare @sqlstr varchar(max);
select @sqlstr = 'a,b,c,d,e,f';
我想在sql server2008中使用一条sql语句来处理一行六列。
a,b,c,d,e,f
最佳答案
如果您可以将其声明为nvarchar(MAX)
而不是varchar(max)
,您可以尝试将其转换为动态sql。例如:
declare @sqlstr nvarchar(max);
--Select the initial values
select @sqlstr = 'a,b,c,d,e,f';
--Replace the comma so the string becomes a','b','c','d','e','f
select @sqlstr = REPLACE(@sqlstr, ',', ''',''')
--Add select to the beginning and add leading and trailing ' around the select values
select @sqlstr = 'Select ''' + @sqlstr + ''''
--execute the dynamic sql of select 'a','b','c','d','e','f'
exec sp_executesql @sqlstr
也可以稍微缩写
declare @sqlstr nvarchar(max);
--Select the initial values
select @sqlstr = 'a,b,c,d,e,f';
--Build the sql statement
select @sqlstr = 'Select ''' + REPLACE(@sqlstr, ',', ''',''') + ''''
--execute the dynamic sql of select 'a','b','c','d','e','f'
exec sp_executesql @sqlstr
或者如果您被束缚于 VARCHAR(MAX)
DECLARE @sqlstr VARCHAR(MAX)
--Select the initial values
SELECT @sqlstr = 'a,b,c,d,e,f';
--Build the sql statement
DECLARE @DynamicSQL NVARCHAR(MAX) = 'Select ''' + REPLACE(@sqlstr, ',', ''',''') + ''''
--execute the dynamic sql of select 'a','b','c','d','e','f'
EXEC sp_executesql @DynamicSQL
请参阅Sql Fiddle示例
关于sql将字符串拆分为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12854674/