Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 在SQL中将值从一列拆分为具有不同分隔符的多列_Sql Server - Fatal编程技术网

Sql server 在SQL中将值从一列拆分为具有不同分隔符的多列

Sql server 在SQL中将值从一列拆分为具有不同分隔符的多列,sql-server,Sql Server,如何以任何可能的方式在SQL中实现这一点 请参见下面的图片: || Id || Column1 || || 1000 || SA(13), DS(1) || || 2000 || QW(1) || || 3000 || TE(23), RE(1), BB(40), VV(5) || 结果应该是: || Id ||

如何以任何可能的方式在SQL中实现这一点

请参见下面的图片:

||    Id    ||    Column1                      ||
||  1000    ||  SA(13), DS(1)                  ||
||  2000    ||  QW(1)                          ||
||  3000    ||  TE(23), RE(1), BB(40), VV(5)   ||
结果应该是:

|| Id   ||  Column2    ||  Colum3  ||
|| 1000 ||    SA       ||    13    ||
|| 1000 ||    DS       ||     1    ||
|| 2000 ||    QW       ||     1    ||
|| 3000 ||    TE       ||    23    ||
|| 3000 ||    RE       ||     1    ||
|| 3000 ||    BB       ||    40    ||
|| 3000 ||    VV       ||     5    ||

在SQL Server中执行此操作的一种方法是递归CTE:

with cte as (
      select id,
             left(column1, charindex(',', column1) - 1) as col23,
             substring(column1, charindex(',', column1) + 1) + ',' as rest
      from t
      union all
      select id,
             left(rest, charindex(',', rest) - 1) as col23
             substring(rest, charindex(',', rest) + 1) as rest
      from t
      where rest like '%,%'
     )
select id, left(col23, 2) as column2,
       replace(replace(substring(col23, 3, len(col23)), '(', ''), ')', '') as column3
from cte;

注意:这假设
column2
有两个字符(如示例数据中所示)。如果这可能有所不同,您也可以使用Jeff Moden提供的CSV拆分器功能以及
left()
substring()
,使用
col23
来进行拆分:

返回:

测试设置:

拆分字符串引用:


这显示了一个非常糟糕的数据库设计:(这些是很好的链接!是否有一个查询不需要函数,我没有在我们的数据库中运行函数的访问权限database@drummerboi不需要函数。我遇到此错误“传递给左或子字符串函数的长度参数无效”@drummerboi这里有一个基于Gordon答案的工作版本:@drummerboi请记住接受Gordon的答案,因为它已经引导您找到了解决方案。
select 
    Id
 , col2 = left(x.Item,charindex('(',x.Item)-1)
 , col3 = substring(x.Item
          ,charindex('(',x.Item)+1
          ,charindex(')',x.Item)-charindex('(',x.Item)-1
          )
from t
  cross apply (
    select Item = ltrim(rtrim(i.Item))
      from [dbo].[delimitedsplit8K](t.col,',') as i
      ) x
+------+------+------+
|  Id  | col2 | col3 |
+------+------+------+
| 1000 | SA   |   13 |
| 1000 | DS   |    1 |
| 2000 | QW   |    1 |
| 3000 | TE   |   23 |
| 3000 | RE   |    1 |
| 3000 | BB   |   40 |
| 3000 | VV   |    5 |
+------+------+------+