我是MySQL功能的新手。我创建了一个函数:
CREATE FUNCTION `tems`.`<function_name>`(IN bid INT, IN cid INT)
RETURNS INT(10)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE min_no INT;
SELECT COALESCE(min(number),1)
FROM
(SELECT r1.number -1 AS number, r1.branch_id, r1.course_id
FROM `Room` AS r1
LEFT JOIN `Room` AS r2
ON r1.branch_id = r2.branch_id
AND r1.course_id = r2.course_id
AND (r1.number - 1) = r2.number
WHERE r1.number > 1 AND r2.number IS NULL
UNION ALL
SELECT max(number) + 1, branch_id, course_id
FROM `Room`
GROUP BY branch_id, course_id) AS q
WHERE branch_id=bid AND course_id=cid
GROUP BY branch_id, course_id
INTO min_no;
RETURN (min_no);
END;
我想获得bid
,cid
并返回选择值,但我收到了错误消息:
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 'IN bid INT, IN cid INT)
RETURNS INT(10)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS ' at line 1
我做错了什么?
答案 0 :(得分:1)
使用下面的DELIMITER
以及删除两部分标识符。只需声明函数名称。
DELIMITER $$
CREATE FUNCTION MyTestFunc (bid INT, cid INT)
RETURNS INT(10)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE min_no INT;
SELECT COALESCE(min(number),1)
FROM
(SELECT r1.number -1 AS number, r1.branch_id, r1.course_id
FROM `Room` AS r1
LEFT JOIN `Room` AS r2
ON r1.branch_id = r2.branch_id
AND r1.course_id = r2.course_id
AND (r1.number - 1) = r2.number
WHERE r1.number > 1 AND r2.number IS NULL
UNION ALL
SELECT max(number) + 1, branch_id, course_id
FROM `Room`
GROUP BY branch_id, course_id) AS q
WHERE branch_id=bid AND course_id=cid
GROUP BY branch_id, course_id
INTO min_no;
RETURN (min_no);
END$$
DELIMITER ;