2011-09-22 92 views
2

查询:加入条件语句中UPDATE

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)

+0

MSSQL。我写的条件陈述是PHP速记,但我不知道如何显示我想要做的事情的例子。 – scarhand

回答

2

您可以使用ISNULL()

SET quantityLimit = ISNULL(allocation, 0) 

同等功能的其他数据库NVL()为Oracle和IFNULL() MySQL和SQLite


你真正应该使用虽然是COALESCE(),如果你想增加代码的可移植性。 COALESCESQL-92 standard的一部分,并广泛支持RDBMS。

+0

至少在Oracle中,您最好使用coalesce,因为nvl是一个pl/sql函数,并且本地实现了coalesce。 http://stackoverflow.com/questions/950084/oracle-differences-between-nvl-and-coalesce –

+0

是不是ANSIES标准? –

+0

@ConradFrix就是这样。我修改了我的答案。 – NullUserException

1

你使用什么数据库? 例如,在Oracle SQL你可以写case when allocation is null then 0 else allocation endnvl (allocation, 0)coalesce (allocation, 0)

而且case syntax in MSSQL是一样的Oracle。

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)