甲骨文;限制每列值的行数

时间:2013-12-24 20:21:04

标签: oracle triggers duplicates row

我有一个带有邮政编码列的表格(荷兰格式,但不要紧,)

CREATE TABLE  "TEST"
(
    "ID" NUMBER(10) NOT NULL ENABLE,
    "POSTALCODE" VARCHAR2(6) NOT NULL ENABLE,
    ....
    CONSTRAINT "TEST_PK" PRIMARY KEY ("ID") ENABLE
)

我正在尝试创建一个触发器来限制包含重复邮政编码的记录数量;只有两行可以同时包含相同的邮政编码。 我尝试了以下代码:

CREATE OR REPLACE TRIGGER TR_TEST_PC
    BEFORE UPDATE OR INSERT OF "POSTALCODE " ON "TEST"
    FOR EACH ROW
    WHEN ( OLD.POSTALCODE <> NEW.POSTALCODE )
DECLARE
   v_count NUMBER;
BEGIN
    SELECT COUNT(*)
    INTO v_count
    FROM TEST
    WHERE POSTALCODE = :NEW.POSTALCODE ;  
    IF (v_count > 2) THEN
        raise_application_error(-20000, 'Max. 2 rows with same postal code.');
    END IF;
END TR_TEST_PC;

但这会返回错误:

ORA-04091: table MYDB.TEST is mutating, trigger/function may not see it
ORA-06512: at "MYDB.TR_TEST_PC", line 4
ORA-04088: error during execution of trigger 'MYDB.TR_TEST_PC'

我理解这是因为你无法访问你正在变异的表。

如何制作一个触发器,确保不超过2条记录包含相同的邮政编码?

2 个答案:

答案 0 :(得分:1)

这可能会起作用而不是你的触发器:

CREATE MATERIALIZED VIEW mv_my
BUILD IMMEDIATE
REFRESH FAST ON COMMIT AS
SELECT POSTALCODE, COUNT(*) AS cnt FROM TEST GROUP BY POSTALCODE
/

ALTER TABLE mv_my ADD CHECK(cnt < 2)
/

让我知道。 欢呼声,

Sebas

答案 1 :(得分:1)

我最终使用了更新后的触发器:

CREATE OR REPLACE TRIGGER TR_TEST_PC
    AFTER UPDATE OR INSERT OF "POSTALCODE" ON "TEST"
DECLARE
    v_count NUMBER;
BEGIN
    SELECT MAX(COUNT(*))
    INTO v_count
    FROM TEST
    GROUP BY POSTALCODE;
    IF (v_count > 2) THEN
        raise_application_error(-20000, 'Max. 2 rows with same postal code.');
    END IF;
END TR_TEST_PC;