1,创建一个简单的存储过程:
USE tests; # 指定数据库
DROP PROCEDURE test(); # 删除存储过程
DELIMITER // # 设置结束符号
CREATE PROCEDURE test() # 创建存储过程
BEGIN # 开始
SELECT * FROM test; # 要执行的语句
END // # 结束
DELIMITER ; # 把结束符号改回
CALL test(); # 调用存储过程
2,存储过程变量
USE tests; # 指定数据库
DROP PROCEDURE IF EXISTS test; # 删除存储过程
DELIMITER // # 设置结束符号
CREATE PROCEDURE test() # 创建存储过程
BEGIN # 开始
DECLARE A INT DEFAULT 0; # 声明一个变量,默认值为0
SELECT COUNT(*) INTO A FROM test; # 要执行的语句
SELECT A;
END // # 结束
DELIMITER ; # 把结束符号改回
CALL test(); # 调用存储过程
3.存储过程参数
USE tests; # 指定数据库
DROP PROCEDURE IF EXISTS test; # 删除存储过程
DELIMITER // # IN只能传入,不能返回。out能返回猫不能传入。inout能返回也能传入
CREATE PROCEDURE test(IN countryName VARCHAR(255))
BEGIN
SELECT *
FROM test
WHERE account = countryName;
END//
CALL test(“manji”); # 调用存储过程
返回多个值
USE tests;
DROP PROCEDURE IF EXISTS test;
DELIMITER //
CREATE PROCEDURE test(IN a INT,OUT b INT,OUT c VARCHAR(50))
BEGIN
SELECT COUNT() INTO b FROM test WHERE id = a;
SELECT COUNT() INTO c FROM test WHERE userId = a;
SELECT b,c;
END//
CALL test(1,@sum1,@sum2);
SELECT @sum1,@sum2;
IF判断
USE tests;
DROP PROCEDURE IF EXISTS test;
DELIMITER //
CREATE PROCEDURE test(IN a INT,OUT b INT,OUT c VARCHAR(50))
BEGIN
IF a=0 THEN
SET B = 0;
SET C = 0;
ELSEIF a>0 THEN
SELECT COUNT() INTO b FROM test WHERE id<a;
SELECT COUNT() INTO c FROM test1 WHERE userId<a;
END IF;
END//
CALL test(5,@sum1,@sum2);
SELECT @sum1,@sum2;
if和case嵌套
USE tests;
DROP PROCEDURE IF EXISTS test;
DELIMITER //
CREATE PROCEDURE test(IN a INT,OUT b INT)
BEGIN
DECLARE pandun INT DEFAULT 0;
IF a=0 THEN
SET b = 404;
ELSEIF a>0 THEN
SELECT userId INTO pandun FROM test1 WHERE userId=a;
CASE pandun
WHEN 1 THEN
SELECT COUNT(*) INTO b FROM test;
WHEN 2 THEN
SELECT COUNT(*) INTO b FROM test1;
WHEN 3 THEN
SET b =33;
ELSE
SET b = 0;
END CASE;
END IF;
END//
CALL test(3,@sum1);
SELECT @sum1;