IF为SET变量

时间:2013-10-23 15:20:20

标签: sql sql-server

所以我的代码完美无瑕,但我需要进行一次升级,而我无法理解。 基本上。我每年的价格高达2052年(40年)。我把这些价格惊人地放在每个ID的连续起始年和5个价格中(总共72个ID)。我的行号从550开始,每次循环增加2。有一个区(我现在知道)每次循环时需要增加3个区。在循环结束时设置变量值时,有没有办法设置IF语句或CASE语句?因此,当我进入“SET @LINE = @LINE + 2”时,我需要这样的条件类似于..

CASE
     WHEN DISTRICT = 'ALASKA'
     THEN @LINE = @LINE + 3
     ELSE @LINE = @LINE + 2
END

以下是我现在正在使用的内容。

DECLARE @IDF INT
DECLARE @FLAG INT       
DECLARE @LINE INT
TRUNCATE TABLE #CODE
SET @IDF = 1
WHILE (@IDF < 73)   
BEGIN   
    SET @FLAG = (SELECT min(YEAR) FROM #TABLE1 WHERE ID = @IDF)
    SET @LINE = 550
    WHILE (@FLAG < 2053)
    BEGIN
        INSERT INTO #CODE(ID,DISTRICT,year,LINE,t1,t2,t3,t4,t5)
        SELECT ID,
               DISTRICT,
               year,
               (@LINE) AS 'LINE',
               (SELECT YEARLY_PRICING FROM #TABLE1 b WHERE b.ID = @IDF AND b.YEAR = @FLAG) AS 't1',
               (SELECT YEARLY_PRICING FROM #TABLE1 b WHERE b.ID = @IDF AND b.YEAR = @FLAG+1) AS 't2',
               (SELECT YEARLY_PRICING FROM #TABLE1 b WHERE b.ID = @IDF AND b.YEAR = @FLAG+2) AS 't3',
               (SELECT YEARLY_PRICING FROM #TABLE1 b WHERE b.ID = @IDF AND b.YEAR = @FLAG+3) AS 't4',
               (SELECT YEARLY_PRICING FROM #TABLE1 b WHERE b.ID = @IDF AND b.YEAR = @FLAG+4) AS 't5'
        FROM #TABLE1 WHERE ID = @IDF AND YEAR = @FLAG
    SET @FLAG = @FLAG + 5
    SET @LINE = @LINE + 2
    END
SET @IDF = @IDF + 1
END

1 个答案:

答案 0 :(得分:1)

WHILE (@IDF < 73)   
BEGIN   
    SET @FLAG = (SELECT min(YEAR) FROM #TABLE1 WHERE ID = @IDF)
    SET @LINE = 550
    WHILE (@FLAG < 2053)
    BEGIN
        INSERT INTO #CODE(ID,DISTRICT,year,LINE,t1,t2,t3,t4,t5)
        SELECT ID,
               DISTRICT,
               year,
               (@LINE) AS 'LINE',
               (SELECT YEARLY_PRICING FROM #TABLE1 b WHERE b.ID = @IDF AND b.YEAR = @FLAG) AS 't1',
               (SELECT YEARLY_PRICING FROM #TABLE1 b WHERE b.ID = @IDF AND b.YEAR = @FLAG+1) AS 't2',
               (SELECT YEARLY_PRICING FROM #TABLE1 b WHERE b.ID = @IDF AND b.YEAR = @FLAG+2) AS 't3',
               (SELECT YEARLY_PRICING FROM #TABLE1 b WHERE b.ID = @IDF AND b.YEAR = @FLAG+3) AS 't4',
               (SELECT YEARLY_PRICING FROM #TABLE1 b WHERE b.ID = @IDF AND b.YEAR = @FLAG+4) AS 't5'
        FROM #TABLE1 WHERE ID = @IDF AND YEAR = @FLAG

    SELECT @LINE = CASE 
                        WHEN DISTRICT = 'ALASKA'
                        THEN @LINE + 3
                        ELSE @LINE + 2
                    END
    FROM #CODE
    WHERE LINE = @LINE
    AND [YEAR] = @FLAG

    SET @FLAG = @FLAG + 5
    END
SET @IDF = @IDF + 1
END