如何使用SQL Server中的条件将一列分隔为多个

时间:2018-04-05 05:09:28

标签: sql-server sql-server-2008

我希望根据条件将一列分成多个列。

表:emp

CREATE TABLE [dbo].[emp]
(
    [name] [varchar](200) NULL,
    [id] [int] NULL
) ON [PRIMARY]
GO

INSERT [dbo].[emp] ([name], [id]) 
VALUES (N'lux-pen-oxo-mobile', 1), 
       (N'pne-soap', 2),
       (N'hop-pen-mobile-soap-jad', 3),
       (N'pen-soap-box', 4)

根据以上数据,我想要输出如下:

id  |prod1  |prod2   |prod3   |prod4    | Prod5
1   |lux    |pen     |oxo     |mobile   |   
2   |pne    |soap    |        |         |
3   |hop    |pen     |mobile  |soap     |jad    
4   |pen    |soap    |box     |

我试过这样:

select  
    id,
    case 
       when charindex('-', name) > 0 
          then substring(name, 1, charindex('-', [name]) - 1) 
    end prod1,
    substring(name, charindex('-', [name], 2) + 1, len(name)) prod2,
    substring(name, charindex('-', [name], 3) + 1, len(name)) prod3,
    substring(name, charindex('-', [name], 4) + 1, len(name)) prod4,
    substring(name, charindex('-', [name], 5) + 1, len(name)) prod4 
from 
    [emp]

此查询未返回预期结果。

请告诉我如何编写查询以在SQL Server中实现此任务。

1 个答案:

答案 0 :(得分:0)

您可以使用CTE执行此操作,例如以下示例。

;WITH Split_Names (ID,xmlname)
AS
(
    SELECT ID,      
    CONVERT(XML,'<Names><name>'  
    + REPLACE(Name,'-', '</name><name>') + '</name></Names>') AS xmlname
      FROM [dbo].[emp]
)

SELECT ID,      
xmlname.value('/Names[1]/name[1]','varchar(100)') AS prod1,    
xmlname.value('/Names[1]/name[2]','varchar(100)') AS prod2,
xmlname.value('/Names[1]/name[3]','varchar(100)') AS prod3,
xmlname.value('/Names[1]/name[4]','varchar(100)') AS prod4,
xmlname.value('/Names[1]/name[5]','varchar(100)') AS prod5   
FROM Split_Names

<强>输出

+----+-------+-------+--------+--------+-------+
| ID | prod1 | prod2 | prod3  | prod4  | prod5 |
+----+-------+-------+--------+--------+-------+
| 1  | lux   | pen   | oxo    | mobile | NULL  |
+----+-------+-------+--------+--------+-------+
| 2  | pne   | soap  | NULL   | NULL   | NULL  |
+----+-------+-------+--------+--------+-------+
| 3  | hop   | pen   | mobile | soap   | jad   |
+----+-------+-------+--------+--------+-------+
| 4  | pen   | soap  | box    | NULL   | NULL  |
+----+-------+-------+--------+--------+-------+

如果您想将NULL替换为'',那么您可以更改select中的列,如下所示。

ISNULL(xmlname.value('/Names[1]/name[1]','varchar(100)'),'') AS prod1  ,  

Live Demo