Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server while loop union all [closed]

Tags:

sql

sql-server

I am trying to execute this code below. It is a simplified example of the actual code I have to make, so I know that it is useless to loop in such a way. However, I need to look and union select statements in SQL Server. When I try to run this query I get an error:

Incorrect syntax near the keyword 'END'.

Any ideas?

  DECLARE @position INT
    SET @position = -1

    WHILE(@position < 1)
    BEGIN
    SELECT * FROM mytable

    UNION ALL
    END
 SELECT * FROM mytable
like image 654
richsoni Avatar asked Oct 12 '12 17:10

richsoni


2 Answers

Instead of trying to use UNION I would use a temp table or temp table variable to merge the result sets

CREATE TABLE #Temp
(
  <COLUMNS>
)

 DECLARE @position INT
 SET @position = -1

 WHILE(@position < 1)
 BEGIN

    INSERT INTO #Temp (<COLUMNS>)
    SELECT * FROM mytable

    SET @position = @position + 1

 END

 SELECT * FROM #Temp
like image 122
msmucker0527 Avatar answered Nov 02 '22 21:11

msmucker0527


That query makes no sense. To use UNION, you need to be selecting from a second table.

SQL Server essentially sees:

SELECT * FROM mytable      

UNION ALL 

With no second table after the UNION.

like image 45
LittleBobbyTables - Au Revoir Avatar answered Nov 02 '22 20:11

LittleBobbyTables - Au Revoir