简体   繁体   中英

How to compare two values in different tables with a TRIGGER SQL?

CREATE TRIGGER Comparer_Prix 
BEFORE UPDATE ON ARTICLE 
FOR EACH ROW BEGIN 
SELECT ARTICLE.PRIXVENTE, ARTICLE.N_PRODUIT, ARTICLE.N_FABRICANT, LIEN_FABRICANT_PRODUIT.PRIXFABRICANT, LIEN_FABRICANT_PRODUIT.N_PRODUIT, LIEN_FABRICANT_PRODUIT.N_FABRICANT 
FROM ARTICLE, LIEN_FABRICANT_PRODUIT 
WHERE ARTICLE.N_FABRICANT=LIEN_FABRICANT_PRODUIT.N_FABRICANT AND ARTICLE.N_PRODUIT=LIEN_FABRICANT_PRODUIT.N_PRODUIT; 
IF (NEW.PRIXVENTE< PRIXFABRICANT) THEN RAISE_APPLICATION_ERROR(-20001, 'Refusé'); 
END IF; 
END;

I am trying to create a trigger that codes the following rule: the sales price must always be higher than the manufacturing price.

Here the errors I get:

Error(2,3): PL/SQL: SQL Statement ignored
Error(2,69): PL/SQL: ORA-00904: "LIEN_FABRICANT_PRODUIT"."PRIXFABRICANT": invalid identifier
Error(2.92): PLS-00302: The component "PRIXFABRICANT" must be declared.
Error(5,3): PL/SQL: Statement ignored
Error(5,10): PLS-00201: the identifier 'NEW.PRIXVENTE' must be declared.

It is not new , but :new (you're missing a colon).

Though, that's not the only issue here; you can't select from a table which is just being modified; mutating table error is expected. Lucky you, you don't have to select from article as you can reference its values using the same :new value.

ORA-00904 means that you've used a column name which doesn't exist in that table. As you didn't post tables' descriptions, I'm simply repeating what you wrote. Fix it yourself.

Something like this:

create or replace trigger comparer_prix
  before update on article
  for each row
declare
  l_prixfabricant   lien_fabricant_produit.prixfabricant%type;
begin
  select prixfabricant
    into l_prixfabricant
    from lien_fabricant_produit
    where n_fabricatn = :new.n_fabricant
      and n_produit   = :new.n_produit;

  if :new.prixvente < l_prixfabricant then
     raise_application_error(-20001, 'Refusé');
  end if;
end;
/

Also, it wouldn't harm if you learnt how to properly format code and make it easier to read. Use table aliases (instead of those lengthy table names).

If You compare two tables use: ... WHERE... AND EXISTS(SELECT * FROM <TAB_COMPARE>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM