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
2
  • These posts and link are helpful to you. Commented Nov 17, 2012 at 10:53
  • Rows should get split by ',' and columns should get split by '|' Commented Nov 17, 2012 at 10:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

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.