2016-02-12 103 views
4

我在遵循MySQL指南IF語法時遇到語法錯誤。IF語法錯誤

我的查詢是:

if 0=0 then select 'hello world'; end if; 

從邏輯上講,這應該選擇'hello world',而是我得到

ERROR 1064 (42000): 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 'if (0=0) then select 'hello world'' at line 1 
ERROR 1064 (42000): 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 'end if' at line 1 

回答

5

你的查詢只在存儲過程/函數上下文有效。 請參閱there以供參考。

0

如果語句在一般SQL流程中不受支持。它只能用於功能或程序。但是,您可以按以下方式使用它

use my_db; 
delimiter # 
create procedure xyz() 
begin 
    IF 0=0 then select 'hello world'; 
end if; 
end# 
+0

爲什麼不直接使用內置的IF()函數? – spiderman

+0

是的,這是可能的,但我已經根據問題的背景回答了,因爲我知道了! – geeksal

1

使用if語句像這樣僅在存儲過程或函數內有效。

什麼你可能想使用的是if()功能,那麼你可以使用:

select IF(0=0, 'hello world','');