是否可以在postgres中使用声明的变量?

时间:2017-11-09 17:24:36

标签: postgresql

我试图根据另一个表中的一些ID在postgres中的表上创建一个检查约束。我知道你不能直接用支票中的选项来做,但是我认为可以将ids变成一个变量并在支票中使用它们,但这似乎也不起作用。这就是我所拥有的:

DO $$
DECLARE
  assigned uuid := (select "WorkOrderStatusCodeId" from "WorkOrdersV2"."WorkOrderStatusCodes" where "Code" = 'A');
  onHold uuid := (select "WorkOrderStatusCodeId" from "WorkOrdersV2"."WorkOrderStatusCodes" where "Code" = 'O');
BEGIN
  ALTER TABLE "WorkOrdersV2"."WorkOrders" ADD CHECK (("WorkOrderStatusCodeId" not in (assigned, onHold) and "DisplayOrder" is null) or ("WorkOrderStatusCodeId" in (assigned, onHold) and "DisplayOrder" is not null));
END $$;

它给了我一个错误:ERROR: column "assigned" does not exist

有没有办法使用检查约束来执行此操作,还是需要使用触发器?

1 个答案:

答案 0 :(得分:1)

您必须使用动态SQL:

execute 'ALTER TABLE "WorkOrdersV2"."WorkOrders" ADD CHECK (("WorkOrderStatusCodeId" not in (''' || assigned || ''',''' || onHold || ''') and "DisplayOrder" is null) or ("WorkOrderStatusCodeId" in (''' ||assigned || ''', ''' || onHold || ''') and "DisplayOrder" is not null));'