Shaggy
Shaggy

Reputation: 5800

SQL user defined function to split string to multiple column and rows

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

Upvotes: 1

Views: 6029

Answers (2)

heximal
heximal

Reputation: 10517

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

Upvotes: 1

roman
roman

Reputation: 117485

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

Upvotes: 2

Related Questions