0

嗨,我正在使用 MySQL 创建一个函数:

CREATE FUNCTION INSERTGROUP(name VARCHAR(50))
RETURNS INT
NOT DETERMINISTIC
BEGIN
DECLARE 'idGroup' INT;

IF (NOT EXISTS (SELECT groupID FROM groupsTable WHERE groupName = 'name'))
THEN INSERT INTO groupsTable (groupName) VALUES ('name');

SELECT groupID INTO 'idGroup' FROM groupsTable WHERE groupName='name';

RETURN 'idGroup';
END//

但是当我尝试创建它时出现此错误:

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
''idGroup' INT;

IF (NOT EXISTS (SELECT groupID FROM serverGroupsTable WHERE gro' at line 5

我已经通过论坛和其他类似的问题,但我不能让它创建功能。

我做错了什么?语法是否正确?我需要添加其他东西吗?

好的,这就是我尝试过的:

CREATE FUNCTION INSERTGROUP(name VARCHAR(255))
RETURNS INT
NOT DETERMINISTIC
BEGIN
DECLARE idGroup INT;

IF (NOT EXISTS (SELECT groupID FROM groupsTable WHERE groupName = name))
THEN INSERT INTO groupsTable (groupName) VALUES (name);

SELECT groupID INTO idGroup FROM groupsTable WHERE groupName=name;

RETURN idGroup;
END//

CREATE FUNCTION INSERTGROUP(name VARCHAR(255))
RETURNS INT
NOT DETERMINISTIC
BEGIN
DECLARE idGroup INT;

IF (NOT EXISTS (SELECT groupID FROM groupsTable WHERE groupName = 'name'))
THEN INSERT INTO groupsTable (groupName) VALUES ('name');

SELECT groupID INTO idGroup FROM groupsTable WHERE groupName='name';

RETURN idGroup;
END//

最后两个我得到了这个错误:

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
'' at line 13

和上面的一样

我也做DELIMITER //改变它;

4

1 回答 1

4

从声明中删除引号

DECLARE idGroup INT;

并且您忘记了函数开头的分隔符更改

delimiter //
CREATE FUNCTION INSERTGROUP(name VARCHAR(255))

你忘了结束你的if陈述

end if;

无论你想让它在哪里结束

于 2012-11-14T18:05:18.143 回答