Link to home
Start Free TrialLog in
Avatar of Xeavn
Xeavn

asked on

Multiple Rows into a Single Row

I am trying to join Multiple Rows into a single Row for this stored procedure, so that it will look like the following:

Parameter       Price         Method

Copper            $11            200.8, 6020, 345.1
Arsenic            $11            200.8, 6020

For each unique combination of Parameter and Price. The Method table of course has multiple entries for each parameter, and usually at the same price.

Here is my stored procedure so far:

CREATE PROCEDURE [sp_PriceList2]
AS
SET NOCOUNT ON
DECLARE @price            DECIMAL(7, 2)
DECLARE @prmid            INTEGER
DECLARE @mthdtmp            NVARCHAR(30)
DECLARE @mthdrow            NVARCHAR(200)
DECLARE @my_cur CURSOR
DECLARE @my_cur2 CURSOR
SELECT @mthdrow = ''
SET @my_cur = CURSOR FOR
      SELECT DISTINCT PRM_ID,  MTHD_PRICE FROM PARAMETERS INNER JOIN METHODS ON MTHD_PRMID = PRM_ID
      WHERE MTHD_PRICE > 0

OPEN @my_cur
FETCH NEXT FROM @my_cur INTO @prmid, @price
WHILE @@FETCH_STATUS = 0
BEGIN
      SET @my_cur2 = CURSOR FOR
      SELECT MTHD_REF FROM METHODS WHERE MTHD_PRMID = @prmid AND MTHD_PRICE = @price
      OPEN @my_cur2
      FETCH NEXT FROM @my_cur2 INTO @mthdtmp
      WHILE @@FETCH_STATUS = 0
            BEGIN
                  SELECT @mthdrow = @mthdrow + @mthdtmp + ','
                  FETCH NEXT FROM @my_cur2 INTO @mthdtmp
            END
            CLOSE @my_cur2
            DEALLOCATE @my_cur2
            SELECT DISTINCT PRM_ID, PRM_ABBREV, MTHD_PRICE, @mthdrow FROM PARAMETERS INNER JOIN METHODS ON MTHD_PRMID = PRM_ID
            WHERE PRM_ID = @prmid AND MTHD_PRICE = @price

            SELECT @mthdrow = ' '

FETCH NEXT FROM @my_cur INTO @prmid, @price
END
CLOSE @my_cur
DEALLOCATE @my_cur
GO

This almost does what I want it to. It actually returns about 290 different single line tables. I need someway to merge all those together, and someway to tell when I am on my last Fetch into Cursor 2, so that I can drop that last comma off.


ASKER CERTIFIED SOLUTION
Avatar of rw3admin
rw3admin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Xeavn
Xeavn

ASKER

Thanks rw3admin,

It wasn't completely what I was after, but it was close enough that I was able to figure the rest out on my own.
Thanks,
Yes I didnt mess with your code I just wanted to give you an example, I knew you were intelligent enough to figure how to make it work in your own code.

rw3admin