Raú*_*vas 22 mysql database stored-procedures if-statement
我在尝试创建这个存储过程时遇到了一些困难,欢迎任何形式的帮助:
create procedure checando(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)
begin
if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
set resultado = 0;
else if exists (select * from compas where nombre = nombrecillo) then
set resultado = -1;
else
set resultado = -2;
end if;
end;
Run Code Online (Sandbox Code Playgroud)
我正在研究的表是:
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| Nombre | varchar(30) | YES | | NULL | |
| contrasenia | varchar(30) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
Run Code Online (Sandbox Code Playgroud)
Boh*_*ian 32
问题是你要么没有关闭你,if要么你需要elseif:
create procedure checando(
in nombrecillo varchar(30),
in contrilla varchar(30),
out resultado int)
begin
if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
set resultado = 0;
elseif exists (select * from compas where nombre = nombrecillo) then
set resultado = -1;
else
set resultado = -2;
end if;
end;
Run Code Online (Sandbox Code Playgroud)
Oct*_*adu 16
我认为这个结构:if exists (select...特定于MS SQL.在MySQL EXISTS谓词中告诉您子查询是否找到任何行,并且它的使用方式如下:SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
您可以像这样重写上面的代码行:
DELIMITER $$
CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)
BEGIN
DECLARE count_prim INT;
DECLARE count_sec INT;
SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;
if (count_prim > 0) then
set resultado = 0;
elseif (count_sec > 0) then
set resultado = -1;
else
set resultado = -2;
end if;
SELECT resultado;
END
Run Code Online (Sandbox Code Playgroud)