MySQL存储函数嵌套查询(在INSERT查询中是SELECT)

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

表格

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;

enter image description here

select * from mStock;

enter image description here

类别ID已添加到物料表中,但未添加到mStock表中。我也尝试过使用select into查询,但它不起作用。

mysql stored-functions mysql-function
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.