是否可以在informix db中创建条件唯一约束(我的当前版本是11.70)
我想做的例子(postgresql):
create table test (id int primary key, v varchar(25), a boolean);
create unique index test_index on test(v, a) where a = true;
insert into test values (1, 'l', true);
insert into test values (2, 'k', true);
insert into test values (3, 'l', false);
insert into test values (4, 'l', false);
insert into test values (5, 'l', true); -- Fails because of test_index
select * from test;
-- prints:
-- id v a
-- --------------
-- 1 l true
-- 2 k true
-- 3 l false
-- 4 l false
答案 0 :(得分:0)
根据我的理解,只有当v
为真时,您才希望a
具有唯一性。
虽然您无法创建唯一索引,但您可以通过 DML 操作创建触发器以实现此目标。
INSERT 操作的示例:
[infx1150@tardis ~]$ dbaccess test -
Database selected.
> CREATE TABLE test (
> id INT PRIMARY KEY,
> v VARCHAR(25),
> a BOOLEAN
> );
Table created.
> CREATE PROCEDURE sp_test(v_val VARCHAR(25), a_val BOOLEAN)
> DEFINE n INT;
> LET n = 0;
>
> IF a_val THEN
> SELECT COUNT(*) INTO n
> FROM test
> WHERE v = v_val
> AND a = 't';
>
> IF n > 1 THEN
> RAISE EXCEPTION -746, 0, "There is already one row with v = " || v_val || " and a true flag";
> END IF;
> END IF;
> END PROCEDURE;
Routine created.
> CREATE TRIGGER ti_test INSERT ON test
> REFERENCING new AS n
> FOR EACH ROW (EXECUTE PROCEDURE sp_test(n.v, n.a));
Trigger created.
> INSERT INTO test VALUES (1, 'l', 't');
1 row(s) inserted.
> INSERT INTO test VALUES (2, 'k', 't');
1 row(s) inserted.
> INSERT INTO test VALUES (3, 'l', 'f');
1 row(s) inserted.
> INSERT INTO test VALUES (4, 'l', 'f');
1 row(s) inserted.
> INSERT INTO test VALUES (5, 'l', 't');
746: There is already one row with v = l and a true flag
Error in line 1
Near character position 1
> SELECT * FROM test;
id v a
1 l t
2 k t
3 l f
4 l f
4 row(s) retrieved.
>
Database closed.
[infx1150@tardis ~]$
这可以在数据库中使用事务记录(缓冲,无缓冲和 ANSI ),但不能在非交易数据库。