Sql 无法在存储过程中为所选查询执行联合

Sql 无法在存储过程中为所选查询执行联合,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,在这个存储过程中,我将每个循环的输出作为单个表,因此我将多个表作为输出,但我希望通过union可以实现单个表中的所有行,但我不知道如何使用。创建临时表并插入循环中的临时表,然后结果将是: ALTER PROC [dbo].[Usp_SelectQuestion] @NoOfQuestion int AS BEGIN Declare @CNT int Declare @test int Declare @x int Declare @y int set @x = 1;

在这个存储过程中,我将每个循环的输出作为单个表,因此我将多个表作为输出,但我希望通过union可以实现单个表中的所有行,但我不知道如何使用。

创建临时表并插入循环中的临时表,然后结果将是:

ALTER PROC [dbo].[Usp_SelectQuestion]
   @NoOfQuestion int
AS
BEGIN
  Declare @CNT int
  Declare @test int
  Declare @x int
  Declare @y int

  set @x = 1;
  set @y = 1; 
  set @CNT=(Select Count(*) from (select Distinct(setno)from onlin) AS A)
  set @test=@NoOfQuestion/@CNT

  while (@x <= @CNT)  
  begin
    select top (@test) * from onlin where setno = @x order by NEWID()
      set @x = @x + 1
  end
END
使用以下命令:

declare @temptable as table(col1 int, col2 varchar(50),... etc)

  while (@x <= @CNT)  
  begin
     insert into @temptable   'temptable columns need to match columns in the SELECT statement
        select top (@test) * from onlin where setno = @x order by NEWID()

     set @x = @x + 1
  end

  select * from @temptable
然后插入到表中

CREATE TEMPORARY TABLE tmp SELECT * FROM tableName;
CREATE TEMPORARY TABLE tmp SELECT * FROM tableName;
INSERT INTO tableName SELECT * FROM tmp;