如何解析字符串字段在SQL Server 2008中,如果该字符串是CSV格式
问题描述:
我在CSV行插入如何解析字符串字段在SQL Server 2008中,如果该字符串是CSV格式
'6 33','318011385','3183300153','Z','21.11.2011 13:33:22','51','51','2','0','032425','','','','','8 50318011100 318069332','','21.11.2011','21.11.2011','','0','','','GOT','0','0','0','0','0','0','0','0','0','0','0','21.11.2011','4','','','','','','','','','','','','',''
我需要使用T-从这个CSV格式提取几个字段串场SQL。 我的主要方法是计数冒号(,)和基于结肠NUM两个冒号之间解析数据:
select min(SUBSTRING(field,charindex(''',''',recorddata,charindex(''',''',recorddata)+1)+3,CHARINDEX(''',''',field,charindex(''',''',field,charindex(''',''',field)+1)+3) - (charindex(''',''',field,charindex(''',''',field)+1)+3))) as fld from TBLSYNCEXPORT where SUBSTRING(field,2,CHARINDEX(''',''',field,0)-2) = @type and substring(field,CHARINDEX(''',''',field)+3,3) = @person and SUBSTRING(field,charindex(''',''',field,charindex(''',''',field)+1)+3,CHARINDEX(''',''',field,charindex(''',''',field,charindex(''',''',field)+1)+3) - (charindex(''',''',field,charindex(''',''',field)+1)+3)) > @prev_type
有没有更好的方法,这一个?
答
如果你喜欢一个更清晰的方式,至少对我来说,你可以做这样的事情:
CREATE TABLE #destination_table(
value varchar(10)
)
DECLARE @position INT
DECLARE @source_string VARCHAR(1000)
SELECT @source_string = "'6 33','318011385','3183300153','Z','21.11.2011 13:33:22','51','51','2','0','032425','','','','','8 50318011100 318069332','','21.11.2011','21.11.2011','','0','','','GOT','0','0','0','0','0','0','0','0','0','0','0','21.11.2011','4','','','','','','','','','','','','',''"
SELECT @position = CHARINDEX(',', @source_string)
WHILE @position <> 0
BEGIN
INSERT INTO #destination_table VALUES(LEFT(@source_string, @position-1))
SELECT @source_string = STUFF(@source_string, 1, @position, NULL)
SELECT @position = CHARINDEX(',', @source_string)
END
INSERT INTO #destination_table VALUES(@source_string)
SELECT * FROM #destination_table
-- or select what you need
select value from #destination_table where id = 2
drop table #destination_table
它会在一个表中插入不同的值,然后你可以选择需要的值。
可能重复的[在tsql中的分割函数等效?](http://stackoverflow.com/questions/697519/split-function-equivalent-in-tsql) – MatBailie 2011-12-14 10:55:13