Mysql 虽不像其他语言一样灵活,但是也可以使用简单的变量。



使用 set

1
2
> set @id = 1;
> select * from user where id = @id;
1
2
> set @count = (select count(0) from user);
> select @count;

使用 select

1
2
> select count(0) into @count from user;
> select @count;
1
2
> select max(status), avg(status) into @max, @avg from user;
> select @max, @avg;

存储过程

1
2
3
4
5
6
7
8
9
10
11
12
drop procedure IF EXISTS test;
delimiter //
create procedure test()
begin
DECLARE cnt INT DEFAULT 0;
select count(*) into cnt from user;
select cnt;
end
//
delimiter ;

call test();
03-16 21:25