I am trying to loop through my counter to create a dynamic sql query which should fin

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Anusrivastava
    New Member
    • Mar 2015
    • 1

    I am trying to loop through my counter to create a dynamic sql query which should fin

    I am trying to loop through my counter to create a dynamic sql query which should finally look like

    I am trying to use this approach to get the final query but doesnt seems to work

    Code:
    declare @CurrentRow int
    set @CurrentRow =0;
    declare @RowsToProcess int
    declare @FinalHistoricalQuery varchar(5000)
    WHILE @CurrentRow<3
    BEGIN      
       SET @FinalHistoricalQuery =' select 11'+convert(varchar(20),@CurrentRow) + ' union '
       SET @CurrentRow=@CurrentRow+1
    END
     
    SET @FinalHistoricalQuery = left(@FinalHistoricalQuery,len(@FinalHistoricalQuery)-6)
    exec (@FinalHistoricalQuery)
    the final ouput that i am looking for is 110 111 112 but it comes as 112 Any suggestion would be helpfull
    Last edited by Rabbit; Mar 11 '15, 03:35 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Please use code tags when posting code or formatted data.

    The problem is that you keep replacing the value of the variable instead of appending to it. You are doing x = new value instead of x = x + new value

    Comment

    Working...