mysql concat并插入不工作

时间:2013-03-13 16:54:38

标签: mysql sql stored-procedures

我在存储过程中有一个代码,它将“PID-”添加到id号,因此如果id号为1,则结果为PID-1。但它不起作用。

以下是代码:

DROP PROCEDURE `inserproducts`//
CREATE DEFINER=`root`@`localhost` PROCEDURE `inserproducts`(pid int,pname varchar(50),pdesc varchar(50),psupp varchar(50),pdate date,pquant int)
begin
insert into products(productid,productname,proddescription,supplier,lastpurchasedate,quantityleft)
        values(select concat('PID',pid,pname),pdesc,psupp,pdate,pquant));

select pid=last_insert_id();
end

我如何加入插入和连接在一起?请帮帮我。

2 个答案:

答案 0 :(得分:3)

使用INSERT INTO...SELECT

insert into products(productname,proddescription,supplier,lastpurchasedate,quantityleft)
select concat('PID',pid,pname),pdesc,psupp,pdate,pquant

如果列productid列为AUTO_INCREMENT,则可以省略该列。{/ p>

我想知道为什么当select pid=last_insert_id();pid参数时需要执行IN

更新1

DROP PROCEDURE `inserproducts`;
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `inserproducts`
(
   pid int,
   pname varchar(50),
   pdesc varchar(50),
   psupp varchar(50),
   pdate date,
   pquant int
)
begin

    insert into products
          (productname,
           proddescription,
           supplier,
           lastpurchasedate,
           quantityleft)
    select concat('PID',pid,pname), pdesc, psupp, pdate, pquant;

    select last_insert_id();
end$$
DELIMITER ;

答案 1 :(得分:2)

只需跟进...如果您指定了值,则不需要选择 - 只需使用值即可获得轻微的性能提升:

DROP PROCEDURE `inserproducts`;
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `inserproducts`
(
    in pid int,
    in pname varchar(50),
    in pdesc varchar(50),
    in psupp varchar(50),
    in pdate date,
    in pquant int
)
begin
    insert into products
        (productname, proddescription, supplier, lastpurchasedate, quantityleft)
    values
        (concat('PID',pid,pname), pdesc, psupp, pdate, pquant );

    select last_insert_id();
end$$
DELIMITER ;

除非你真的需要来自另一张桌子的数据,否则我会单独选择...