我的语法错误,当我想如果条件sql
问题描述:
为什么这发生在我身上?我不知道为什么我的语法得到错误的,当我想让如果有条件的话在我的SQL我的语法错误,当我想如果条件sql
IF quantity <= 0
UPDATE tbl_books
SET status = 'Not Available'
ELSE
UPDATE tbl_books
SET quantity = quantity -1
WHERE isbn = 'tes1'
我得到了这样的错误
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'IF 'quantity' <= 0 UPDATE tbl_books SET status = 'Not Available' ELSE UPDA' at line 1
答
据推测,quantity
不是一个变量。因此,它不在if
声明的范围内。
您可以在一个update
语句做到这一点:
UPDATE tbl_books
SET status = (CASE WHEN quantity <= 0 THEN 'Not Available' ELSE status END),
quantity = (CASE WHEN quantity > 0 THEN quantity - 1 ELSE quantity END)
WHERE isbn = 'tes1'
答
是的,那是因为你不能使用IF .. ELSE
程序结构在除了存储过程或存储函数之外的普通SQL查询中。您可以使用条件SET
像
UPDATE tbl_books
SET status = case when quantity <= 0 then 'Not Available' else status end,
quantity = case when quantity > 0 then quantity -1 else quantity end
WHERE isbn = 'tes1';
是'status'默认设置为'Available'? – toonice
是的,它是@toonice – Onosibiw