当前位置:网站首页>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
边栏推荐
- Introduction to new features of ES6
- 基于ThinkPHP5封装-tronapi-波场接口-源码无加密-可二开--附接口文档-作者详细指导-2022年6月30日08:45:27
- 图解使用Navicat for MySQL创建存储过程
- New function of SuperMap iserver11i -- release and use of legend
- Questionnaire star questionnaire packet capturing analysis
- Determining the subject area of data warehouse construction
- Swagger2 automatically generates API documents
- Docker安装Mysql8和sqlyong连接报错2058的解决方法[随笔记录]
- Two batches of pure milk are unqualified? Michael responded that he was conducting a large-scale screening and sampling inspection of products
- Redis的基本操作的命令
猜你喜欢

ECDSA signature verification in crypt

腾讯二面:@Bean 与 @Component 用在同一个类上,会怎么样?

机器学习笔记 - 自相关和偏自相关简介

SuperMap iclient3d for webgl loading TMS tiles

60 个神级 VS Code 插件!!
![[target tracking] |pytracking configuring win to compile prroi_ pool. pyd](/img/ac/1e443164e57c4f34ddd1078de9f0d2.png)
[target tracking] |pytracking configuring win to compile prroi_ pool. pyd

60 divine vs Code plug-ins!!

Apple executives openly "open the connection": Samsung copied the iPhone and only added a large screen

QT MSVC installation and commissioning

Android development interview real question advanced version (with answer analysis)
随机推荐
JMeter性能测试之相关术语及性能测试通过标准
[target tracking] |pytracking configuring win to compile prroi_ pool. pyd
Redis configuration files and new data types
How to solve cross domain problems
Three ways for flinksql to customize udaf
时空预测2-GCN_LSTM
第十三章 信号(三)- 示例演示
JMeter性能测试工作中遇到的问题及剖析,你遇到了几个?
21. Notes on WPF binding
机器学习笔记 - 自相关和偏自相关简介
[MySQL] MySQL installation and configuration
New function of SuperMap iserver11i -- release and use of legend
[yitianxue awk] regular matching
[learn awk in one day] operator
【目标跟踪】|pytracking 配置 win 编译prroi_pool.pyd
Sublist3r error reporting solution
Commands for redis basic operations
Tronapi-波场接口-PHP版本--附接口文档-基于ThinkPHP5封装-源码无加密-可二开-作者详细指导-2022年6月28日11:49:56
Pharmacy management system
Dqn notes