Union in while loop RRS feed

  • Question

  • hi,

    how to union output of a query in while loop and need to insert the output in to temp table. can anybody give any example..


    Friday, March 18, 2011 5:07 AM


  • Hi,

    This looks like T-SQL forum question...

    As you should avoid using loops in general..there are some other tricks like Recutrsive CTE and may be a UNION ALL that you shoud try first...

    If you want an example, you can have a look at below

    NOTE:- This is just for example of syntax, we should try to avoide this as much as possible

    declare @id int
    select @id = 1
    declare @table table
    (firstname nvarchar(max),
    lastname nvarchar(max)
    while (@id<3)
      insert into @table 
      select firstname,lastname from adventureworks.person.contact
      where contactID = @id
      select @id = @id+1
    select * from @table

    Also, it would help in answeing if you can add details...

     - Chintak (My Blog)

    • Proposed as answer by WeiLin Qiao Tuesday, March 22, 2011 10:24 AM
    • Marked as answer by WeiLin Qiao Saturday, March 26, 2011 11:00 AM
    Friday, March 18, 2011 6:15 AM