在两个列组合MSSQL上创建约束

时间:2018-06-07 09:33:49

标签: sql sql-server stored-procedures sql-server-2005

我的桌子上有两个列名孩子,其数据如下所示。

|     Parent          |     Child        |
|---------------------|------------------|
|      100            |      101         |
|---------------------|------------------|

我还在这两列上添加了Unique Constraints,命令如下:

ALTER TABLE Example ADD CONSTRAINT UC_Example UNIQUE (parent,child);

现在,如果我尝试在父级中插入 100 ,在子级中尝试 101 ,则失败,这是正确的但我也想停止反向插入 示例:父级中的 101 和子级中的 100 也会失败

有没有办法使用sql或Procedure或任何预定义的sql命令

2 个答案:

答案 0 :(得分:3)

以下是一个带有函数约束的示例:

{{1}}

答案 1 :(得分:2)

我会使用计算列来完成此操作。这样,就不需要定义其他功能或触发器。

alter table example add min_id as (case when parentId < childId then parentId else childId end) persisted;

alter table example add max_id as (case when parentId < childId then childId else parentId end) persisted;

现在您可以创建一个唯一的索引/约束:

alter table example add constraint unq_parent_child
    unique (min_id, max_id);
相关问题