Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在postgresql中实现约束_Postgresql_Constraints - Fatal编程技术网

如何在postgresql中实现约束

如何在postgresql中实现约束,postgresql,constraints,Postgresql,Constraints,在明细表Product ID、收据ID中,只能添加库存大于0的产品。 仓库产品ID,库存。如何在Postgresql中实现此约束 -- CREATE THE FUNCTION CREATE FUNCTION trg_product_stock_check() RETURNS trigger AS $func$ BEGIN if exists (select * from warehouse w where w.product_id = new.product_id and stock &

在明细表Product ID、收据ID中,只能添加库存大于0的产品。 仓库产品ID,库存。如何在Postgresql中实现此约束

-- CREATE THE FUNCTION
CREATE FUNCTION trg_product_stock_check()
  RETURNS trigger AS
$func$
BEGIN
  if exists (select * from warehouse w where w.product_id = new.product_id and stock <= 0) then
    raise NOTICE 'Product must have a stock of greater than 0';
    return null;
  end if;
  return new;
END
$func$  LANGUAGE plpgsql;

-- CREATE THE TRIGGER
CREATE TRIGGER product_stock_check
BEFORE INSERT ON "orders"
FOR EACH ROW EXECUTE PROCEDURE trg_product_stock_check();
解决方案是创建一个触发器函数,该函数设置在订单表的insert上。首先创建你的函数。您希望在函数中检查仓库表中的产品库存量。如果产品的库存量小于或等于0,则返回null并显示日志消息。否则,返回新创建的行,例如:函数中的new关键字是要插入的行。创建函数后,可以在插入之前将触发器设置为在orders表上运行


您可以阅读有关创建触发器/函数和的更多信息。

因此,当将记录添加到明细表时,您希望检查仓库表中的可用库存,对吗?让我更好地解释一下,我有一个订单表和一个订单明细表。当我插入一个项目的细节,这必须有一个积极的数量,否则我不能输入详细信息。啊,我想你是在寻找一个触发器插入?是的,但我不知道写什么我是一个noob@antonio-更新了关于如何编写触发器的答案