![](/img/trans.png)
[英]How to parse a String field to another type while importing from CSV in SQL Server 2012?
[英]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.