繁体   English   中英

如果该字符串是csv格式,如何解析SQL Server 2008中的字符串字段

[英]How to parse String field in SQL Server 2008 if that String is in csv format

我有一个字符串字段,其中插入了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-sql从这个csv格式中提取几个字段。 我的主要方法是计算冒号(,)并基于冒号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

它会在表格中插入不同的值,然后您可以选择所需的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM