我试图弄清楚如何制作一个我以前从未做过的触发约束。我正在使用Java和Postgresql。
我需要两件事:
一个唯一的约束,它可以防止任何重复[type_of_charge + time_of_use + meter_register_code + period_of_availability] - 这已经通过标准的唯一约束来完成。
如果已存在相同meter_register_code + period_of_availability的行,则触发器约束需要阻止插入任何“anytime”行。
如果已存在“anytime”值,则触发器约束需要停止插入任何行。例如如果已经存在任何时间值,则无法插入非峰值,但如果存在“峰值”值则可以插入。
答案 0 :(得分:1)
我似乎已经解决了以下问题:
CREATE OR REPLACE FUNCTION validate_network_pricing_code() returns trigger as $$
DECLARE
tester int;
BEGIN
IF NEW.time_of_use = 'ANYTIME'
THEN tester := (SELECT COUNT(*) FROM network_pricing_category_code WHERE (
network_pricing_category_code.meter_register_code = NEW.meter_register_code AND
network_pricing_category_code.period_of_availability = NEW.period_of_availability AND
network_pricing_category_code.network_pricing_category_id = NEW.network_pricing_category_id AND
network_pricing_category_code.id != NEW.id
));
END IF;
IF NEW.time_of_use IS NOT NULL AND NEW.time_of_use != 'ANYTIME'
THEN tester := (SELECT COUNT(*) FROM network_pricing_category_code WHERE (
network_pricing_category_code.time_of_use = 'ANYTIME' AND
network_pricing_category_code.meter_register_code = NEW.meter_register_code AND
network_pricing_category_code.period_of_availability = NEW.period_of_availability AND
network_pricing_category_code.network_pricing_category_id = NEW.network_pricing_category_id AND
network_pricing_category_code.id != NEW.id
));
END IF;
IF (tester != 0) THEN
RAISE EXCEPTION 'ANYTIME rates cannot be combined with other types of rates - PEAK, SHOULDER, OFF-PEAK etc ';
END IF;
RETURN NEW;
END;
$$ language plpgsql;
CREATE TRIGGER validate_network_pricing_code_trigger BEFORE INSERT OR UPDATE ON network_pricing_category_code
FOR EACH ROW EXECUTE PROCEDURE validate_network_pricing_code();
通过修改我在此处找到的写入:When Validation Is Not Enough: PostgreSQL Triggers for Data Integrity