Sql Question about combining records.
Hello all,
Great forums, I have been lurking for some information.
I have a table with records that have duplicate ID's but differant desciptions , im trying to combine all of the desciptions into one record.I.E.
Id Description ID2
01 Big 101
01 Brown 102
01 House 103
Id like to have 01 Big Brown House 101
Where would a good place to start? Im not new to Sql but im by no means an expert. So any help would be grealt appriciated.
[602 byte] By [
BrownRJ] at [2007-11-11 7:58:40]

# 2 Re: Sql Question about combining records.
The following solution uses a cursor and a temporary table - You'll need to test it. The results are displayed from the temporary table (table is not modified)
You might want to look at setting unique or primary key constraints on the table.
-- Create temporary table
create table #t1
(
Id int,
description varchar(200),
Id2 int)
-- Declare some variables
declare @Id int
declare @Description varchar(200)
declare @Id2 int
declare @oldId int
-- Use a cursor to enum all the rows in the table. Order By Id1 so that all duplicates are displayed together,
-- then by Id2 (so Big displays before Brown etc and Id2 of Big is used)
-- Change test1 to the name of your table!
declare c1 cursor for select Id,Description,Id2 from test1 order by Id,Id2
set @OldId = -1 --Set an initital value for OldId that won't match with Id in table
-- Open cursor
open c1
fetch next from c1
into @Id,@Description,@Id2
--Run the following until all rows in the table have been processed
WHILE @@FETCH_STATUS = 0
BEGIN
-- Check if id is same as previous id. If it is, update temporary table to append description
if @oldId = @Id
update #t1 set description = description + ' ' + @description where Id = @Id
if @oldId <> @Id --If not insert a new row
insert into #t1 values(@Id,@description,@Id2)
set @oldId = @Id
fetch next from c1
into @Id,@Description,@Id2
END
close c1
deallocate c1
select * from #t1
# 4 Re: Sql Question about combining records.
The code I posted is T-SQL (SQL Server). If you are importing the data from Access to SQL Server there should be no problem.
I don't use Access much, but you could probably write some VBA code in place of the stored procedure. The SP in SQL server is a better option if youre exporting to SQL Server anyway.