当year为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
为all,而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)
发布于 2019-10-17 10:02:56
您将变量type
声明为char
。这只允许单个字符。因此,当您尝试分配一个包含三个字符('all'
)的字符串时,会出现错误。
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
//
https://stackoverflow.com/questions/58429742
复制相似问题