我的语法错误,当我想如果条件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 
+0

是'status'默认设置为'Available'? – toonice

+0

是的,它是@toonice – Onosibiw

据推测,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' 
+0

谢谢你的作品,但为什么我的状态没有改变?我的状态仍然“可用”,而我的数量已经 Onosibiw

+0

谢谢!现在是工作,我只是把工作转向定位 – Onosibiw

是的,那是因为你不能使用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'; 
+1

检查你的查询,两个SET语句存在。 – Mansoor

+0

@Mansoor,速度打字......感谢指点 – Rahul

+0

谢谢你的作品,但为什么我的状态没有改变?我的状态仍然'可用',而我的数量已经 Onosibiw