Stored-Procedures

聲明程序時出錯

  • January 29, 2022

當我執行這個查詢

它返回我列國家的空值計數

(select
   sum(case 
       when (country IS NULL) then 1 
       else 0 END)
   as 'null_flag'
from city)

而當我嘗試在這樣的過程中添加相同的程式碼時

DELIMITER $$

CREATE PROCEDURE get_null_flags (col_name VARCHAR(40))
BEGIN
   (select
       sum(case 
           when ',[' + col_name + ']' IS NULL then 1 
           else 0 END)
       as 'null_flag'
   from city)
   
END $$

DELIMITER ;

它拋出一個錯誤說

Query 1 ERROR: 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' at line 10

注意:我使用的是 MySQL Ver 8.0.28,我已經通過 Homebrew 安裝了這個版本。我還有一個舊版本的 Mysql,即:5.7,我使用此文件切換版本 - https://jeanleem6.github.io/2019/05/08/Multiple-MySQL-Versions-with-Homebrew/

查詢後需要一個分號。IE:

DELIMITER $$

CREATE PROCEDURE get_null_flags (col_name VARCHAR(40))
BEGIN
(select
   sum(case 
       when ',[' + col_name + ']' IS NULL then 1 
       else 0 END)
   as 'null_flag'
from city);

END $$

DELIMITER ;

順便說一句,您不需要將查詢放在括號內。

引用自:https://dba.stackexchange.com/questions/306758