将逗号分隔值拆分为行

时间:2014-11-05 10:41:32

标签: sql-server regex tsql

如何从SQL Server中的逗号分隔字符串中获取值到行中,以便将它们插入到表中?

例如,使用此数据:

 Declare @string as nvarchar(max);
 Declare @substring as nvarchar(50);
 set @string = "Apple, Banana, Cherry, Orange, Mango"

我目前已对此示例进行了硬编码set @last = 2,但@last应包含字符串中的字数。参数@substring将在循环中逐个包含每个水果,我想用它来插入目标表。

这是我当前的代码,但我仍然坚持如何将@last设置为所需的值:

DECLARE @first AS INT
SET @first = 1
DECLARE @step AS INT
SET @step = 1
DECLARE @last AS INT
SET @last = 2

BEGIN TRANSACTION
WHILE(@first <= @last)
BEGIN

INSERT INTO tbFruit(Name)   
VALUES(@substring);

SET @first += @step
END
COMMIT TRANSACTION

2 个答案:

答案 0 :(得分:4)

您可以一次性完成所有操作,而不是使用WHILE循环。因此,在此代码中,它会将值推送到临时表的行中,然后将其用于INSERT到目标表中:

将逗号分隔值拆分为以下行的示例代码:

Convert Comma Separated column value to rows

DECLARE @string AS NVARCHAR(MAX);
DECLARE @substring AS NVARCHAR(50);
SET @string = 'Apple, Banana, Cherry, Orange, Mango'

SELECT Split.a.value('.', 'VARCHAR(100)') AS Fruits
INTO   #fruits
FROM   
   (
     SELECT CAST ('<M>' + REPLACE(@string, ', ', '</M><M>') + '</M>' AS XML) AS String
   ) AS A
     CROSS APPLY String.nodes('/M') AS Split ( a ); 

-- show what's in the temp table
SELECT *
FROM   #fruits

此时,您在临时表中的行中有值,您可以使用它来填充目标表,如下所示:

INSERT INTO tbFruit ( Name )
SELECT Fruits FROM #fruits

-- show what's in the target table
SELECT * FROM   #target_table

-- tidy up
DROP TABLE #fruits

SQL Fiddle Demo

TSQL代码:

 DECLARE @string AS NVARCHAR(MAX) = 'Apple, Banana, Cherry, Orange, Mango'
 DECLARE @substring AS NVARCHAR(50)

 SELECT Split.a.value('.', 'VARCHAR(100)') AS Fruits
 INTO   #fruits
 FROM   ( SELECT    CAST ('<M>' + REPLACE(@string, ', ', '</M><M>') + '</M>' AS XML) AS String
        ) AS A
        CROSS APPLY String.nodes('/M') AS Split ( a )   

 CREATE TABLE #target_table ( Fruits NVARCHAR(50) )

 INSERT INTO #target_table
        ( fruits )
        SELECT  *
        FROM    #fruits

 SELECT * FROM   #target_table

 DROP TABLE #fruits
 DROP TABLE #target_table

<强>结果:

| FRUITS |
|--------|
|  Apple |
| Banana |
| Cherry |
| Orange |
|  Mango |

答案 1 :(得分:0)

请尝试以下代码:

DECLARE @string VARCHAR(MAX),
@Split CHAR(1),
@X xml

--The String containg the fruit names separated by comma.
SELECT @string = 'Apple, Banana, Cherry, Orange, Mango',

--Separator in the String.
@Split = ','

--Use XML to extract the fruit names.
SELECT @X = CONVERT(xml,'<root><s>' + REPLACE(@string,@Split,'</s><s>') + '</s></root>')

--Insert the fruit names into the table.
INSERT INTO tbFruit (Name) SELECT T.c.value('.','varchar(max)')
FROM @X.nodes('/root/s') T(c)