2011-12-14 62 views
0

我在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 

有沒有更好的方法,這一個?

+1

可能重複的[在tsql中的分割函數等效?](http://stackoverflow.com/questions/697519/split-function-equivalent-in-tsql) – MatBailie 2011-12-14 10:55:13

回答

2

如果你喜歡一個更清晰的方式,至少對我來說,你可以做這樣的事情:

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 

它會在一個表中插入不同的值,然後你可以選擇需要的值。