我正在尝试编写简单的mysql存储过程,似乎我无法正确理解,到目前为止我已经
delimiter //
create procedure addRecord(_login varchar(15),_artist varchar(50),_record varchar(50))
begin
declare dbArtist varchar(50);
delcare dbRecord varchar(50);
set dbArtist = (select artistname from artists where lower(artistname) = lower(_artist));
set dbRecord=(select recordname from records where lower(recordname)=lower(_record));
if not exists (select * from Artists where lower(artistname)=lower(_artist)) then
begin
INSERT INTO `Artists`(`ArtistName`) VALUES (_artist);
set dbArtist=_artist;
end
if not exists (select * from Records as R inner join Artists as A on R.ArtistId=A.ArtistId where lower(R.RecordName)=lower(_record) and A.ArtistName=dbArtist) then
begin
INSERT INTO `Records`(`ArtistId`, `RecordName`) VALUES ((select artistid from artists where artistname=dbArtist),_record);
set dbRecord=_record;
end
end
但我在第4行遇到语法错误:
#1064 - 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 'dbRecord varchar(50);
set dbArtist = (select artistname from artists where lowe' at line 4
这个消息错误是由phpMyAdmin返回给我的,有谁能告诉我为什么会出错?
编辑:修改后的版本,仍然不太好
delimiter //
create procedure addRecord(_login varchar(15),_artist varchar(50),_record varchar(50))
begin
declare dbArtist varchar(50);
declare dbRecord varchar(50);
set dbArtist = (select artistname from artists where lower(artistname) = lower(_artist));
set dbRecord=(select recordname from records where lower(recordname)=lower(_record));
if not exists (select * from Artists where lower(artistname)=lower(_artist)) then
begin
INSERT INTO `Artists`(`ArtistName`) VALUES (_artist);
set dbArtist=_artist;
end
if not exists
(select * from Records as R inner join Artists as A on R.ArtistId = A.ArtistId where lower(R.RecordName)=lower(_record) and A.ArtistName=dbArtist)
then
begin
INSERT INTO `Records`(`ArtistId`, `RecordName`) VALUES ( (select artistid from artists where artistname=dbArtist) ,_record);
set dbRecord=_record;
end
end
现在出现第14行错误消息:
#1064 - 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 'if not exists (select * from Records as R inner join Artists as A on R.ArtistId' at line 14
答案 0 :(得分:2)
问题是你拼写错误DECLARE
:
delcare dbRecord varchar(50);
更新:对于您的下一个错误,问题是您非法使用NOT EXISTS
。
在存储过程中,正确的方法是对现有行进行计数,然后在计数为0时有条件地插入值。
这样的事情:
SELECT COUNT(*)
INTO @v_row_count
FROM Artists
WHERE LOWER(artistname)=LOWER(_artist);
IF (@v_row_count = 0)
THEN
INSERT INTO `Artists`(`ArtistName`) VALUES (_artist);
set dbArtist=_artist;
END IF;
P.S。为避免选择查询的性能不佳,您应该考虑使用不区分大小写的排序规则,这样您就不需要将LOWER()
函数应用于artistname列。