简体   繁体   中英

Simple SQL case issue - returning 0 when NULL

Apparently NUMBER + NULL returns NULL in SQL. So I need it to add 0 instead of NULL but this isn't working, I'm getting a syntax error. I'm looking at the docs and this is what it says to do so I'm not sure...

SELECT sku, (qty + (SELECT(CASE qty WHEN IS NULL THEN 0 ELSE qty END)
                    FROM other WHERE sku = Sheet1.sku LIMIT 1)) as qty
FROM Sheet1 WHERE sku != '' 
ORDER BY sku ASC

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

'IS NULL THEN 0 ELSE qty END) FROM other WHERE sku = Sheet1.sk

You're really close.

Case qty When NULL Then 0 else qty END

The IS Null is a Where Clause Convention. You can also use Coalesce:

Select Coalesce(qty, 0)

Coalesce returns the 1st non-null of it's parameter list. So if qty is Null you get 0, otherwise you get qty.

使用此语法将NULL替换为0:

select COALESCE(qty,0)...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM