sql将字符串拆分为一行

标签 sql sql-server string sql-server-2008

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/

相关文章:

C程序: how to find the maximum/minimum frequency of a character in a string

mysql - 数据库设计帮助 - 拆分表

python - 在sql server和dataframe中将宽格式转换为长格式大约有1000列 - 优化

sql-server - T-sql Cursor,出错了怎么办?

sql - 转换为日期时间 - 带有日期的 DateTime 列和带有时间的 nvarchar 列

java - 需要将 CSV 文件中的所有信息存储到数组中

python - 比较 pandas DataFrame 列中的多个字符串

sql - 按日期降序排列 - 月、日、年

sql - PL/SQL 神秘箭头运算符

c# - 使用 like 执行查询不起作用