当前位置:网站首页>Definition of variables and assignment of variables in MySQL
Definition of variables and assignment of variables in MySQL
2022-06-30 12:47:00 【Full stack programmer webmaster】
explain : Now the tutorials and books on defining variables are basically on stored procedures , But variables can only act on begin…end In block , However, the definition and use of common variables are less , To solve these problems, we can only find explanations in the official documents .
Preface
MySQL Stored procedure , There are two ways to define variables : 1、 Use set or select Direct assignment , The variable name is @ start for example :
set @var=1; You can declare... Anywhere in a conversation , The scope is the entire session , Called user variable .
2、 With declare Keyword declared variables , Can only be used in stored procedures , Called a stored procedure variable , for example :
declare var1 int default 0; Mainly used in the storage process , Or send parameters to storage .
The difference between the two :
When calling a stored procedure , With declare Declared variables are initialized to null. And the conversation variable ( namely @ Variable at the beginning ) Will not be reinitialized , In a conversation , Just initialize once , After that, the results of the last calculation are all within the session , It's equivalent to the global variable in this session .
Main content
- local variable
- User variables
- Session variables
- Global variables
Session variables and global variables are called system variables .
One 、 local variable , Only in the present begin/end Valid in code block Local variables are generally used in sql In the block , For example, stored procedure begin/end. Its scope is limited to the statement block , After execution of the statement block , Local variables disappear .declare Statement is used specifically to define a local variable , have access to default To describe the default values .set Statement is to set different types of variables , Including session variables and global variables . Local variables define the syntax form
declare var_name [, var_name]... data_type [ DEFAULT value ];For example, in begin/end Add the following statement to the statement block , Accept the function passed in a/b Variables are then added , adopt set The statement is assigned to c Variable .
set Sentence grammatical form set var_name=expr [, var_name=expr]…; set Statement can be used for the assignment of local variables , It can also be used for declaration and assignment of user variables .
declare c int default 0;
set c=a+b;
select c as C;Or use select …. into… Form assignment
select into Sentence pattern :select col_name[,...] into var_name[,...] table_expr [where...];Example :
declare v_employee_name varchar(100);
declare v_employee_salary decimal(8,4);
select employee_name, employee_salary
into v_employee_name, v_employee_salary
from employees
where employee_id=1;Two 、 User variables , The user variables are valid throughout the process of linking the client to the database instance .
MySQL The user variable in does not need to be stated in advance , Use... Directly when using “@ Variable name ” Just use it .
First usage :set @num=1; or set @num:=1; // Use here set Statement to create and initialize variables , Use it directly @num Variable
Second usage :select @num:=1; or select @num:= Field name from Table name where ……,
select Statement is used to output user variables , such as select @ Variable name , Data used to output data sources that are not tables .
Notice the two assignment symbols above , Use set Can be used when “=” or “:=”, But use select Must use “:= assignment ”
User variables are connected to the database of , Variables declared in the connection , After the user variable is created in the stored procedure, it will continue until the database instance is disconnected , Variables will disappear .
Variables declared in this connection cannot be used in another connection .
The variable name of the user variable takes the form @varname In the form of .
The name must be @ start .
You need to use... When declaring variables set sentence , For example, the following statement declares a statement named @a The variable of .
set @a = 1;
Declare a @a The variable of , And assign it to 1,MySQL The variables in it are not strictly limited to data types , Its data type varies according to the value you assign to it .(SQL SERVER Use in declare Statement declaration variables , And strictly limit the data type .)
We can also use select Statement to assign a value to a variable .
such as :
set @name = '';
select @name:=password from user limit 0,1;
# Get a record from the data table password The value of the field is given to @name Variable . Output to query result set after execution .( Notice that there is a colon in front of the equals sign , hinder limit 0,1 Is used to limit the return of results , It can be 0 or 1 individual . amount to SQL SERVER Inside top 1)
If you write directly :select @name:=password from user;
If the query returns multiple values , that @name The value of the variable is the last recorded password Value of field .
User variables can act on the current entire connection , But when the current connection is broken , All user variables defined by it will disappear .
User variables are used as follows ( We don't need to use declare Keywords define user variables , It can be used directly ) Definition , The variable name must be @ Start :
# Definition
select @ Variable name perhaps select @ Variable name := Field name from Table name where Filter statements ;
set @ Variable name ;
# assignment @num Variable name ,value Value
set @num=value; or select @num:=value;There are two ways to assign values to user variables , One is direct use ”=” Number , The other is to use ”:=” Number . The difference lies in the use of set When the command assigns a value to a user variable , Both methods can be used ; When using select Statement when assigning a value to a user variable , Only use ”:=” The way , Because in select In the sentence ,”=” Number declare Statement is used specifically to define a local variable .set Statement is to set different types of variables , Including session variables and global variables .
for example :
begin
#Routine body goes here...
#select c as c;
declare c int default 0;
set @var1=143; # Define a user variable , And initialize to 143
set @var2=34;
set c=a+b;
set @d=c;
select @sum:=(@[email protected]) as sum, @dif:=(@[email protected]) as dif, @d as C;# Use user variables [email protected] Represents the variable name
set c=100;
select c as CA;
end
# Execute the following statement segment in the query
call `order`(12,13); # Execute the stored procedure defined above
select @var1; # Look at the user variables defined after the execution of the stored procedure , Whether it can also output , The result is that user variables can be output @var1,@var2 two-variable .
select @var2;The execution of the order After the stored procedure , New in stored procedure var1,var2 User variables can still be used select Statement output , But the local variables defined in the stored procedure c Can't identify .
System variables :
System variables are divided into global variables and session variables .
The global variable is in MySQL At startup, the server automatically initializes them to the default value , These default values can be changed by my.ini This file to change .
Session variables every time a new connection is established , from MySQL To initialize the .MySQL Copies the values of all current global variables . As a conversation variable .
( in other words , If after the session is established , The values of session variables and global variables have not been changed manually , So the values of all these variables are the same .)
The difference between a global variable and a session variable is , Changes to global variables affect the entire server , But changes to session variables , It only affects the current conversation ( That is, the current database connection ).
We can use
show session variables;Statement to output all session variables ( I could just write it as show variables, If you don't specify whether to output global variables or session variables , Output session variables by default .) If you want to output all global variables :
show global variablesThe values of some system variables can be changed dynamically using statements , But some system variables are read-only .
For those system variables that can be changed , We can use set Statement changes .
There are two system variables before the variable name @;
If you want to change Session variables Value , Using statements :
set session varname = value;
perhaps
set @@session.varname = value;such as :
mysql> set session sort_buffer_size = 40000;
Query OK, 0 rows affected(0.00 sec)
use select @@sort_buffer_size; Output to see what the changed value is .
If you want to change the value of a global variable , take session Change to global:
set global sort_buffer_size = 40000;
set @@global.sort_buffer_size = 40000;But to change the value of a global variable , Need to own super jurisdiction .
( Be careful ,root Just a built-in account , Not a kind of authority , This account has MySQL All permissions in the database . Any account as long as it has the name super The authority of , You can change the value of the global variable , As long as any user has file Permission can be called load_file perhaps into outfile,into dumpfile,load data infile equally .)
utilize select We can Query the value of a single session variable or a global variable :
select @@session.sort_buffer_size
select @@global.sort_buffer_size
select @@global.tmpdirWhatever is mentioned above session, Both can be used. local This keyword replaces .
such as :
select @@local.sort_buffer_size
local yes session A synonym for .No matter when setting system variable or querying system variable value , As long as you don't specify whether it is a global variable or a session variable . All as session variables .
such as :
set @@sort_buffer_size = 50000;
select @@sort_buffer_size; None of the above is designated as blobal still session, So all as session Handle .
3、 ... and 、 Session variables
The server maintains a series of session variables for each connected client . When the client connects to the database instance , Use the current value of the corresponding global variable to initialize the client's session variable . Setting session variables does not require special permissions , But the client can only change its own session variables , The session variables of other clients cannot be changed . Session variables have the same scope as user variables , Current connection only . When the current connection is disconnected , All session variables it sets are invalid .
There are three ways to change the value of a session variable :
set session var_name = value;
set @@session.var_name = value;
set var_name = value; # default session The default keyword is session
View all session variables
show session variables;There are three ways to view a session variable :
select @@var_name;
select @@session.var_name;
show session variables like "%var%";Whatever is mentioned above session, Both can be used. local This keyword replaces .
such as :
select @@local.sort_buffer_size
local yes session A synonym for .Four 、 Global variables
Global variables affect the overall operation of the server . When the server starts , It initializes all global variables to default values . These defaults can be changed in the options file or in the options specified on the command line . To change global variables , Must possess super jurisdiction . The global variable acts on server The entire life cycle , But not across reboots . That is to say, all global variables set after restart are invalid . For global variables to continue to take effect after restart , The corresponding configuration file needs to be changed .
To set a global variable , There are two ways :
set global var_name = value; // Be careful : Here global Don't omit . According to the manual ,set Command to set variables if you do not specify GLOBAL、SESSION perhaps LOCAL, By default SESSION
set @@global.var_name = value; // ditto View all global variables
show global variables; To see a global variable , There are two ways :
select @@global.var_name;
show global variables like “%var%”;Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/100678.html Link to the original text :https://javaforall.cn
边栏推荐
- NoSQL - redis configuration and optimization
- Four ways for flinksql to customize udtf
- 视频按每100帧存一个文件夹,处理完再图片转视频
- Pharmacy management system
- 腾讯二面:@Bean 与 @Component 用在同一个类上,会怎么样?
- Substrate 源码追新导读: 5月中旬: Uniques NFT模块和Nomination Pool
- New function of SuperMap iserver11i -- release and use of legend
- Layout of pyqt5 interface and loading of resource files
- Wechat launched the picture big bang function; Apple's self-developed 5g chip may have failed; Microsoft solves the bug that causes edge to stop responding | geek headlines
- 江西财经大学智慧江财登录分析
猜你喜欢

Android development interview real question advanced version (with answer analysis)

Redis-缓存问题
![[qnx hypervisor 2.2 user manual]6.2.3 communication between guest and external](/img/ca/9065325ce8882d95fb24c82fb62abc.png)
[qnx hypervisor 2.2 user manual]6.2.3 communication between guest and external

Lichuang EDA learning notes 10 common connector component identification and passive buzzer driving circuit

数据仓库建设之确定主题域

Visual studio configures QT and implements project packaging through NSIS

【一天学awk】内置变量的使用

【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(二)

电机控制park变换公式推导
![[yitianxue awk] regular matching](/img/a6/608ec8d0808dfae04d19dfeea66399.png)
[yitianxue awk] regular matching
随机推荐
数据仓库建设之确定主题域
图解使用Navicat for MySQL创建存储过程
浅谈 JMeter 运行原理
[qnx hypervisor 2.2 user manual]6.2.3 communication between guest and external
【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(二)
Analysis of smart jiangcai login in Jiangxi University of Finance and Economics
Dqn notes
JMeter之事务控制器
江西财经大学智慧江财登录分析
Lichuang EDA learning notes 10 common connector component identification and passive buzzer driving circuit
【C语言深度解剖】float变量在内存中存储原理&&指针变量与“零值”比较
【驚了】迅雷下載速度竟然比不上虛擬機中的下載速度
Google refutes rumors and gives up tensorflow. It's still alive!
MySQL built-in functions
解决numpy.core._exceptions.UFuncTypeError: ufunc ‘add‘ did not contain a loop with signature matchin问题
全面解析免费及收费SSH工具的基本特性和总结
Two batches of pure milk are unqualified? Michael responded that he was conducting a large-scale screening and sampling inspection of products
QT implementation dynamic navigation bar
Substrate 源码追新导读: Call调用索引化, 存储层事物化全面完成
【OpenGL】OpenGL Examples