一个包含多个case和where子句的Update语句

时间:2016-01-04 19:06:10

标签: sql sql-update case grouping

我有一个包含以下列的表

june_hours
july_hours
august_hours
... 
april_hours
may_hours

我希望有一个触发器可以说 如果june_hours为null,如果sept_hours为null,则将其设置为零,将其设置为零。但是,我想在一个更新声明中这样做。

UPDATE  a
SET     july_hours = 0
From    LT_VOLUNTEER_HOURS a
    JOIN inserted b ON a.id_key = b.id_key
    where a.july_hours is null

UPDATE  a
SET     sept_hours = 0
From    LT_VOLUNTEER_HOURS a
    JOIN inserted b ON a.id_key = b.id_key
    where a.sept_hours is null

依旧...... 如果可能的话,我想做什么 是说

update table
set
    case where june_hours is null = 0
    case where sept_hours is null = 0
    case where april_hours is null = 0

这可行吗? 我一直在读书,我找不到任何肯定的东西。

1 个答案:

答案 0 :(得分:1)

首先,您应该将每个“小时”存储为表格中的单独行。这将使这个更新更容易 - 也可能是很多其他查询。

无论如何,你可以这样做:

update table
    set june_hours = coalesce(june_hours, 0),
        sept_hours = coalesce(sept_hours, 0),
        april_hours = coalesce(april_hours, 0)
    where june_hours is null or sept_hours is null or april_hours is null;

编辑:

您的代码看起来像是在触发器中运行。同样的想法成立:

update vh
    set june_hours = coalesce(june_hours, 0),
        sept_hours = coalesce(sept_hours, 0),
        april_hours = coalesce(april_hours, 0)
    from LT_VOLUNTEER_HOURS vh join
         inserted i 
         on vh.id_key = i.id_key
where lv.june_hours is null or lv.sept_hours is null or lv.april_hours is null;

当然,您可以将其延长至所有月份。 where子句是可选的,但它确实使查询的意图更加明显(并且可以减少开销)。