1

I have string with format 'S1CW3733|1050105000224,S1CW4923|1050105000009'

I have function in SQL which Convert it in format

item
S1CW3733|1050105000224
S1CW4923|1050105000009

is it possible to do it this way ? (multiple column)

item       item2
S1CW3733   1050105000224
S1CW4923   1050105000009

My function:-

ALTER Function [dbo].[fnSplit]
(
    @sInputList Varchar(8000), -- List of delimited items  
    @sDelimiter VarChar(8000) = ',' -- delimiter that separates items  
) 
Returns @List Table (item VarChar(8000))  
Begin  
 Declare @sItem VarChar(8000)  

 While CharIndex(@sDelimiter,@sInputList,0) <> 0  
  Begin  
   Select   
   @sItem=RTrim(LTrim(SubString(@sInputList,1,CharIndex(@sDelimiter,@sInputList,0)-1))),  
   @sInputList=RTrim(LTrim(SubString(@sInputList,CharIndex(@sDelimiter,@sInputList,0)+Len(@sDelimiter),Len(@sInputList))))  

   If Len(@sItem) > 0  
    Insert Into @List Select @sItem  
 End  

 If Len(@sInputList) > 0  
  Insert Into @List Select @sInputList -- Put the last item in  

 Return  
End
palacsint
  • 28,416
  • 10
  • 82
  • 109
Shaggy
  • 5,422
  • 28
  • 98
  • 163
  • These [posts](http://stackoverflow.com/questions/11185318/how-to-separate-string-into-different-columns) and [link](http://www.codeproject.com/Articles/7938/SQL-User-Defined-Function-to-Parse-a-Delimited-Str) are helpful to you. – bonCodigo Nov 17 '12 at 10:53
  • Rows should get split by ',' and columns should get split by '|' – Shaggy Nov 17 '12 at 10:56

2 Answers2

2

well if you have only two columns, you allways can do this

select
    left(f.item, c.c - 1) as item1,
    right(f.item, len(f.item) - c.c) as item12
from dbo.fnSplit('S1CW3733|1050105000224,S1CW4923|1050105000009', ',') as f
    outer apply (select charindex('|', f.item) as c) as c

I have not checked if charindex != 0, so you can add this check.

If, however, you have multiple columns delimited by '|', I don't think there's a way to do it without dynamic SQL

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
1

Another way. You can modify your function. The function must expect additional parameter - which part of splitted string to return. So in your sql request you will do something like this:

select
  fnSplit(item, ',', '|', 0) as item_left,
  fnSplit(item, ',', '|', 1) as item_right
from
  mytable

in this case the function must look like

    ALTER Function [dbo].[fnSplit]
    (
        @sInputList Varchar(8000), -- List of delimited items  
        @sDelimiter1 VarChar(8000) = ',', -- delimiter that separates items  
        @sDelimiter2 VarChar(8000) = '|', -- delimiter that separates splitted item
        @which_part int = 0 -- if 0 return left part, 1 -right part
    ) 
    Returns VarChar(8000)
... business login here
heximal
  • 10,327
  • 5
  • 46
  • 69