你好,美好的一天.. 在使用shell或cmd进行存储过程查询时,我需要一些帮助。 这是我的bookAuthor表
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| authorID | int(11) | NO | PRI | NULL | auto_increment |
| authorLname | varchar(50) | YES | | NULL | |
| authorFname | varchar(50) | YES | | NULL | |
| authorMname | varchar(50) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+`
如果我使用单个操作而不使用if语句(如下面的查询),则效果很好
MariaDB [library]> create procedure selectAll()
-> select * from bookAuthor;
Query OK, 0 rows affected (0.60 sec)
但是如果我使用if语句并在下面放置类似查询的参数
MariaDB [library]> create procedure insertUpdateSelectDelete
-> (
-> id int(11),
-> lname varchar(50),
-> fname varchar(50),
-> mname varchar(50),
-> statementtype varchar(30)
-> )
-> if statementtype = 'Insert'
-> insert into bookAuthor
-> (
-> authorLname,
-> authorFname,
-> authorMname
-> )
-> values
-> (
-> lname,
-> fname,
-> mname
-> )
-> if statementtype = 'Update'
-> update bookAuthor set
-> authorLname = lname,
-> authorFname = fname,
-> authorMname = mname
-> where authorID = id
-> if statementtype = 'Select'
-> select * from bookAuthor
-> if statementtype = 'Delete'
-> delete from bookAuthor where authorID = id;
它将返回这样的错误
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'insert into bookAuthor
(
authorLname,
authorFname,
authorMname
)
values
(
lname,' at line 10
答案 0 :(得分:1)
您的代码有很多问题。首先,IF
语句在条件之后需要THEN
,并且必须以END IF
终止。其次,该过程中的所有语句必须以;
结尾。尝试以下方法:
create procedure insertUpdateSelectDelete(
id int(11),
lname varchar(50),
fname varchar(50),
mname varchar(50),
statementtype varchar(30)
)
begin
if statementtype = 'Insert' then
insert into bookAuthor (authorLname,authorFname,authorMname)
values (lname,fname,mname);
elseif statementtype = 'Update' then
update bookAuthor
set authorLname = lname, authorFname = fname, authorMname = mname
where authorID = id;
elseif statementtype = 'Select' then
select * from bookAuthor;
elseif statementtype = 'Delete' then
delete from bookAuthor where authorID = id;
end if;
end
请注意,如果像我一样将过程编写为IF/ELSEIF
块,则由于过程中只有一个语句,因此您并不一定需要BEGIN/END
包装器。
这是该过程的demo on dbfiddle。