在UPDATE中添加条件语句

时间:2011-09-22 18:43:57

标签: tsql conditional

查询:

UPDATE empPac
    SET quantityLimit = allocation,
        allocationStart = '"&allocationStart&"',
        nextUpdate = DATEADD(mm, allocationMonths, "&allocationStart&"),
        lastUpdate = GETDATE(),
        quantityIssued = 0,
        quantityShipped = 0
    WHERE allocation IS NOT NULL AND
          allocationMonths <> 0 AND
          (nextUpdate <= DATEADD(mm, "&checkCondition&", GETDATE()) OR
           nextUpdate IS NULL) AND
          empIdent in (select empIdent
                       from employee
                       where custIdent='"&custIdent&"')

我想要做的是向SET quantityLimit = allocation添加一个条件语句,这样我就不想拥有WHERE allocation IS NOT NULL,而是希望它有一个条件语句,例如SET quantityLimit = ((allocation IS NULL) ? 0 : allocation)

3 个答案:

答案 0 :(得分:2)

您可以使用ISNULL()

SET quantityLimit = ISNULL(allocation, 0)

其他数据库的等效函数为Oracle NVL()和MySQL IFNULL()SQLite


如果您想提高代码的可移植性,那么您真正应该使用的是COALESCE()COALESCESQL-92 standard的一部分,并在RDBMS之间得到广泛支持。

答案 1 :(得分:1)

您使用什么数据库? 例如,在oracle sql中,您可以编写case when allocation is null then 0 else allocation endnvl (allocation, 0)coalesce (allocation, 0)

case syntax in MSSQL与Oracle中的相同。

答案 2 :(得分:0)

这是TSQL(MSSQL)方式:

SET quantityLimit = isnull(allocation,0)

...替代

SET quantityLimit = CASE WHEN allocation is null THEN 0 ELSE allocation END
--This one might be handy if you wanted to check for more than just null values.  Such as:
----...CASE WHEN allocation is null THEN 0 WHEN some_other_value THEN 1 WHEN ... THEN ... ELSE allocation END

SET quantityLimit = coalesce(allocation,0)
--This one gives you the first non-null value it finds, given a list of places to look.  Such as:
----...coalesce(allocation,some_other_field,some_nuther_field,...,0)