我的mysql存储过程有什么问题?

时间:2019-09-02 07:02:49

标签: mysql if-statement stored-procedures

我有一个存储过程,用于检查表中是否已存在新条目。如果存在,则不会发生插入。当我运行它时,有一个错误

DROP PROCEDURE IF EXISTS AddPriority2;
DELIMITER $$

CREATE PROCEDURE AddPriority2
(
    IN strName VARCHAR(100),
    OUT itExists INT
)
BEGIN
DECLARE 
SELECT COUNT(Id) INTO itExists
FROM priorities
WHERE Name = strName AND StatId = 1;

IF(itExists = 0) THEN
INSERT INTO priorities
(
    NAME,
    StatId
)
VALUES
(
    strName,
    1
);
END IF;
END

这是错误

Query: CREATE PROCEDURE AddPriority2 ( IN strName VARCHAR(100), OUT itExists INT ) BEGIN DECLARE SELECT COUNT(Id) INTO itExists FROM pr...

Error Code: 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 'SELECT COUNT(Id) INTO itExists
FROM priorities
WHERE Name = strName AND StatId =' at line 8

1 个答案:

答案 0 :(得分:2)

1)您不能声明select语句-声明必须用于变量..(并且我不会为此使用输出参数)2)或可以使用exist代替

if not exists (select 1 from priorities WHERE Name = strName AND StatId = 1) then
   insert...
end if;