在 "IS NULL" 条件下更改列状态

Change column status on "IS NULL" condition

我有一个 table tblBooking:

bkID bkCusID bkTotalAmount
---- ------- -------------
17   11      NULL
18   11      NULL
19   11      NULL

如果 bkTotalAmount 为空,则 bkStatus 应该是 0,如果不是,则它应该 1:

bkID bkCusID bkStatus
---- ------- -------------
17   11      
18   11      
19   11

我已经使用 COALESCE 将状态更改为 0 但不知道如何将状态更改为 1 如果 bkTotalAmount 不为空:

SELECT bkID, bkCusID, COALESCE(bkTotalAmount, 0) AS bkStatus
FROM tblBooking
WHERE bkCusID = 11 AND bkTotalAmount IS NULL

使用 ISNULL 函数代替 COALESCE

SELECT 
bkID,
bkCusID,
ISNULL(bkTotalAmount+1, 0) AS bkStatus 
FROM tblBooking WHERE bkCusID=11 

只需使用case:

SELECT bkID, bkCusID,
       (CASE WHEN bkTotalAmount IS NULL THEN 0 ELSE 1 END) AS bkStatus
FROM tblBooking
WHERE bkCusID = 11 ;

如果您希望将其存储在 table 本身中,您 可以 使用更新。相反,我建议添加一个计算列:

alter table tblBooking add bkStatus as (CASE WHEN bkTotalAmount IS NULL THEN 0 ELSE 1 END);