Hello, I'm new to SQL. Below is an example of what I am working with.
no vendor
2345 CPH
2410 NOE
2410 abcE
2419 CPH
2419 WWSP
2419 WWwP
I want to create a table like the following:
2345 CPH
2410 NOE, abcE
2419 CPH, WWSP, WWwP
I'm not sure how to put the loop within the query?? The script below only creates:
2419 CPH, WWSP, WWwP
Any solution, or better work around? Lead me to any good tutorials. Thank you in advance!
****************************************
create table #tmpvndlst(
vendid int identity(1,1),
opseq char(10),
vendor varchar(4))
INSERT INTO #tmpvndlst VALUES ('2345', 'CPH')
INSERT INTO #tmpvndlst VALUES ('2410', 'NOE')
INSERT INTO #tmpvndlst VALUES ('2410', 'abcE')
INSERT INTO #tmpvndlst VALUES ('2419', 'CPH')
INSERT INTO #tmpvndlst VALUES ('2419', 'WWSP')
INSERT INTO #tmpvndlst VALUES ('2419', '
select * from #tmpvndlst
declare @seq char(10)
declare @seq2 char(10)
declare @ln char(20)
declare @rows int
declare @cnt int
declare @fln char(20)
SELECT DISTINCT @seq2=opseq
from #tmpvndlst
group by opseq
HAVING COUNT(opseq) > 1
select @rows=count(opseq)
from #tmpvndlst
where opseq = @seq2
--print @rows
set @cnt = 1
set @ln = ''
while @cnt <= @rows
begin
select @seq=opseq, @ln=rtrim(@ln) + ', ' + a.vendor
from #tmpvndlst a
where a.opseq=@seq2
set @fln = rtrim(substring(@ln,3,len(@ln)))
set @cnt = @cnt + 1
set @ln = ''
end
print @seq + ' ' + @fln
drop table #tmpvndlst
no vendor
2345 CPH
2410 NOE
2410 abcE
2419 CPH
2419 WWSP
2419 WWwP
I want to create a table like the following:
2345 CPH
2410 NOE, abcE
2419 CPH, WWSP, WWwP
I'm not sure how to put the loop within the query?? The script below only creates:
2419 CPH, WWSP, WWwP
Any solution, or better work around? Lead me to any good tutorials. Thank you in advance!
****************************************
create table #tmpvndlst(
vendid int identity(1,1),
opseq char(10),
vendor varchar(4))
INSERT INTO #tmpvndlst VALUES ('2345', 'CPH')
INSERT INTO #tmpvndlst VALUES ('2410', 'NOE')
INSERT INTO #tmpvndlst VALUES ('2410', 'abcE')
INSERT INTO #tmpvndlst VALUES ('2419', 'CPH')
INSERT INTO #tmpvndlst VALUES ('2419', 'WWSP')
INSERT INTO #tmpvndlst VALUES ('2419', '
select * from #tmpvndlst
declare @seq char(10)
declare @seq2 char(10)
declare @ln char(20)
declare @rows int
declare @cnt int
declare @fln char(20)
SELECT DISTINCT @seq2=opseq
from #tmpvndlst
group by opseq
HAVING COUNT(opseq) > 1
select @rows=count(opseq)
from #tmpvndlst
where opseq = @seq2
--print @rows
set @cnt = 1
set @ln = ''
while @cnt <= @rows
begin
select @seq=opseq, @ln=rtrim(@ln) + ', ' + a.vendor
from #tmpvndlst a
where a.opseq=@seq2
set @fln = rtrim(substring(@ln,3,len(@ln)))
set @cnt = @cnt + 1
set @ln = ''
end
print @seq + ' ' + @fln
drop table #tmpvndlst