July 11, 2019 at 2:02 pm
Hi Guys,
I have one task and i need to build the logic to split the columns by comma,
see below for table definition
CREATE TABLE #X1
(SCHID VARCHAR(250))
INSERT INTO #X1 VALUES ('101,102,103,104,105,106,107')
The desired output should be,
IDAdditionalIds
101102|103|104|105|106|107
Can you please help me to build this? I appropriate for your help, and Thanks for your help.
July 11, 2019 at 2:11 pm
all you need isย String Splitter
July 11, 2019 at 2:30 pm
So the number of columns returned = (number 0f commas + 1), is that correct?
What happens if the number of commas varies by input data row?
What should the columns be called?
July 11, 2019 at 2:33 pm
Thanks for your reply,
The First Column need to have only one Value before comma, and rest it need to go to other column.
July 11, 2019 at 2:39 pm
Seems like the easiest would be to use CHARINDEX
and STUFF
:
SELECT I.ID,
I.AdditionalIDs
FROM (VALUES ('101,102,103,104,105,106,107')) X1(SCHID)
CROSS APPLY (VALUES(LEFT(X1.SCHID,NULLIF(CHARINDEX(',',X1.SCHID),0)-1),STUFF(X1.SCHID,1,NULLIF(CHARINDEX(',',X1.SCHID),0),'')))I(ID,AdditionalIDs);
You could also write the above as follows, which may be easier to read:
SELECT I.ID,
I.AdditionalIDs
FROM (VALUES ('101,102,103,104,105,106,107')) X1(SCHID)
CROSS APPLY (VALUES(NULLIF(CHARINDEX(',',X1.SCHID),0))) CI(I)
CROSS APPLY (VALUES(LEFT(X1.SCHID,CI.I-1),STUFF(X1.SCHID,1,CI.I,'')))I(ID,AdditionalIDs);
Thom~
Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
Larnu.uk
July 11, 2019 at 2:40 pm
or such one:
with data as
(select '101,102,103,104,105,106,107' [SCHID])
select
left(SCHID,charindex(',',SCHID)-1) [Id]
,stuff(SCHID,1,charindex(',',SCHID),'') [AdditionalIds]
from data
July 11, 2019 at 2:45 pm
July 11, 2019 at 3:10 pm
Thanks Guys,
It helps me to develop in my logic.
July 11, 2019 at 3:32 pm
SELECT LEFT(SCHID, x.Pos - 1) [Id],
REPLACE(SUBSTRING(SCHID, x.Pos + 1, 8000),',','|') [AdditionalIds]
FROM #X1
CROSS APPLY(VALUES (CHARINDEX(',', SCHID))) x(Pos)
Viewing 10 posts - 1 through 9 (of 9 total)
You must be logged in to reply to this topic. Login to reply