Get the type of a variable in MySQL

后端 未结 3 1519
感情败类
感情败类 2021-01-01 22:32

If I define a variable like set @a = \"1\";. How can I see that @a is a string?

相关标签:
3条回答
  • 2021-01-01 23:01

    You CAN determine the type of a variable in MySQL. Create a table by selecting your variable and then check the column type:

    set @a:="1"; -- your variable
    
    drop temporary table if exists foo;
    create temporary table foo select @a; -- dirty magic
    desc foo;
    +-------+----------+------+-----+---------+-------+
    | Field | Type     | Null | Key | Default | Extra |
    +-------+----------+------+-----+---------+-------+
    | @a    | longtext | YES  |     | NULL    |       |
    +-------+----------+------+-----+---------+-------+
    
    0 讨论(0)
  • 2021-01-01 23:02

    In MySql, you cannot identify the Datatype of the variable. But there is a way to identify only the strings and Integer by using cast :

    set @a = "11";
    SELECT CAST(@a AS SIGNED); // Output : 11
    
    set @a = "text";
    SELECT CAST(@a AS SIGNED); // Output : 0
    
    
    set @a = "121212";
    SELECT CAST(@a AS SIGNED); // Output : 121212
    
    set @a = "Mysql is open source";
    SELECT CAST(@a AS SIGNED); // Output : 0
    
    0 讨论(0)
  • 2021-01-01 23:10

    You cannot determine the type of a variable in MySQL.

    As an alternative, you can easily CAST() your variable in the type you desire:

    @a = CAST(123 AS CHAR);
    

    More information and examples about casting in the MySQL Manual:

    11.9. Cast Functions and Operators

    0 讨论(0)
提交回复
热议问题