mysql @变量和变量的区别及怎么判断记录唯一性
DELIMITER//
drop PROCEDURE if EXISTS test.express;
create PROCEDURE test.express()
BEGIN
select count(1) into @a from test.test_user where userid='user';
select @a;
IF @a>1 THEN
select 'hello world';
ELSE
select 'error';
END IF;
END
//
CALL test.express();
通过
select count(1) into @a from test.test_user where userid='user';
通过@a变量是否大于1为条件进行判断。
注意:在这里我们使用了@变量,那么变量有什么区别呢?
(引自:http://stackoverflow.com/questions/1009954/mysql-variable-vs-variable-whats-the-difference)
MySQL
has the concept of user-defined variables.
They are loosely typed variables that may be initialized somewhere in a session and keep their value until the session ends.
They are prepended with an @
sign, like this: @var
You can initialize this variable with a SET
statement or inside in a query:
SET @var := 1 SELECT @var2 := 2
When you develop a stored procedure in MySQL
, you can pass the input parameters and declare the local variables:
DELIMITER // CREATE PROCEDURE prc_test (var INT)
BEGIN
DECLARE var2 INT;
SET var2 = 1;
SELECT var2;
END;
// DELIMITER ;
These variables are not prepended with any prefixes.
The difference between a procedure variable and a session-specific user-defined variable is that procedure variable is reinitialized to NULL
each time the procedure is called, while the session-specific variable is not:
CREATE PROCEDURE prc_test ()
BEGIN
DECLARE var2 INT DEFAULT 1;
SET var2 := var2 + 1;
SET @var2 := @var2 + 1;
SELECT var2, @var2;
END; SET @var2 = 1; CALL prc_test(); var2 @var2
--- ---
2 2 CALL prc_test(); var2 @var2
--- ---
2 3 CALL prc_test(); var2 @var2
--- ---
2 4
As you can see, var2
(procedure variable) is reinitialized each time the procedure is called, while @var2
(session-specific variable) is not.
(In addition to user-defined variables, MySQL also has some predefined "system variables", which may be "global variables" such as @@global.port
or "session variables" such as @@session.sql_mode
; these "session variables" are unrelated to session-specific user-defined variables.)
附录:(http://dev.mysql.com/doc/refman/5.0/en/user-variables.html)
User-Defined Variables
You can store a value in a user-defined variable in one statement and then refer to it later in another statement. This enables you to pass values from one statement to another. User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients. All variables for a given client session are automatically freed when that client exits.
User variables are written as @
, where the variable name var_name
var_name
consists of alphanumeric characters, “.
”, “_
”, and “$
”. A user variable name can contain other characters if you quote it as a string or identifier (for example, @'my-var'
, @"my-var"
, or @`my-var`
).
User variable names are not case sensitive in MySQL 5.0 and up, but are case sensitive before MySQL 5.0.
One way to set a user-defined variable is by issuing a SET
statement:
SET @var_name
=expr
[, @var_name
=expr
] ...
For SET
, either =
or :=
can be used as the assignment operator.
You can also assign a value to a user variable in statements other than SET
. In this case, the assignment operator must be :=
and not =
because the latter is treated as the comparison operator =
in non-SET
statements:
mysql>SET @t1=1, @t2=2, @t3:=4;
mysql>SELECT @t1, @t2, @t3, @t4 := @t1+@t2+@t3;
+------+------+------+--------------------+
| @t1 | @t2 | @t3 | @t4 := @t1+@t2+@t3 |
+------+------+------+--------------------+
| 1 | 2 | 4 | 7 |
+------+------+------+--------------------+
User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary or nonbinary string, or NULL
value. Assignment of decimal and real values does not preserve the precision or scale of the value. A value of a type other than one of the permissible types is converted to a permissible type. For example, a value having a temporal or spatial data type is converted to a binary string.
If a user variable is assigned a nonbinary (character) string value, it has the same character set and collation as the string. The coercibility of user variables is implicit as of MySQL 5.0.3. (This is the same coercibility as for table column values.)
Bit values assigned to user variables are treated as binary strings. To assign a bit value as a number to a user variable, use CAST()
or +0
:
mysql>SET @v1 = b'1000001';
mysql>SET @v2 = CAST(b'1000001' AS UNSIGNED), @v3 = b'1000001'+0;
mysql>SELECT @v1, @v2, @v3;
+------+------+------+
| @v1 | @v2 | @v3 |
+------+------+------+
| A | 65 | 65 |
+------+------+------+
If the value of a user variable is selected in a result set, it is returned to the client as a string.
If you refer to a variable that has not been initialized, it has a value of NULL
and a type of string.
User variables may be used in most contexts where expressions are permitted. This does not currently include contexts that explicitly require a literal value, such as in the LIMIT
clause of a SELECT
statement, or the IGNORE
clause of a N
LINESLOAD DATA
statement.
As a general rule, other than in SET
statements, you should never assign a value to a user variable and read the value within the same statement. For example, to increment a variable, this is okay:
SET @a = @a + 1;
For other statements, such as SELECT
, you might get the results you expect, but this is not guaranteed. In the following statement, you might think that MySQL will evaluate @a
first and then do an assignment second:
SELECT @a, @a:=@a+1, ...;
However, the order of evaluation for expressions involving user variables is undefined.
Another issue with assigning a value to a variable and reading the value within the same non-SET
statement is that the default result type of a variable is based on its type at the start of the statement. The following example illustrates this:
mysql>SET @a='test';
mysql>SELECT @a,(@a:=20) FROM
tbl_name
;
For this SELECT
statement, MySQL reports to the client that column one is a string and converts all accesses of @a
to strings, even though @a is set to a number for the second row. After the SELECT
statement executes, @a
is regarded as a number for the next statement.
To avoid problems with this behavior, either do not assign a value to and read the value of the same variable within a single statement, or else set the variable to 0
, 0.0
, or ''
to define its type before you use it.
In a SELECT
statement, each select expression is evaluated only when sent to the client. This means that in aHAVING
, GROUP BY
, or ORDER BY
clause, referring to a variable that is assigned a value in the select expression list does not work as expected:
mysql> SELECT (@aa:=id) AS a, (@aa+3) AS b FROM tbl_name
HAVING b=5;
The reference to b
in the HAVING
clause refers to an alias for an expression in the select list that uses @aa
. This does not work as expected: @aa
contains the value of id
from the previous selected row, not from the current row.
User variables are intended to provide data values. They cannot be used directly in an SQL statement as an identifier or as part of an identifier, such as in contexts where a table or database name is expected, or as a reserved word such as SELECT
. This is true even if the variable is quoted, as shown in the following example:
mysql>SELECT c1 FROM t;
+----+
| c1 |
+----+
| 0 |
+----+
| 1 |
+----+
2 rows in set (0.00 sec) mysql>SET @col = "c1";
Query OK, 0 rows affected (0.00 sec) mysql>SELECT @col FROM t;
+------+
| @col |
+------+
| c1 |
+------+
1 row in set (0.00 sec) mysql>SELECT `@col` FROM t;
ERROR 1054 (42S22): Unknown column '@col' in 'field list' mysql> SET @col = "`c1`";
Query OK, 0 rows affected (0.00 sec) mysql>SELECT @col FROM t;
+------+
| @col |
+------+
| `c1` |
+------+
1 row in set (0.00 sec)
An exception to this principle that user variables cannot be used to provide identifiers is that if you are constructing a string for use as a prepared statement to be executed later. In this case, user variables can be used to provide any part of the statement. The following example illustrates how this can be done:
mysql>SET @c = "c1";
Query OK, 0 rows affected (0.00 sec) mysql>SET @s = CONCAT("SELECT ", @c, " FROM t");
Query OK, 0 rows affected (0.00 sec) mysql>PREPARE stmt FROM @s;
Query OK, 0 rows affected (0.04 sec)
Statement prepared mysql>EXECUTE stmt;
+----+
| c1 |
+----+
| 0 |
+----+
| 1 |
+----+
2 rows in set (0.00 sec) mysql>DEALLOCATE PREPARE stmt;
Query OK, 0 rows affected (0.00 sec)
See Section 13.5, “SQL Syntax for Prepared Statements”, for more information.
A similar technique can be used in application programs to construct SQL statements using program variables, as shown here using PHP 5:
<?php
$mysqli = new mysqli("localhost", "user", "pass", "test"); if( mysqli_connect_errno() )
die("Connection failed: %s\n", mysqli_connect_error()); $col = "c1"; $query = "SELECT $col FROM t"; $result = $mysqli->query($query); while($row = $result->fetch_assoc())
{
echo "<p>" . $row["$col"] . "</p>\n";
} $result->close(); $mysqli->close();
?>
Assembling an SQL statement in this fashion is sometimes known as “Dynamic SQL”.
mysql @变量和变量的区别及怎么判断记录唯一性的更多相关文章
- MySQL 存储过程的变量
MySQL 存储过程的变量 变量是一个命名数据对象,变量的值可以在存储过程执行期间更改.我们通常使用存储过程中的变量来保存直接/间接结果. 这些变量是存储过程的本地变量. 注意:变量必须先声明后,才 ...
- MySQL学习之变量
变量 MySQL本质是一种编程语言,需要很多变量来保存数据,mysql中很多的属性控制都是通过MySQL中固有的变量来实现的. 系统变量 系统内部定义的变量,系统变量针对的是所有用户(MySQL客户端 ...
- C/C++文字常量与常变量的概念与区别 分类: C/C++ 2015-06-10 22:56 111人阅读 评论(0) 收藏
以下代码使用平台是Windows 64bits+VS2012. 在C/C++编程时,经常遇到以下几个概念:常量.文字常量.符号常量.字面常量.常变量.字符串常量和字符常量,网上博客资料也是千篇千律,不 ...
- SQL Server 表变量和临时表的区别
SQL Server 表变量和临时表的区别 一.表变量 表变量在SQL Server 2000中首次被引入.表变量的具体定义包括列定义,列名,数据类型和约束.而在表变量中可以使用的约束包括主键约束,唯 ...
- sqlserver中表变量和变量表之间区别
sqlserver中表变量和变量表之间区别
- 工作流Activiti5流程变量 任务变量 setVariables 跟 setVariablesLocal区别
工作流Activiti5流程变量 任务变量 setVariables 和 setVariablesLocal区别 因为网上的资料比较少.结合源码把相关API写下来. 设置流程级别变量: runtime ...
- MySQL的环境变量
MySQL的环境变量 服务器变量:调整MySQL的工作属性,由MySQL的配置文件决定 状态变量:MySQL运行以后所输出的自身统计信息 在Linux下查看MySQL的环境变量 1.获取MySQL客户 ...
- .NET中公共变量与属性的区别
在我们的程序中经常会出现以下的代码: 如: 成员变量 public string Name; 或者用属性 private string name ...
- MariaDB/MySQL中的变量
在MySQL/MariaDB中有好几种变量类型:用户自定义变量.系统变量.一般的临时变量(即本地变量,或称为局部变量). 1.用户变量 用户变量是基于会话的,也是基于用户的,所以我觉得称之为会话变量更 ...
随机推荐
- C++ 类的前向声明
前向声明 在计算机程序设计中, 前向声明是指声明标识符(表示编程的实体,如数据类型.变量.函数)时还没有给出完整的定义.即可以声明一个类而不定义它,只声明类但不知道类的成员变量.函数等具体细节. 如: ...
- Nginx fastcgi_param解释
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;#脚本文件请求的路径 fastcgi_param QUERY_STRI ...
- 在Linux终端执行clear或top命令时出现:'xterm': unknown terminal type
在Linux终端执行clear或top命令时出现:'xterm': unknown terminal type的错误. 例如: [root@localhost phpmyadmin]# clear ' ...
- 开发DZ插件教程
插件制作的基本思路是:(初学者适用)1.形成插件思路2.制作插件界面3.构架程序模块4.搭建存储数据5.填充功能语句6.检查应用错误7.完善插件功能 前言:为方便互联网数万Discuz!爱好者,更加深 ...
- .net序列化和反系列化json与类型对象转换
先添加程序集: System.Web.Extensions(在 System.Web.Extensions.dll 中) 引用:using System.Web.Script.Serializati ...
- 简明解释算法中的大O符号
伯乐在线导读:2009年1月28日Arec Barrwin在StackOverflow上提问,“有没有关于大O符号(Big O notation)的简单解释?尽量别用那么正式的定义,用尽可能简单的数学 ...
- libcurl的封装,支持同步异步请求,支持多线程下载,支持https
最近在做一个项目,需要用到http get post等 需求分析需要做到同步和异步,异步请求的返回以可选的回调通知的方式进行. 本人以Linux为例,一步一步的来实现. 配置并且编译libcurl我以 ...
- BZOJ 1014 火星人prefix
Description 火星人最近研究了一种操作:求一个字串两个后缀的公共前缀.比方说,有这样一个字符串:madamimadam,我们将这个字符串的各个字符予以标号:序号: 1 2 3 4 5 6 7 ...
- Arctic Network
poj2349:http://poj.org/problem?id=2349 题意:有卫星电台的城市之间可以任意联络.没有卫星电台的城市只能和距离小于等于D的城市联络.告诉你卫星电台的个数S,让你求最 ...
- c#获取带有汉字的字符串长度
不知道大家注意没,用c#下自带的str.Length方法获得字符串str长度的时候,返回的总是字符的个数,但是如果字符串中包含汉字的话,一个汉字是占两个字符长度的,获取的长度值就有了问题. 解决方案: ...