尝试在MySQL(5.1)中创建存储过程时遇到错误。 每当我尝试运行这个SQL脚本时,我都会看到:
错误1064(42000)第3行:您的SQL语法出错。 在'DECLARE checkExists INT附近; SET checkExists = 0;在第29行选择计数(*)INTO c'
据我所知,以这种方式声明变量应该是可以接受的。 我在下面包含了SQL脚本。
DELIMITER //
CREATE PROCEDURE add_movie(
IN movieTitle VARCHAR(100),
IN movieYear INT,
IN movieDirector VARCHAR(100),
IN movieBannerURL VARCHAR(100),
IN movieTrailerURL VARCHAR(100),
IN starFirstName VARCHAR(50),
IN starLastName VARCHAR(50),
IN starDateOfBirth DATE,
IN starPhotoURL VARCHAR(200),
IN genreName VARCHAR(32),
OUT movieAdded INT,
OUT starAdded INT,
OUT genreAdded INT,
OUT movieStarLinkAdded INT,
OUT movieGenreLinkAdded INT)
LANGUAGE SQL
NOT DETERMINISTIC
SQL SECURITY INVOKER
COMMENT 'Adds Movie, Star, Genre and respective links to DB if they do not exist'
BEGIN
SET movieAdded = 0;
SET starAdded = 0;
SET genreAdded = 0;
SET movieStarLinkAdded = 0;
SET movieGenreLinkAdded = 0;
DECLARE checkExists INT;
SET checkExists = 0;
SELECT count(*) INTO checkExists FROM movies m WHERE m.title = movieTitle;
IF(checkExists > 0) THEN
INSERT INTO movies(title, year, director, banner_url, trailer_url)
VALUES (movieTitle, movieYear, movieDirector, movieBannerURL, movieTrailerURL);
SET movieAdded = 1;
END IF;
SET checkExists = 0;
SELECT count(*) INTO checkExists FROM stars s WHERE s.first_name = starFirstName AND s.last_name = starLastName;
IF(checkExists > 0) THEN
INSERT INTO stars(first_name, last_name, dob, photo_url)
VALUES (starFirstName, starLastName, starDateOfBirth, starPhotoURL);
SET starAdded = 1;
END IF;
SET checkExists = 0;
SELECT count(*) INTO checkExists FROM genres g WHERE g.name = genreName;
IF(checkExists > 0) THEN
INSERT INTO genres(name)
VALUES (genreName);
SET genreAdded = 1;
END IF;
SET checkExists = 0;
SELECT count(*) INTO checkExists FROM stars_in_movies sm, stars s, movies m
WHERE m.title = movieTitle AND s.first_name = starFirstName
AND s.last_name = starLastName AND sm.star_id = s.id AND sm.movie_id = m.id;
IF(checkExists > 0) THEN
INSERT INTO stars_in_movies(star_id, movie_id)
VALUES(
SELECT s.id, m.id FROM stars s, movies m WHERE s.first_name = starFirstName
AND s.last_name = starLastName AND m.title = movieTitle);
SET movieStarLinkAdded = 1;
END IF;
SET checkExists = 0;
SELECT count(*) INTO checkExists FROM genres_in_movies gm, genres g, movies m
WHERE m.title = movieTitle AND genre.name = genreName
AND gm.movie_id = m.id AND gm.genre_id = g.id;
IF(checkExists > 0) THEN
INSERT INTO genres_in_movies(genre_id, movie_id)
VALUES(
SELECT g.id, m.id FROM genres g, movies m
WHERE g.name = genreName AND m.title = movieTitle);
SET movieGenreLinkAdded = 1;
END IF;
END //
DELIMITER ;
如果有人能帮助我理解我在这里做错了什么,我会非常感激。谢谢。
答案 0 :(得分:2)
将所有DECLARE
语句移至BEGIN .. END
块的开头,BEGIN
旁边。
请参阅文档:https://dev.mysql.com/doc/refman/5.6/en/declare.html
仅允许在BEGIN ... END复合语句中使用DECLARE,并且必须在其开始之前,在任何其他语句之前。