sql - mysql if Syntax ERROR -
i'm trying create procedure on mysql, it's not hard, when using "if" things goes crazy, says there's error cant understand. here goes:
create sp_verify_date (in comp int,in prod int,in qt int) begin select count(cd_compra) @tes produto_compra cd_produto=prod , cd_compra=comp; if (@tes = 1) update produto_compra cd_produto=prod , cd_compra=comp set qt_produto = qt_produto + qt; else insert produto_compra values(comp,prod,qt); end if; end
many peterm !!! works !!!! lost 2 night's trying find error, , ideia better procedure used it, again !
there several problems code:
- you have use
create procedure
instead ofcreate
; - your
update
syntax wrong.set
goes beforewhere
clause. - you need change
delimiter
try
delimiter $$ create procedure sp_verify_date (in comp int, in prod int, in qt int) begin select count(cd_compra) @tes produto_compra cd_produto=prod , cd_compra=comp; if (@tes = 1) update produto_compra set qt_produto = qt_produto + qt cd_produto=prod , cd_compra=comp; else insert produto_compra values(comp,prod,qt); end if; end$$ delimiter ;
other code ok.
here sqlfiddle demo
now can boil down whole thing 1 insert statement if have or if define unique index on (cd_produto, cd_compra)
(and following logic of code should have such constraint) using insert ... on duplicate key update
syntax
create procedure sp_verify_date (in comp int, in prod int, in qt int) insert produto_compra (cd_produto, cd_compra, qt_produto) values(comp, prod, qt) on duplicate key update qt_produto = qt_produto + values(qt_produto);
since it's one-statement sp don't need use begin ... end
block , change delimiter.
obviously if need can opt-out stored procedure , use such insert statement on own.
here sqlfiddle demo
Comments
Post a Comment