| Author |
Topic |
|
slimt_slimt
Aged Yak Warrior
746 Posts |
Posted - 2012-07-10 : 12:20:48
|
hi,i have a following sample:create table repl (id varchar(300))goinsert into repl (id)select '123,12,some text,5334,234,23' union allselect '124,14,"some text, in quotes, with comma",5334,234,23' union allselect '125,11,even more text,5334,234,23'go and this is desired output:123||12||some text||5334||234||23124||14||some text, in quotes, with comma||5334||234||23125||11||even more text||5334||234||23So i want each comma to be replaces with ||, unless commas are in quotes (e.g.: line 2 of desired output).thanks |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-07-10 : 12:57:09
|
for the given sample data, this hack works!select replace(replace(replace(id,', ','@'),',','||'),'@',', ') from repl ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
nigelrivett
Master Smack Fu Yak Hacker
3385 Posts |
Posted - 2012-07-10 : 13:16:14
|
| Got carried away a bitNot suggesting you use this butdeclare @repl table (id varchar(300))insert into @repl (id)select '123,12,some text,5334,234,23' union allselect '124,14,"some text, in quotes, with comma",5334,234,23' union allselect '124,14,"some text, in quotes, with comma","some text, in quotes,,x,,again",5334,234,23' union allselect '125,11,even more text,5334,234,23';with cte1 as(select id = REPLACE(id,',','\\'), rownum = row_number() over (order by id) from @repl),cte2 as(select id, i=CHARINDEX('"',id), j=CHARINDEX('"',id, CHARINDEX('"',id)+1), seq = 1, rownum from cte1union allselect id, i=CHARINDEX('"',id, j+1), j=CHARINDEX('"',id, CHARINDEX('"',id,j+1)+1), seq = seq + 1, rownum from cte2 where CHARINDEX('"',id, j+1) <> 0), cte3 as(select id = replace(cte1.id,SUBSTRING(cte2.id,i,j-i+1), REPLACE(SUBSTRING(cte2.id,i,j-i+1),'\\',',')), cte1.rownum, seq = 2 from cte1 join cte2 on cte1.rownum = cte2.rownum and cte2.seq = 1 and cte2.j <> 0union allselect id = replace(cte3.id,SUBSTRING(cte2.id,i,j-i+1), REPLACE(SUBSTRING(cte2.id,i,j-i+1),'\\',',')), cte1.rownum, seq = cte3.seq + 1 from cte1 join cte2 on cte1.rownum = cte2.rownum join cte3 on cte3.rownum = cte2.rownum and cte2.seq = cte3.seq and cte2.j <> 0)select id from cte3 where seq = (select MAX(seq) from cte3 c3 where cte3.rownum = c3.rownum)union allselect id from cte1 where id not like '%"%'==========================================Cursors are useful if you don't know sql.SSIS can be used in a similar way.Beer is not cold and it isn't fizzy. |
 |
|
|
|
|
|