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:

  1. you have use create procedure instead of create;
  2. your update syntax wrong. set goes before where clause.
  3. 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

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -