为什么无法在mysql过程中对if语句进行正确的逻辑查询?

问题描述 投票:0回答:1

查询年份为18时的所有数据:

SELECT * from tb where year=18 //
+----+------+------+------+
| id | name | year | num  |
+----+------+------+------+
|  2 | a    |   18 |  400 |
|  4 | b    |   18 |  200 |
|  6 | c    |   18 |  100 |
+----+------+------+------+

现在我写了一个mysql程序:

create procedure show_data(in type char,myear int)
begin
if type = "all" then 
    SELECT * from tb where year=myear;
elseif type != "all" then
    SELECT * from tb where name=type and year=myear;
end if;
end //

show_data过程中的逻辑很清楚:当输入参数type全部为,而myear为18时,根据该过程,查询仅为SELECT * from tb where year=18

call show_data("all",18)我得到的如下:

call show_data("all",18)//
+----+------+------+------+
| id | name | year | num  |
+----+------+------+------+
|  2 | a    |   18 |  400 |
+----+------+------+------+
1 row in set (0.00 sec)

Query OK, 0 rows affected, 1 warning (0.00 sec)

show warnings//
+---------+------+-------------------------------------------+
| Level   | Code | Message                                   |
+---------+------+-------------------------------------------+
| Warning | 1265 | Data truncated for column 'type' at row 1 |
+---------+------+-------------------------------------------+
1 row in set (0.00 sec)
mysql procedure
1个回答
0
投票

您将变量type声明为char。这仅允许一个字符。因此,当您尝试分配一个包含三个字符('all')的字符串时遇到的错误。

考虑this example

delimiter //
create procedure debug_char(in type char, myear int)
begin
    select type;
end 
//

call debug_char('abc', 1);

收益率:

Error: ER_DATA_TOO_LONG: Data too long for column 'type' at row 1

您需要将数据类型更改为char(3),以便该值适合它(如果实际值大于3,则实际上您希望与name列中的最大字符长度相同)。

注意:可以通过将逻辑移至查询本身而不是使用if来简化代码,如下所示:

delimiter //
create procedure debug_char(in type char(3), myear int)
begin
    select * from tb where (name = type or type = 'all') and year = myear;
end
//
© www.soinside.com 2019 - 2024. All rights reserved.