views:

48

answers:

2
declare @mydata nvarchar(4000)    

set @mydata =  '36|0, 77|5, 132|61'

I have this data that I need to get into a table. So for Row1 columnA would be 36 and columnB would be 0. For Row2 columnA would be 77 and columnB would be 5 etc.

What is the best way to do this?

Thanks

+1  A: 

You need a split table-valued-function. There's plenty of examples on the web, e.g. http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648

CREATE FUNCTION dbo.Split
(
    @RowData nvarchar(2000),
    @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
    Id int identity(1,1),
    Data nvarchar(100)
) 
AS  
BEGIN 
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select 
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End

    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))

    Return
END
go

declare @mydata nvarchar(4000)     
set @mydata =  '36|0, 77|5, 132|61' 

select
    rowid, [1] as col1, [2] as col2
from
(
    select
        Row.Id as rowid, Col.Id as colid, Col.Data
    from dbo.Split(@mydata, ',') as Row
        cross apply dbo.Split(Row.Data, '|') as Col
) d
pivot
(
    min(d.data)
    for d.colid in ([1], [2])
) pd

I just picked the first split function I found. I don't thnk it's the best one but it works for this eample.

Ths outputs:

rowi     col1     col2
1   36  0
2   77  5
3   132 61
Daniel Renshaw
+1  A: 

If the data is in a file, you should be able tp bcp or BULK INSERT specifying row and column terminators

Otherwise, you'll need a nested split function

Of course, you could also send the data to SQL Server as xml

gbn