Mysql 存储函数嵌套查询(SELECT inside INSERT 查询)
Mysql Stored Function Nested Query (SELECT inside INSERT Query)
Tables
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);
要添加的存储函数Material
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
正在检查条目是否添加到table
select * from material;
select * from mStock;
类别 ID 添加到 Material Table,但未添加到 mStock Table。我也试过使用 select 进入 查询,但它不起作用。
注意 else 中的 where 子句:
where lower(name) = lower(nm)
将其替换为
where lower(name) = lower(cat)
Tables
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);
要添加的存储函数Material
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
正在检查条目是否添加到table
select * from material;
select * from mStock;
类别 ID 添加到 Material Table,但未添加到 mStock Table。我也试过使用 select 进入 查询,但它不起作用。
注意 else 中的 where 子句:
where lower(name) = lower(nm)
将其替换为
where lower(name) = lower(cat)