|
|
Question : normalize a delimited list field
|
|
I have a field that contains a pipe delimited list here are 5 rows as an example:
0|3| 1|3| 0|2|3| 0|
I would like to concanetate these fields together so that instead of 5 rows I would get one like this:
0|3|1|3|0|2|3|0|
I need to do this in SQL (t-sql) as it will be part of a derived table as part of another query.
But how do I return one row from multiple?
|
Answer : normalize a delimited list field
|
|
consider EE as the table, while EE temp is used to compute the results:
create table ee ( d varchar(100)) set nocount on go insert into EE values ('0|3|') insert into EE values ('1|3|') insert into EE values ('0|2|3|') insert into EE values ('0|')
-- insert int EE values ('0|3|1|3|0|2|3|0|') go create table EETemp ( d varchar(100), parts int , part int) go declare @rowcount int
insert into EETemp select d, len(d) - len(replace(d, '|' , '' )) , 0 from EE set @rowcount = @@rowcount
while @rowcount > 0 begin update EETemp set part = 1 where parts > 1 insert into EETemp select d,parts,2 from EETemp where part = 1 set @rowcount = @@rowcount
update EETemp set d = substring(d,1, charindex('|',d)) , parts = 1, part = 0 where part = 1 update EETemp set d = substring(d,charindex('|',d)+1, len(d)) , parts = parts-1, part = 0 where part = 2 end
update EETemp set d = replace(d,'|','')
select * from EE select d, count(*) from EETemp group by d
go drop table EE go drop table EETemp
CHeers
|
|
|
|
|