[英]SQL conditional constraint on multiple columns being unique
I would like to have a conditional constraint on my database: 我想在我的数据库上有一个条件约束:
You can see that my CreatedBy
column has a few entries missing due to legacy data problems. 您可以看到由于遗留数据问题,我的
CreatedBy
列中缺少一些条目。
My new code ensures the CreatedBy
is filled out. 我的新代码确保填写了
CreatedBy
。
Question: 题:
I would like to ensure that noone can enter duplicate entries into the db by adding a conditional constraint. 我想确保没有人可以通过添加条件约束将重复的条目输入到数据库中。 that defines that a row should be unique by
AnswerID
, PollID
and CreatedBy
... only if CreatedBy
is not empty 只有当
CreatedBy
不为空时才定义一行应该是AnswerID
, PollID
和CreatedBy
唯一的...
It might look like this: 它可能看起来像这样:
CONSTRAINT UNIQUE BY AnswerID, PollID, CreatedBy WHERE CreatedBy IS NOT NULL
Any ideas if it's possible? 任何想法,如果可能的话?
Sure, use a filtered index : 当然,使用过滤索引 :
CREATE UNIQUE NONCLUSTERED INDEX <indexName>
ON <tableName> (AnswerID, PollID, CreatedBy)
WHERE CreatedBy IS NOT NULL;
Or, since you said "not empty" then something like this should do: 或者,既然你说“不空”,那么这样的事情应该做:
CREATE UNIQUE NONCLUSTERED INDEX <indexName>
ON <tableName> (AnswerID, PollID, CreatedBy)
WHERE CreatedBy IS NOT NULL
AND CreatedBy <> N'';
If version is prior to 2008: 如果版本早于2008年:
CREATE VIEW dbo.vw_Tablename
WITH SCHEMABINDING AS
SELECT AnswerID, PollID, CreatedBy
FROM dbo.Tablename
WHERE CreatedBy IS NOT NULL;
GO
CREATE UNIQUE CLUSTERED INDEX UIX_vw_Tablename
ON dbo.vw_Tablename(AnswerID, PollID, CreatedBy)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.