行的逗号分隔值

Comma separated values to rows

我写了下面的代码。它不工作

输入

A,B,C,D

QUERY(到目前为止我已经试过了)

Declare @products nvarchar(max)='A,B,C,D'
Declare @individual nvarchar(max)

Declare @Jurisdiction table
(
     JurisdictionX nvarchar(max)
)
WHILE LEN(@products) > 0
BEGIN
    IF PATINDEX('%,%',@products) > 0
    BEGIN
        SET @individual = SUBSTRING(@products, 0, PATINDEX('%,%',@products))
        SELECT @individual

        SET @products = SUBSTRING(@products, LEN(@individual + ',') + 1,
                                                     LEN(@products))
    END

    ELSE
    BEGIN
       SET @individual = @products
       SET @products = NULL
       Insert into @Jurisdiction values(@individual);
    END
END

Select * from @Jurisdiction;

期望输出

COLS
.....
 A
 B
 C
 D

我要执行插入操作。没用

您似乎没有指定列名:JurisdictionX

试试这个:Insert into @Jurisdiction(JurisdictionX) values(@individual);

我认为您正在尝试将 Comma Separated Values 插入行。

为此你可以使用这个查询

DECLARE @STR NVARCHAR(MAX)='A,B,C,D'

SELECT PARSENAME(REPLACE(Split.a.value('.', 'VARCHAR(100)'),',','.'),1) 'Ids' 
FROM  
(
     -- Select the string in XML format
     SELECT CAST ('<M>' + REPLACE(@STR, ',', '</M><M>') + '</M>' AS XML) AS Data         
) AS A 
CROSS APPLY Data.nodes ('/M') AS Split(a)

更新:根据OP

给出的代码
Declare @products nvarchar(max)='A,B,C,D'
Declare @individual nvarchar(max)

Declare @Jurisdiction table
(
JurisdictionX nvarchar(max)
)
WHILE LEN(@products) > 0
BEGIN
IF PATINDEX('%,%',@products) > 0
BEGIN
SET @individual = SUBSTRING(@products, 0, PATINDEX('%,%',@products))
SELECT @individual

SET @products = SUBSTRING(@products, LEN(@individual + ',') + 1,
                                     LEN(@products))
END
ELSE
BEGIN
SET @individual = @products
SET @products = NULL
Insert into @Jurisdiction values(@individual);
END
END

Select * from @Jurisdiction;