SQL Server UNION多个选择在WHILE语句中

时间:2014-08-15 01:31:04

标签: sql sql-server

我在存储过程中有一个WHILE语句:

DECLARE @reverseindex int
DECLARE @index INT

SET @index = 1

WHILE (@index <= @workingyears)
BEGIN
    SET @reverseindex = @workingyears-@index+1

    SELECT daysallowed, date, holidaytype, leavetype, isactive 
    FROM setup_holiday_schedule 
    WHERE workingyears = @reverseindex
      AND holidayschedulecode = @holidayschedulecode
END

运行此查询我会得到多个表,具体取决于@workingyears的大小。我想在WHILE语句的末尾只有一个表结果。

这可能吗?

2 个答案:

答案 0 :(得分:1)

为什么你需要一个while功能?我认为这个查询几乎完全相同:

SELECT daysallowed, date, holidaytype, leavetype, isactive 
FROM setup_holiday_schedule 
WHERE workingyears between 1 and @workingyears AND
      holidayschedulecode = @holidayschedulecode
ORDER BY workingyears desc;

答案 1 :(得分:0)

表值变量怎么样?

DECLARE @reverseindex int
DECLARE @index INT
DECLARE @results TABLE (
    daysallowed INT,
    date DATE,
    holidaytype INT,
    leavetype INT,
    isactive BIT
)

SET @index = 1
WHILE (@index <= @workingyears)
BEGIN

    SET @reverseindex = @workingyears-@index+1
    INSERT INTO @results (
        daysallowed, date, holidaytype, leavetype, isactive
    )
    SELECT daysallowed, date, holidaytype, leavetype, isactive 
    FROM setup_holiday_schedule 
    WHERE workingyears = @reverseindex
    AND holidayschedulecode = @holidayschedulecode

END

SELECT daysallowed, date, holidaytype, leavetype, isactive FROM @results