将csv值转换为表

时间:2014-07-10 15:49:44

标签: sql-server-2008 tsql csv

DATA:

id  data
114 10047,10001,10003
123 90080
233 10020,10029,10032,10065

TABLE:

DECLARE @TEMP TABLE (id int 
                    ,data varchar(50)
                    PRIMARY KEY (id)
                    )

INSERT INTO @TEMP VALUES (114,'10047,10001,10003')
INSERT INTO @TEMP VALUES (123,'90080')
INSERT INTO @TEMP VALUES (233,'10020,10029,10032,10065')

鉴于以上数据,我试图将逗号分隔值转换为表,以便我可以加入值,我已经有一个函数,通过将单个值作为参数正常工作,我该如何调用函数它遍历上面的每一行(不使用游标)并输出这样的值:

id  data
114 10047
114 10001
114 10003
123 90080
233 10020
233 10029
233 10032
233 10065

功能:

FUNCTION [dbo].[ConvertCsvToTable](@csvList nvarchar(MAX))
RETURNS @csvTable table([id] int NOT NULL)

AS
BEGIN
DECLARE @pos int
DECLARE @nextPos int
DECLARE @valueLen int

SELECT @pos = 0, @nextPos = 1

WHILE @nextPos > 0
BEGIN
  SELECT @nextPos = charindex(',', @csvList, @pos + 1)
  SELECT @valueLen = CASE WHEN @nextPos > 0
                          THEN @nextPos
                          ELSE len(@csvList) + 1
                     END - @pos - 1
  INSERT @csvTable (id)
     VALUES (convert(int, substring(@csvList, @pos + 1, @valueLen)))
  SELECT @pos = @nextPos
END

RETURN
END

1 个答案:

答案 0 :(得分:1)

如果将逗号分隔值转换为XML数据,则可以使用更简单的解决方案。您的结果可以使用如下单个选择语句来实现:

-- Improve table structure adding XML field
DECLARE @TEMP TABLE (id int 
                ,data varchar(50)
                ,xmldata xml
                PRIMARY KEY (id)
                )

-- Your initial data
INSERT INTO @TEMP VALUES (114,'10047,10001,10003',null)
INSERT INTO @TEMP VALUES (123,'90080',null)
INSERT INTO @TEMP VALUES (233,'10020,10029,10032,10065',null)

-- Transforming CSV string to XML
UPDATE @TEMP
SET xmldata = CONVERT(XML, '<DATA><RAW>'+REPLACE(data, ',', '</RAW><RAW>')+'</RAW></DATA>')

-- Query XML data to obtain required result
SELECT  t.id,
        x.xmldata.value('(.)[1]','INT') AS data
  FROM  @TEMP t
  CROSS APPLY t.xmldata.nodes('/DATA/RAW') x(xmldata);