预防B& A& S中的SQL条目B已经存在

时间:2016-12-15 23:51:54

标签: sql sql-server database

我有一个包含两行的表:public enum EventType { EventA, EventC { @Override public Map<String, Map<String, String>> execute(String eventMapHolder) { // same code which is there in execute method for EventA and EventC } }, EventB { @Override public Map<String, Map<String, String>> execute(String eventMapHolder) { // same code which is there in execute method of EventB } }; // other methods which are there already } AccountID。我需要防止两列中的重复。意思是,如果存在条目:

PartnerAccountID

我需要确保以下内容也不存在:

| AccountID | PartnerAccountID |
| 1         | 2                |

在约束中以任何方式做到这一点?

2 个答案:

答案 0 :(得分:4)

如果您可以在表达式上创建唯一索引,那就太好了:

create unique index unq_t_AccountID_PartnerAccountID
    on t((case when AccountID < PartnerAccountID then AccountId else PartnerAccountID end),
         (case when AccountID < PartnerAccountID then PartnerAccountIDelse AccountId end)
        );

但是,您可以通过将列创建为计算列然后创建索引来执行几乎相同的操作:

alter table t add minid as (case when AccountID < PartnerAccountID then AccountId else PartnerAccountID end);

alter table t add maxid as (case when AccountID < PartnerAccountID then PartnerAccountIDelse AccountId end);

create unique index unq_t_minid_maxid on t(minid, maxid);

答案 1 :(得分:0)

一种方法也可以是创建一个代替触发器,它只是忽略两列中的重复项;优点是如果信息已经存储(不是相反),则不需要中止事务。以下是尝试触发器的外观:

CREATE TRIGGER tr_t ON t
    INSTEAD OF INSERT
  AS
  BEGIN
   INSERT t
   SELECT AccountID, PartnerAccountID
   FROM inserted
   where not exists (select * from t2 where t2.AccountID = ParnterAccountID and t2.ParnterAccountId = AccountID);
  END