唯一约束(与某个值的另一列相结合)

时间:2014-09-04 19:14:54

标签: sql-server sql-server-2008-r2

我继承了一个数据库设计,它有很多软删除标志。

在下面的代码中,我试图弄清楚是否存在一个约束,允许"一个非软删除的员工"的唯一EmployeeNumber。

在这个模拟示例中,可以重复使用EmployeeNumber,但一次只能删除1个EmployeeNumber。

我试图限制(在下面说明),但他们知道他们不会工作。

有什么想法吗?

在下面的例子中,只有' FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF'会失败。

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = N'dbo' and TABLE_NAME = N'Employee' and TABLE_TYPE = N'BASE TABLE' ) 
BEGIN 
DROP TABLE [dbo].[Employee] 
END 
GO



CREATE TABLE [dbo].[Employee] ( 

    [EmployeeUUID] [uniqueidentifier] NOT NULL,
    [EmployeeNumber] [varchar](10) NOT NULL,
    [LastName] [varchar](64) NOT NULL,
    [FirstName] [varchar](64) NOT NULL,
    [CreateDate] [datetime] NOT NULL DEFAULT CURRENT_TIMESTAMP,
    [HireDate] [datetime] NOT NULL, 
    IsSoftDeleted bit not null default 0
    )

GO

ALTER TABLE [dbo].[Employee] ADD CONSTRAINT PK_Employee PRIMARY KEY NONCLUSTERED (EmployeeUUID) 
GO

/* Does not work for fairly obvious reasons */
/*
ALTER TABLE [dbo].[Employee] ADD CONSTRAINT CK_EmployeeNumber_Unique UNIQUE (EmployeeNumber) 
*/
GO

/* Does not work because it only allows one IsSoftDeleted=1 rowo, not multiples */
/*
ALTER TABLE [dbo].[Employee] ADD CONSTRAINT CK_EmployeeNumber_Unique UNIQUE (EmployeeNumber, [IsSoftDeleted]) 
*/
GO



INSERT INTO [dbo].[Employee] ( [EmployeeUUID] , [EmployeeNumber] , [LastName] , [FirstName] , [HireDate] , [IsSoftDeleted] ) 
Select 'AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA' , '1111111111' , 'Jones' , 'Mary' , '01/01/2001' , 0

INSERT INTO [dbo].[Employee] ( [EmployeeUUID] , [EmployeeNumber] , [LastName] , [FirstName] , [HireDate] , [IsSoftDeleted] ) 
Select 'BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBBBBBB' , '1111111111' , 'Smith' , 'John' , '02/02/2002' , 1

INSERT INTO [dbo].[Employee] ( [EmployeeUUID] , [EmployeeNumber] , [LastName] , [FirstName] , [HireDate] , [IsSoftDeleted] ) 
Select 'CCCCCCCC-CCCC-CCCC-CCCC-CCCCCCCCCCCC' , '1111111111' , 'Apple' , 'Andy' , '03/03/2003' , 1

INSERT INTO [dbo].[Employee] ( [EmployeeUUID] , [EmployeeNumber] , [LastName] , [FirstName] , [HireDate] , [IsSoftDeleted] ) 
Select 'DDDDDDDD-DDDD-DDDD-DDDD-DDDDDDDDDDDD' , '1111111111' , 'Banana' , 'Ben' , '03/03/2003' , 1


/* This would be the only row that would fail to insert, because of the duplicate ([EmployeeNumber]='1111111111' and [IsSoftDeleted]='1') */
INSERT INTO [dbo].[Employee] ( [EmployeeUUID] , [EmployeeNumber] , [LastName] , [FirstName] , [HireDate] , [IsSoftDeleted] ) 
Select 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF' , '1111111111' , 'Banana' , 'Ben' , '03/03/2003' , 0



Select * from [dbo].[Employee]

1 个答案:

答案 0 :(得分:3)

您可以使用已过滤的唯一索引执行此操作。

create unique index UX_Employee_EmployeeNumber 
  on dbo.Employee(EmployeeNumber) 
  where IsSoftDeleted = 0