在“IS NULL”条件下更改列状态

时间:2017-12-21 12:49:01

标签: sql sql-server coalesce isnull

我有一张表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

2 个答案:

答案 0 :(得分:1)

使用ISNULL功能代替COALESCE

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

答案 1 :(得分:1)

只需使用case

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

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

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