Search This Blog

Monday, September 2, 2013

SYBASE: CONSLIDATE Mutliple ROWS INTO SINGLE Field with comma separated another logic


create table test1
(
col1 int,
col2 int,
col3 varchar(255) null,
flg  char(1) default  'N'
)

INSERT INTO test1 (col1,col2) values(1,2)
INSERT INTO test1 (col1,col2) values(1,3)
INSERT INTO test1 (col1,col2) values(2,4)
INSERT INTO test1 (col1,col2) values(2,5)

select * from test1

declare @col1 int
declare @col2 int
declare @counter int
set @counter=0

while ((select count(*) from test1 WHERE flg='N') >1)
begin
set rowcount 1
select @col1=col1,@col2=col2 from test1 WHERE flg='N'

select @col1,@col2

if (@counter=0)
begin
print 'inside counter 0'
update test1 set col3 = convert(varchar,@col2),flg='Y'
from test1
where col1=@col1
and col2=@col2
AND flg='N'
AND col3 is null
set @counter=1
end
select @col2=col2 from test1 WHERE flg='N' AND col1=@col1

if(@counter =1)
begin
print 'inside counter 1'
update test1 set col3 = convert(varchar,col2) + ','+convert(varchar,@col2),flg='Y'
from test1
where col1=@col1
AND flg='N'
AND col3 is not null
end
UPDATE test1 SET flg='Y'
where col1=@col1 and col2=@col2

set rowcount 0
end

select * from test1

No comments:

Post a Comment