0

I have a string field in which csv row is inserted

'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','','','','','','','','','','','','',''

I need to extract several fields from this csv format using t-sql. My main approach was to count colons (,) and based on the colon num to parse the data between two colons:

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

is there a better method that this one?

kjurkovic
  • 4,044
  • 2
  • 23
  • 28
  • 1
    possible duplicate of [Split Function equivalent in tsql?](http://stackoverflow.com/questions/697519/split-function-equivalent-in-tsql) – MatBailie Dec 14 '11 at 10:55

1 Answers1

2

If you prefer a more clear way, at least for me, you can do something like this:

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

It'll insert the different values in a table and then you can choose the needed values.

aF.
  • 64,980
  • 43
  • 135
  • 198