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 connection-specific.
That is, a user variable defined by one client cannot be seen or used by other clients.
All variables for a given client connection are automatically freed when that client exits.

In a SET statement, you may use either the= or the := operator to assign a
value to a user variable.
In a SELECT statement, you have to use the := operator for assigning a value to a variable.

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 = is treated as a
comparison operator in non-SET statements.

[変数の割り当て]
SETでは, 「 =:= 」の2パターンで変数を割り当てられる。
SELECTでは, 「 := 」のみ利用出来る。 「 = 」を利用すると比較になってしまう。

    ○ 正しい例

set_variables

X 間違い例
select_set_statement

———————————————————————
User variable names are not case sensitive
(ユーザー定義変数は、大文字小文字を区別しない)
———————————————————————

mysql> SET @a = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> SET @A = @a;
Query OK, 0 rows affected (0.00 sec)

mysql> select @a,@A,@a+@A;

not_case_sensitive

———————————————————————
continuing the session
(上記セッションのまま続けて変数を変更)
———————————————————————

mysql> SET @a = 2;
Query OK, 0 rows affected (0.00 sec)

mysql> select @a,@A,@a+@A;

user_variables

When the

    session ends, all its user variables are lost

, and user variables are

    specific to the client connection.

MYSQL user defined variable (ユーザー定義変数)

Comments are closed.

Post Navigation