Question : SQL query or stored procedure to denormalize and export data

I need to write a query or stored procedure that will get data out of a table and group the data in one cell of a table.  Here is what I need.

Here is the table in the database and sample data

ID    CustomerNumber     AccountID
1     123456                    ABC
2     123456                    DEF
3     654321                    GFK
4     987654                    LKJ
5     987654                    KMN

As you can see there can be multiple account IDs for a Customer number.
My Client wants the data exported to an Excel file in the following format.

Customer Number     Account IDs
123456                    ABC DEF
654321                    GFK
987654                    LKJ KMN

For some reason my client is insistant on having all the account IDs for a Customer number in a sigle cell.

So I am trying to write a query or Stored Procedure to put the data into a Temp table in the format the client wants so I can export it.  Getting the data into a Temp table with the following format will also work.

Customer Number     AccountID_1    AccountID_2   ....
123456                    ABC                 DEF
654321                    GFK
987654                    LKJ                  KMN

The number of account IDs for a customer number can vary.  There is no limit to how many account IDs can be associated with a customer number, but it will probably not exceed 10.  I would guess that I have to use a cusor to step through the records and combine the account IDs into one string for each customer number and then insert that into a temp table.  I just not sure how to go about it.  Or if there is an easier and better way.  I am using SQL Server 2000 and also out-putting the data to an ASP.NET web page.  Thanks for any help.

Andre

Answer : SQL query or stored procedure to denormalize and export data

CREATE FUNCTION udf_GetAccounts (@CustomerNumber int)
RETURNS varchar(250)
AS
BEGIN
DECLARE @accounts varchar(250)
SET @accounts = ''
SELECT @accounts = @accounts + AccountID + ',' FROM myTable WHERE CustomerNumber = @CustomerNumber
RETURN SUBSTRING(@accounts, 1, LEN(@accounts) - 1) --strip off the last comma
END

CREATE PROCEDURE sproc_GetAccounts
AS
CREATE TABLE #tmpTable (
     CustomerNumber int,
     Accounts varchar(250)
)

INSERT INTO #tmpTable (CustomerNumber, Accounts) SELECT CustomerNumber, dbo.udf_GetAccounts(CustomerNumber)
     FROM myTable GROUP BY CustomerNumber
GO
Random Solutions  
 
programming4us programming4us