By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,654 Members | 1,599 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,654 IT Pros & Developers. It's quick & easy.

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

P: 1
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

Expand|Select|Wrap|Line Numbers
  1. declare @CurrentRow int
  2. set @CurrentRow =0;
  3. declare @RowsToProcess int
  4. declare @FinalHistoricalQuery varchar(5000)
  5. WHILE @CurrentRow<3
  6. BEGIN      
  7.    SET @FinalHistoricalQuery =' select 11'+convert(varchar(20),@CurrentRow) + ' union '
  8.    SET @CurrentRow=@CurrentRow+1
  9. END
  10.  
  11. SET @FinalHistoricalQuery = left(@FinalHistoricalQuery,len(@FinalHistoricalQuery)-6)
  12. exec (@FinalHistoricalQuery)
the final ouput that i am looking for is 110 111 112 but it comes as 112 Any suggestion would be helpfull
Mar 11 '15 #1
Share this Question
Share on Google+
1 Reply


Rabbit
Expert Mod 10K+
P: 12,430
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
Mar 11 '15 #2

Post your reply

Sign in to post your reply or Sign up for a free account.