-- 成员表
CREATE TABLE `customer` (
`id` int(11) unsigned NOT NULL COMMENT '主键',
`name` varchar(200) DEFAULT NULL COMMENT '用户名'
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- 测试存储过程
create table user_profile
(
uid int auto_increment,
stuName varchar(1000) not null,
gender enum('男','女') default '男' not null,
-- gender enum('1','0') default '1' not null, -- 1为男性
score float not null,
primary key(uid)
)engine=innodb charset=utf8;
delimiter // -- 声明分割符
drop procedure if exists wk; -- 如果存在就删除wk
create procedure wk(var varchar(1000)) -- 创建存储过程
begin
declare i int DEFAULT 1; -- 定义变量
while i < 11 do
insert into user_profile (uid,stuName) values (i,var);
set i = i +1;
end while;
end //
delimiter; -- 声明分割符结束
set @var:=(select GROUP_CONCAT(id) from customer); -- 定义变量
call wk(@var); -- 执行存储过程
select CHAR_LENGTH(@var:=(select GROUP_CONCAT(id) from customer));
select LENGTH(@var:=(select GROUP_CONCAT(id) from customer));
select count(*) from customer -- 查询成员总数
select CHAR_LENGTH(@var:=(select GROUP_CONCAT(id) from customer))-CHAR_LENGTH(REPLACE(@var:=(select GROUP_CONCAT(id) from customer),',','')) + 1; -- 得出数组成员总数
-- 实现mysql数组
DELIMITER //
DROP PROCEDURE IF EXISTS array;
CREATE PROCEDURE array(array_content varchar(10000))
BEGIN
SET @i=1;
SET @count=CHAR_LENGTH(array_content)-CHAR_LENGTH(REPLACE(array_content,',','')) + 1; -- 得出数组成员总数
CREATE TABLE tmp(field VARCHAR(100)); -- 创建字段表
WHILE @i <= @count DO
INSERT INTO tmp VALUES (SUBSTRING_INDEX(SUBSTRING_INDEX(array_content,',',@i),',',-1)); -- 依次插入每个成员 从左数第I个分隔符的右边全部,再从右数的第一个分隔符的左边:
SET @i=@i+1;
END WHILE;
END//
DELIMITER ;
set @var:=(select GROUP_CONCAT(id) from customer); -- 定义变量
call array(@var);
-- 游标使用循环结果集
DELIMITER //
DROP PROCEDURE IF EXISTS pro;
CREATE PROCEDURE pro(OUT param VARCHAR(1000)) -- 设置参数可以在外面访问
BEGIN
DECLARE myid INT(11);
DECLARE title VARCHAR(100);
DECLARE i INT DEFAULT 0;
DECLARE str VARCHAR(1000);
DECLARE len INT(2);
DECLARE num INT;
DECLARE cur CURSOR FOR SELECT id FROM customer; -- 定义游标查询
SELECT COUNT(*) INTO num FROM customer;
SET str='';
OPEN cur;
WHILE i
FETCH cur INTO myid; -- 获取游标中的数据
SET str = CONCAT(str,myid,',');
SET i=i+1;
END WHILE;
SELECT LENGTH(str) INTO len;
SELECT SUBSTR(str,1,len-1) INTO param;
CLOSE cur;
END//
DELIMITER ;
-- set @var:=(select GROUP_CONCAT(id) from customer); -- 定义变量
call pro(@var);
select @var;