Union select statements within the while loop T-SQL

2.3k views Asked by At

I'm trying to use cursors to dynamically produce a result set. following is the code

        DECLARE           @ MilestoneName VARCHAR(100),
        @MilestoneSts  VARCHAR(100),
        @ProjectPre    VARCHAR(10),
        @ProjectID     VARCHAR(10),
        @Center        VARCHAR(20),
        @CenterPre     VARCHAR(20),
        @Source        VARCHAR(20),
        @Actual        INT;

SET @MilestoneName = null;
SET @MilestoneSts = null;
SET @ProjectPre = null;
SET @CenterPre  = null;

DECLARE s_cursor CURSOR FOR
SELECT ProjectID, Center, Source, Actual
FROM #MILESTONE


OPEN s_cursor
FETCH NEXT FROM s_cursor INTO @ProjectID, @Center, @Source, @Actual

WHILE @@FETCH_STATUS = 0
BEGIN

  SELECT @@FETCH_STATUS sts, @ProjectID PID, @Center Center, @Source Source, @Actual Actual 
  FETCH NEXT FROM s_cursor INTO @ProjectID, @Center, @Source, @Actual
END

CLOSE s_cursor
DEALLOCATE s_cursor  

However using that I'm able to produce 79 results of single rows but I want to union all those rows into one result.. any possible solution will be highly appreciated..

1

There are 1 answers

4
gjvdkamp On

just checking, why are you using a cursor for this?

This sproc could be replaced by just saying

SELECT ProjectID, Center, Source, Actual
FROM #MILESTONE

But maybe I'm missing somehting here?

If there's logic you left out in your code look at this post: Multi-statement Table Valued Function vs Inline Table Valued Function

GJ