Team,
i have another scenario, i need to split 4 columns and also 8 columns split,
i changed the beginning code
declare @numCols int = 4
i tried to change the final join statement, not able to achieve, Can you help on this.
i could not able to join the single join statement at the end of the function
declare @String varchar(max)
set @String='sunday,9,meals,EYR,sunday,9,meals,USD,monday,9,meals,USD,friday,9,meals,USD'
begin
declare @numCols int = 4
declare @itr int = 0
declare @SplittedValues table
(
rowID int,
colID int,
Id varchar(50)
)
declare @SplitLength int, @Delimiter varchar(5)
set @Delimiter = ','
while len(@String) > 0
begin
select @SplitLength = (case charindex(@Delimiter,@String) when 0 then
len(@String) else charindex(@Delimiter,@String) -1 end)
insert into @SplittedValues(rowID, colID, Id)
select @itr / @numCols, @itr % @numCols, substring(@String,1,@SplitLength)
select @String = (case (len(@String) - @SplitLength) when 0 then ''
else right(@String, len(@String) - @SplitLength - 1) end)
set @itr = @itr + 1
end
select * From @SplittedValues
select l.id as LeftId, r.id as RightId
from
(select rowid, id from @SplittedValues where colid = 0) l
join
(select rowid, id from @SplittedValues where colid = 1) r
on l.rowid = r.rowID
---need to join single statement
select m.id as LeftId, n.id as RightId
from
(select rowid, id from @SplittedValues where colid = 2) m
join
(select rowid, id from @SplittedValues where colid = 3) n
on m.rowid = n.rowID
--return
END
Team, can you help
I need to split 8 columns.
select * From dbo.EightColumnSplit(Sunday,9,USD,10,USD,Billable,Meals,25,Monday,9,USD,10,USD,Billable,Meals,25)
I need split columns like below
- Sunday,9,USD,10,USD,Billable, Meals,25
- Monday,9,USD,10,USD,Billable,Meals,25
select * From dbo.TwoColumnSplit('Sunday,9,Monday,9,Tuesday,8,wed,9')
Create function dbo.TwoColumnSplit
(
@String varchar(max)
)
returns @returnTable table
(
LeftId varchar(50)
, RightId varchar(50)
)
as
begin
declare @numCols int = 2
declare @itr int = 0
declare @SplittedValues table
(
rowID int,
colID int,
Id varchar(50)
)
declare @SplitLength int, @Delimiter varchar(5)
set @Delimiter = ','
while len(@String) > 0
begin
select @SplitLength = (case charindex(@Delimiter,@String) when 0 then
len(@String) else charindex(@Delimiter,@String) -1 end)
insert into @SplittedValues(rowID, colID, Id)
select @itr / @numCols, @itr % @numCols, substring(@String,1,@SplitLength)
select @String = (case (len(@String) - @SplitLength) when 0 then ''
else right(@String, len(@String) - @SplitLength - 1) end)
set @itr = @itr + 1
end
insert into @returnTable(LeftId, RightId)
select l.id as LeftId, r.id as RightId
from
(select rowid, id from @SplittedValues where colid = 0) l
join
(select rowid, id from @SplittedValues where colid = 1) r
on l.rowid = r.rowID
return
END