I wrote a function which returns a table with single column with data separated as ‘|’.
Example if you pass parameter to function as funsplit('SAGAR|INDIA|MUMBAI','|')
it returns as
Item<Column Name>
SAGAR
INDIA
MUMBAI
I want it as
COLUMN 1 COLUMN2 COLUMN3
-----------------------------
SAGAR INDIA MUMBAI
Here is my function
ALTER FUNCTION [dbo].[funSplit]
(
@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
This will transpose your results.
If the order matters to you, you need to return that order from your function
If the columns are variable, then you can create the above with dynamic SQL and use
sp_executesql