1

I have a table containing the following text per row

"[0,0,0,1,2,4,1,0,0,2,0,0,0,0,847,18207,0,0,0,0,0,0,0,0,0,0,0,0]"

Now i want to insert these 28 values in a table containing 28 columns. I tried a few split functions but these would return only rows.

Any ideas?

5
  • SQL Server has no concept of "string array". How is the data actually stored? Commented Apr 4, 2016 at 13:53
  • use a split function and then dynamically pivot it's results. Commented Apr 4, 2016 at 13:56
  • is it always fixed 28 values into 28 columns ? Commented Apr 4, 2016 at 13:57
  • always 28 values -- destination table actually has 30 columns - 28 for the values, one key column, one other column. Value / column amount will not change. Commented Apr 4, 2016 at 14:00
  • select "insert into table28 values(" + SUBSTRING(text, 2, LEN(text) -2) + ");" as "sql" from table, run, copy column, paste and run :) Commented Apr 4, 2016 at 14:09

2 Answers 2

3

using dbo.fnParseString()

INSERT INTO a_table (col1, col2, col3, . . . )
SELECT dbo.fnParseString(-1, ',', str)
      ,dbo.fnParseString(-2, ',', str)
      ,dbo.fnParseString(-3, ',', str)
      ,....
FROM  yourtable 
Sign up to request clarification or add additional context in comments.

3 Comments

I agree that a splitter is a good approach but the splitter you referenced is horribly inefficient. You do NOT need to resort to looping for splitting strings. sqlperformance.com/2012/07/t-sql-queries/split-strings or here. sqlservercentral.com/articles/Tally+Table/72993
those splits CSV into rows. OP required it in column
Right. But you don't need a loop for that. You can use crosstab or pivot to get them back into columns. This would be a great time for an xml splitter.
1
DECLARE @x XML

;with cte as (
SELECT '[0,0,0,1,2,4,1,0,0,2,0,0,0,0,847,18207,0,0,0,0,0,0,0,0,0,0,0,0]' as col
)

SELECT @x= (
SELECT CAST('<s>' + REPLACE(REPLACE(REPLACE(col,'[','<a>'),']','</a>'),',','</a><a>') +'</s>'AS XML)
FROM cte
FOR XML PATH('')
)


SELECT  t.v.value('a[1]','int'),
        t.v.value('a[2]','int'),
        t.v.value('a[3]','int'),
        ...
        t.v.value('a[28]','int')
FROM @x.nodes('/s') as t(v)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.