创建一个不违反唯一索引的行

Create a row which does not violate a unique index

我有一个 table,有 IdAccountIdPeriodIdComment。我有一个 (AccountId, PeriodId) 的唯一索引。我想创建这样一个不违反唯一索引的行。 AccountIdPeriodId 不能为空,它们是外键。

我唯一的想法是交叉加入 AccountPeriod table 以获得所有有效组合并丢弃已经存在的组合并从其余组合中选择一个?

这是一个好的方法还是有更好的方法?

更新 1:有些人想知道原因。我在一个程序中需要这个功能,它向当前 table 添加一个新行,并且只允许用户在它已经在数据库中之后修改该行。该程序现在使用默认构造函数创建一个包含 AccountId1PeriodId1 的新行,空注释。如果此组合可用,则在插入后用户可以更改它并提供有意义的评论(每个 (AccountId, PeriodId) 最多可以有一个评论。但如果组合不可用,则原始插入将失败。所以我的任务是给不用的程序一个组合,这样就可以安全插入了。

事实证明我最初的想法足够快。此查询 returns 一个未使用的 (AccountId, PeriodId).

select top 1 * 
from 
(
    select Account.Id as AccountId, [Period].Id as PeriodId
    from Account cross join [Period]

    except

    select AccountId, PeriodId
    from AccountPeriodFilename
) as T