#创建存储过程
DELIMITER $
CREATE PROCEDURE testa()
BEGIN
SELECT * FROM student;
SELECT * FROM cj;
END $
DELIMITER ;
#调用存储过程
CALL testa();
#创建存储过程
DELIMITER $
CREATE PROCEDURE test2()
BEGIN
#声明变量类型
DECLARE UN VARCHAR(32) DEFAULT'';
#给username变量赋值
SET un='xiaoxiao';
#将查询结果赋值给un变量
SELECT username INTO FROM student WHERE stuid =1;
#查询un变量,返回
SELECT un;
END $
DELIMITER;
#调用存储过程
CALL test2();
#变量的作用过程
DELIMITER $
CREATE PROCEDURE test3()
BEGIN
BEGIN
BEGIN
#声明变量类型
DECLARE UN VARCHAR(32) DEFAULT'';
#给username变量赋值
SET un='xiaoxiao';
#将查询结果赋值给un变量
SELECT username INTO FROM student WHERE stuid =1;
#查询un变量,返回
SELECT un;
END $
BEGIN
#声明变量类型
DECLARE UN VARCHAR(32) DEFAULT'';
#给username变量赋值
SET un='xiaoxiao';
#将查询结果赋值给un变量
SELECT username INTO FROM student WHERE stuid =1;
#查询un变量,返回
SELECT un;
END;
END $
DELIMITER ;
#调用存储过程
CALL test3();
#创建库
CREATE DATABASE IF NOT EXISTS test DEFAULT CHARSET UTF8;
USE test;
#创建表
CREATE TABLE IF NOT EXISTS users
(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50),
age INT,
STATUS INT,
score INT,
accontid INT
);
SELECT * FROM users;
#插入数据
INSERT INTO users(NAME,age,STATUS,score,accontid)
VALUES('张三',19,0,40,10001),
('李四',15,1,0,10002),
('王五',15,2,0,10001),
('王小利',20,3,0,10003);
CREATE TABLE IF NOT EXISTS orders
(
id INT PRIMARY KEY AUTO_INCREMENT,
order_name VARCHAR(50),
carete_date DATETIME,
money INT
);
SELECT * FROM orders;
INSERT INTO orders(order_name,carete_date,money)
VALUES('201902020001','2019-02-20 09:53:22',200),
('201902020002','2019-04-20 08:53:22',100),
('20190219003','2019-03-20 07:53:22',300);
#创建存储过程
DELIMITER $
CREATE PROCEDURE test4(userId INT)
BEGIN
#声明变量usernaem
DECLARE username VARCHAR(32) DEFAULT '';
#声明变量订单数量ordercount
#declare ordercount int default 0;
#查询语句,将用户表的名字放到username变量
SELECT NAME INTO username FROM users WHERE id=userId;
#将变量username查出
SELECT username;
END $
DELIMITER ;
CALL test4(1);
#创建存储过程
DELIMITER $
CREATE PROCEDURE test7(userId INT)
BEGIN
#声明变量usernaem
DECLARE username VARCHAR(32) DEFAULT '';
IF(userId%2=0)
THEN
#查询语句,将用户表的名字放到username变量
SELECT NAME INTO username FROM users WHERE id=userId;
#将变量username查出
SELECT username;
ELSE
SELECT userId;
END IF;
END $
DELIMITER ;
CALL test7(2);
#创建存储过程
DELIMITER $
CREATE PROCEDURE test9()
BEGIN
#声明变量
DECLARE i INT DEFAULT 0;
#while循环,do后面是循环体
WHILE(i<10)DO
BEGIN
SELECT i;
SET i=i+1;
INSERT INTO test1(id) VALUES(i);
END;
#结束循环
END WHILE;
END $
DELIMITER $;
CALL test9();
SELECT * FROM test1;
#创建存储过程
DELIMITER $
CREATE PROCEDURE test10()
BEGIN
#声明变量
DECLARE i INT DEFAULT 0;
#while循环,do后面是循环体
REPEAT
BEGIN
SELECT i;
SET i=1+1;
INSERT INTO test1(id) VALUES(i);
END;
#结束循环
UNTIL i>=10;
END REPEAT;
END $
DELIMITER $;
CALL test10();
#定义函数
DELIMITER $
CREATE FUNCTION getusername(userid INT) RETURNS VARCHAR(32)
READS SQL DATA #从数据库中读取数据,但不修改数据
BEGIN
DECLARE username VARCHAR(32) DEFAULT '';
SELECT NAME INTO username FROM users WHERE id=userid;
RETURN username;
END $
DELIMITER ;
#调用函数
SELECT getusername(1);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)