MySQL - 变量

MySQL变量分为两大类:系统变量(会话变量、全局变量) 和 用户变量(局部变量、用户变量)

1、局部变量

只能位于存贮过程内,放在存贮过程中,位于begin-end块中

– 定义:局部变量名 类型(宽度,精度) default 默认值;
declare sum decimal(5) default 0;

  • 赋值:
    形式一:set 局部变量名=值;
    形式二:select 查询项 into 局部变量 from 表|视图。。。
    select sum(salary) into deptSalary from employees where department_id=90;
  • 查看:select 局部变量名;

2、用户变量

不用定义,在使用是前面 @变量名,作用域是当前连接
  • 赋值:
    形式一:set @变量名=值; set @变量名:=值;
    形式二:select:=查询项1,查询项2… from 表|视图。。。
    形式三:select @变量名=值; 具有赋值并查询的功能

  • 查看:select @用户变量名;

set @x:=0;
select @x;

set @x:=@x+1;
select @x;

set @x=@x+1;
select @x;

set @x:=@x+1;
select @x;

select @x:=@x+1;
select @x;

select department_id, @rs:=count(employee_id)deptNum from employees where department_id=90;

select @rs;

3、会话变量(系统变量)

服务器为每个客户端连接维护的变量,作用域是当前连接,每个连接得会话变量是独立的
  • 查看所有的会话变量
    show VARIABLES;
    – 等价于
    show SESSION VARIABLES;
    show local variables;

  • 查看指定的会话变量
    show variables like 'tx%';
    show variables like 'autocommit%';

    select @@autocommit;
    – 等价于
    select @@session.autocommit;

  • 设置会话变量的值

set session auto_increment_increment=2; -- session可以省略,也可以换成local
set auto_increment_increment=2;
set @@session.autocommit=off;
set @@local.autocommit=on;

drop table if exists test;
CREATE TABLE test(id int auto_increment not null PRIMARY KEY ,col VARCHAR(10));
INSERT INTO test(col) VALUES('abc');
INSERT INTO test(col) VALUES('xyz');
SELECT * FROM test;

以上会话变量的修改仅在会话期间保留,再次打开时,系统会认为是一个新的会话,会重新初始化所有的系统变量

4、全局变量

保留服务器的配置,服务器启动时,系统会初始化所有的全局变量为默认值
  • 必须是super权限才可以修改全局变量
    – 查看全部
    show global variables;
    – 查看部分
    show global variables like 'auto%';
    select @@global.auto_increment_increment;

  • 设置全局变量
    set global auto_increment_increment=2; 修改了全局变量的值
    set @@global.auto_increment_increment=2;
    show variables; 当有同名的会话变量时,会话变量的值不会因为全局变量的值改变而改变

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值