Author |
Topic |
ayamas
Aged Yak Warrior
552 Posts |
Posted - 2008-06-09 : 23:18:42
|
Hi guys,I have a table like this.Declare @tbl as table(Invoiceid int,Dc varchar(100))Insert into @tblSelect 1,'101,102,104'union allSelect 2,'105,106,107' union allSelect 3,'110,111,112,113,114' union allSelect 4 ,'115'I want to split the values in the column Dc.The output should beInvoiceid Dc1--------- 1011--------- 1021--------- 1042--------- 1052--------- 1062--------- 107... and so on.Thanks for any help. |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-06-10 : 00:07:14
|
Create a function like this:-CREATE FUNCTION ParseValues (@String varchar(8000) ) RETURNS @RESULTS TABLE (ID int identity(1,1), Val int ) AS BEGIN DECLARE @Value varchar(100) WHILE @String is not null BEGIN SELECT @Value=CASE WHEN CHARINDEX(',',@String) >0 THEN LEFT(@String,CHARINDEX(',',@String)-1) ELSE @String END, @String=CASE WHEN CHARINDEX(',',@String) >0 THEN SUBSTRING(@String,CHARINDEX(',',@String)+1,LEN(@String)) ELSE NULL END INSERT INTO @RESULTS (Val) SELECT @Value END RETURN END and use it like thisDeclare @tbl as table(Invoiceid int,Dc varchar(100))Insert into @tblSelect 1,'101,102,104'union allSelect 2,'105,106,107' union allSelect 3,'110,111,112,113,114' union allSelect 4 ,'115'SELECT t.InvoiceId,b.Val FROM @tbl tCROSS APPLY ParseValues(t.Dc)bOutput------------------------------------------------InvoiceId Val----------- -----------1 1011 1021 1042 1052 1062 1073 1103 1113 1123 1133 1144 115 |
 |
|
ranganath
Posting Yak Master
209 Posts |
Posted - 2008-06-10 : 01:40:01
|
Hi,try with this alsoDeclare @tbl as table(Invoiceid int,Dc varchar(100))Insert into @tblSelect 1,'101,102,104'union allSelect 2,'105,106,107' union allSelect 3,'110,111,112,113,114' union allSelect 4 ,'115'DECLARE @delimiter NVARCHAR(5)SELECT @delimiter = ','SELECT s.Invoiceid,SUBSTRING(s.DC, v.Number - 1,COALESCE(NULLIF(CHARINDEX(',', s.DC, v.Number), 0), LEN(s.DC) + 1) - v.Number + 1) AS valueFROM @tbl AS sINNER JOIN master..spt_values AS v ON v.Type = 'p'WHERE SUBSTRING(',_' + s.DC, v.Number, 1) = ',' |
 |
|
ayamas
Aged Yak Warrior
552 Posts |
Posted - 2008-06-10 : 05:32:04
|
Thank you guys for your help & feedback.I ended up having this solution.Most part of it is inspired by visakhs solution.CREATE FUNCTION ParseValues (@String varchar(8000) ) RETURNS @RESULTS TABLE ( Val int) AS BEGIN DECLARE @x XmlSET @x='<i>'+REPLACE(@String,',','</i><i>')+'</i>'INSERT INTO @RESULTS (Val)SELECT x.i.value('.','int') FROM @x.nodes('//i')x(i) RETURN ENDDeclare @tbl as table(Invoiceid int,Dc varchar(100))Insert into @tblSelect 1,'101,102,104'union allSelect 2,'105,106,107' union allSelect 3,'110,111,112,113,114' union allSelect 4 ,'115'SELECT t.InvoiceId,b.Val FROM @tbl tCROSS APPLY ParseValues(t.Dc)b |
 |
|
|
|
|