• 用户自定义变量

    用户自定义变量

    用户自定义变量格式为 @var_namevar_name 目前只支持字母,数字,_$组成。用户自定义变量是大小写不敏感的。

    用户自定义变量是跟 session 绑定的,也就是说只有当前连接可以看见设置的用户变量,其他客户端连接无法查看到。

    SET 语句可以设置用户自定义变量:

    1. SET @var_name = expr [, @var_name = expr] ...
    2. SET @var_name := expr

    对于 SET 语句,赋值操作符可以是 = 也可以是 :=

    例:

    1. mysql> SET @a1=1, @a2=2, @a3:=4;
    2. mysql> SELECT @a1, @a2, @t3, @a4 := @a1+@a2+@a3;
    3. +------+------+------+--------------------+
    4. | @a1 | @a2 | @a3 | @a4 := @a1+@a2+@a3 |
    5. +------+------+------+--------------------+
    6. | 1 | 2 | 4 | 7 |
    7. +------+------+------+--------------------+

    如果设置用户变量用了 HEX 或者 BIT 值,TiDB会把它当成二进制字符串。如果你要将其设置成数字,那么需要手动加上 CAST转换: CAST(.. AS UNSIGNED)

    1. mysql> SELECT @v1, @v2, @v3;
    2. +------+------+------+
    3. | @v1 | @v2 | @v3 |
    4. +------+------+------+
    5. | A | 65 | 65 |
    6. +------+------+------+
    7. 1 row in set (0.00 sec)
    8. mysql> SET @v1 = b'1000001';
    9. Query OK, 0 rows affected (0.00 sec)
    10. mysql> SET @v2 = b'1000001'+0;
    11. Query OK, 0 rows affected (0.00 sec)
    12. mysql> SET @v3 = CAST(b'1000001' AS UNSIGNED);
    13. Query OK, 0 rows affected (0.00 sec)
    14. mysql> SELECT @v1, @v2, @v3;
    15. +------+------+------+
    16. | @v1 | @v2 | @v3 |
    17. +------+------+------+
    18. | A | 65 | 65 |
    19. +------+------+------+
    20. 1 row in set (0.00 sec)

    如果获取一个没有设置过的变量,会返回一个 NULL:

    1. mysql> select @not_exist;
    2. +------------+
    3. | @not_exist |
    4. +------------+
    5. | NULL |
    6. +------------+
    7. 1 row in set (0.00 sec)

    用户自定义变量不能直接在 SQL 语句中被当成 identifier,例:

    1. mysql> select * from t;
    2. +------+
    3. | a |
    4. +------+
    5. | 1 |
    6. +------+
    7. 1 row in set (0.00 sec)
    8. mysql> SET @col = "a";
    9. Query OK, 0 rows affected (0.00 sec)
    10. mysql> SELECT @col FROM t;
    11. +------+
    12. | @col |
    13. +------+
    14. | a |
    15. +------+
    16. 1 row in set (0.00 sec)
    17. mysql> SELECT `@col` FROM t;
    18. ERROR 1054 (42S22): Unknown column '@col' in 'field list'
    19. mysql> SET @col = "`a`";
    20. Query OK, 0 rows affected (0.00 sec)
    21. mysql> SELECT @col FROM t;
    22. +------+
    23. | @col |
    24. +------+
    25. | `a` |
    26. +------+
    27. 1 row in set (0.01 sec)

    但是有一个例外是如果你在 PREPARE 语句中使用它,是可以的:

    1. mysql> PREPARE stmt FROM "SELECT @c FROM t";
    2. Query OK, 0 rows affected (0.00 sec)
    3. mysql> EXECUTE stmt;
    4. +------+
    5. | @c |
    6. +------+
    7. | a |
    8. +------+
    9. 1 row in set (0.01 sec)
    10. mysql> DEALLOCATE PREPARE stmt;
    11. Query OK, 0 rows affected (0.00 sec)

    更多细节。