mysql - Mysql 存储函数嵌套查询(在 INSERT 查询中选择)
问题描述
表
create table category(id int primary key auto_increment, name varchar(30));
insert into category(name) values('Snacks'),('Soft Drink'),('Raw');
create table material(id int primary key auto_increment, name text, catID int references category(id), quantity float, unit text, price float, pur_date date);
create table mStock(name text, catID int, quantity int, unit text);
添加材质的存储函数
CREATE DEFINER=`root`@`localhost` FUNCTION `addMaterial`( nm text, cat text, qty int, un text, pr float) RETURNS int(11)
DETERMINISTIC
BEGIN
declare cnt int;
declare continue handler for 1062
BEGIN
return 0;
END;
insert into MATERIAL
( name, catID, quantity, unit, price, pur_date)
values ( nm, ( select id from CATEGORY where lower(name) = lower(cat) ) ,
qty, un, pr, curdate() );
select count(*) into cnt from mSTOCK where lower(name) = lower(nm);
if( cnt > 0 )
then
update mSTOCK set quantity = quantity + qty where lower(name) = lower(nm);
else
insert into mSTOCK values( nm, ( select id from CATEGORY where lower(name) = lower(nm) ), qty, un );
end if;
RETURN 1;
END
检查表中是否添加了条目
select * from material;
select * from mStock;
类别 ID 已添加到物料表中,但未添加到 mStock 表中。我也尝试过使用select into查询,但它不起作用。
解决方案
在其他情况下注意您的 where 子句:
where lower(name) = lower(nm)
将其替换为
where lower(name) = lower(cat)
推荐阅读
- python - Python绑定公共IP以在没有相同网络的情况下连接
- redis - 数据库选择来实现一个程序来检索实时会话中的前 10 个投票问题
- junit5 - 是否可以在同一个测试文件中混合 jqwik @Property 方法和 junit5 @Test 方法?
- passwords - 此处未经授权映射空白方块
- ruby - 找不到 Gem IO-Console
- sqlalchemy - SQLAlchemy 抛出完整性错误,“更新或删除表违反外键约束”
- python - excel宏的完整文件路径
- php - php codeigniter网站显示未连接到safari ios手机中的服务器
- c++ - C++ 中的字符串是否没有超出范围的异常/错误?
- python - 正则表达式:直到但不包括组或组