在Firebird DBMS中将四个表列限制为不同的值

时间:2014-01-19 21:15:17

标签: sql database validation firebird

我有一张包含4个唯一列的表

我试过这样的东西:

ALTER TABLE "FolderDsg" ADD CONSTRAINT CHK4_FOLDERDSG CHECK (ORDER2 = ORDER3) 
ALTER TABLE "FolderDsg" ADD CONSTRAINT CHK11_FOLDERDSG CHECK (ORDER1 not in (ORDER2)) 
ALTER TABLE "FolderDsg" ADD CONSTRAINT CHK13_FOLDERDSG CHECK (ORDER1 like (ORDER2)) 
/******************************************************************************/ 
/*                             Unique Constraints                             */ 
/******************************************************************************/ 
ALTER TABLE "FolderDsg" ADD CONSTRAINT UNQ1_FOLDERDSG UNIQUE (ORDER1) 
USING INDEX "_IDXORDER1" 

适用于每一列。但是,如何为所有4列创建唯一的?

+------+------+------+------+
|Order1|Order2|Order3|Order4| 
+------+------+------+------+
|1     |2     |3     |4     | = valid OK Check
+------+------+------+------+
|5     |5     |6     |7     | = not valid ( That works in the Database ) 
+------+------+------+------+
|8     |9     |10    |11    | = valid OK Check 
+------+------+------+------+
|12    |13    |9     |14    | = valid  ( That's the Problem ) I need a not valid 
+------+------+------+------+

3 个答案:

答案 0 :(得分:1)

你试过这个吗?

ALTER TABLE "FolderDsg" ADD CONSTRAINT CHECK (ORDER1 not in (ORDER2, ORDER3, ORDER4) and
                                              ORDER2 not in (ORDER3, ORDER4) and
                                              ORDER3 not in (ORDER4)
                                             );

编辑:

如果您还希望列中的值唯一,则可以添加四个唯一约束:

ALTER TABLE "FolderDsg" ADD CONSTRAINT UNIQUE (ORDER1);
ALTER TABLE "FolderDsg" ADD CONSTRAINT UNIQUE (ORDER2);
ALTER TABLE "FolderDsg" ADD CONSTRAINT UNIQUE (ORDER3);
ALTER TABLE "FolderDsg" ADD CONSTRAINT UNIQUE (ORDER4);

编辑II;

而且,如果你真的希望所有列中的所有值都不同,那么你有两个选择。第一种是使用before update / before insert触发器。第二个是更可取的:以标准化格式存储数据。

创建一个表,每个“FolderDsg”有一行,并且顺序为:

create table FolderDsgOrder (
    FolderDsgId int,
    OrderNum int,
    OrderValue int
    /* whatever else you want goes here */
);

现在您可以创建简单约束:

alter table FolderDsgOrder add constraint unique (OrderValue);

答案 1 :(得分:0)

我会创建一个包含所有值的单独表:

CREATE TABLE ALL_VALUES (
    VALUE int not null,
    PRIMARY KEY (VALUE)
);

现在,添加一个触发器来检查和更新它:

CREATE TRIGGER FOR "FolderDsg" AFTER INSERT AS
BEGIN
    -- insert all the values. If any of those already exists, 
    -- the primary key constraint will be violated, and you'll get the error
    INSERT INTO ALL_VALUES VALUES(NEW.ORDER1);
    INSERT INTO ALL_VALUES VALUES(NEW.ORDER2);
    INSERT INTO ALL_VALUES VALUES(NEW.ORDER3);
    INSERT INTO ALL_VALUES VALUES(NEW.ORDER4);
END

如果您有更新和删除,则需要其他触发器才能从ALL_VALUES表中删除内容。

如果值可以为NULL,则可以使用UNIQUE约束而不是PRIMARY KEY。

答案 2 :(得分:0)

我找到了一个接近“米兰巴布什科夫”暗示的解决方案 THX大家特别感谢米兰 看看

http://www.delphipraxis.net/178566-unique-bei-4-verschiedenen-feldern-2.html#post1245205