更新表但使用列中的值 - 选择大小写

时间:2012-02-24 10:04:00

标签: sql sql-server sql-server-2008 tsql

不确定这是否可行,但我在表中有一个字段,需要通过另一个表中的值进行更新,但引用特定列,例如如果它是1然后从[Jan]列等中获取值。

Update table1
    Set Total = 
        CASE @count
            WHEN 1  THEN [Jan]
            WHEN 2  THEN [Feb]
            WHEN 3  THEN [Mar]
            WHEN 4  THEN [Apr]
            WHEN 5  THEN [May]
            WHEN 6  THEN [Jun]
            WHEN 7  THEN [Jul]
            WHEN 8  THEN [Aug]
            WHEN 9  THEN [Sep]
            WHEN 10 THEN [Oct]
            WHEN 11 THEN [Nov]
            WHEN 12 THEN [Dec]
        END
    from table2

提前致谢

3 个答案:

答案 0 :(得分:3)

您可以将CASE放入子查询中:

UPDATE table1
SET Total=(SELECT TOP 1 CASE @count
            WHEN 1  THEN [Jan]
            WHEN 2  THEN [Feb]
            WHEN 3  THEN [Mar]
            WHEN 4  THEN [Apr]
            WHEN 5  THEN [May]
            WHEN 6  THEN [Jun]
            WHEN 7  THEN [Jul]
            WHEN 8  THEN [Aug]
            WHEN 9  THEN [Sep]
            WHEN 10 THEN [Oct]
            WHEN 11 THEN [Nov]
            WHEN 12 THEN [Dec]
        END
        FROM table2)

答案 1 :(得分:3)

Update t
    Set t.Total = 
        CASE @count
            WHEN 1  THEN t2.[Jan]
            WHEN 2  THEN t2.[Feb]
            WHEN 3  THEN t2.[Mar]
            WHEN 4  THEN t2.[Apr]
            WHEN 5  THEN t2.[May]
            WHEN 6  THEN t2.[Jun]
            WHEN 7  THEN t2.[Jul]
            WHEN 8  THEN t2.[Aug]
            WHEN 9  THEN t2.[Sep]
            WHEN 10 THEN t2.[Oct]
            WHEN 11 THEN t2.[Nov]
            WHEN 12 THEN t2.[Dec]
        END
    from table1 t inner join table2 t2 
    on t.ID = t2.ID --your condition

答案 2 :(得分:0)

您可以使用UNPIVOT

UPDATE Table2
SET [Total] =
(
    SELECT B.[Total]
    FROM
    (
        SELECT [Jan], [Feb], [Mar], [Apr], [May], [Jun]
             , [Jul], [Aug], [Sep], [Oct], [Nov], [Dec]
        FROM Table2
    ) AS A ([1], [2], [3], [4], [5], [6]
          , [7], [8], [9], [10], [11], [12])
    UNPIVOT ([Total] FOR [Month] IN
           ([1], [2], [3], [4], [5], [6]
          , [7], [8], [9], [10], [11], [12])) B
    WHERE B.[Month] = @count
)