我尝试在MySQL中创建存储过程:
create PROCEDURE sp_attachAuthorToBook(
IN _bookId INT,
IN _authorName VARCHAR(20)
)
BEGIN
declare _authorId int
select _authorId = id from Authors where name = _authorName
IF (_authorId is null) THEN
INSERT INTO Authors (name)
VALUES (_authorName)
SELECT _authorId = SCOPE_IDENTITY()
END IF
insert into Books_Authors (bookID, authorID)
values (_bookId, _authorId)
END;
但我收到错误:
您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便使用正确的语法 'select _authorId = id from Authors where name = _authorName IF (_authorId在第1行是nul'
似乎脚本太大而无法执行。刚刚破线的行:
IF (_authorId is null) THEN
- IF (_authorId is nul
答案 0 :(得分:0)
您的分隔符存在问题。默认情况下,它是“;”。但是你需要内部分隔符,所以:
DELIMITER |
create PROCEDURE sp_attachAuthorToBook(
IN _bookId INT,
IN _authorName VARCHAR(20)
)
BEGIN
declare _authorId int;
select _authorId = id from Authors where name = _authorName;
IF (_authorId is null) THEN
INSERT INTO Authors (name)
VALUES (_authorName);
SELECT _authorId = LAST_INSERT_ID();
END IF;
insert into Books_Authors (bookID, authorID)
values (_bookId, _authorId);
END|
答案 1 :(得分:0)
它在SQLYOG上的工作代码:请尝试这种方式
DELIMITER $$
CREATE /*[DEFINER = { user | CURRENT_USER }]*/ PROCEDURE `test`.`sp_attachAuthorToBook`(
IN _bookId INT,
IN _authorName VARCHAR(20)
)
BEGIN
DECLARE _authorId INT;
SELECT id INTO _authorId FROM Authorss WHERE `name` = _authorName;
IF _authorId IS NULL THEN
INSERT INTO Authorss(`name`) SELECT _authorName;
SET _authorId = LAST_INSERT_ID();
END IF;
INSERT INTO Book_Authors(bookID, authorID) SELECT _bookId, _authorId;
END$$
DELIMITER ;