解决索引索引限制的一种方法是使用索引视图:
CREATE TABLE dbo.Table01 (
Column01 NVARCHAR(100)
);
GO
CREATE VIEW dbo.vw_Table01_Column01_LenOver5Unique
WITH SCHEMABINDING AS
SELECT Column01
FROM dbo.Table01
WHERE LEN(Column01) >= 5;
GO
CREATE UNIQUE CLUSTERED INDEX cdx
ON dbo.vw_Table01_Column01_LenOver5Unique(Column01);
GO
INSERT INTO dbo.Table01 VALUES('1'); --success
INSERT INTO dbo.Table01 VALUES('1'); --success
INSERT INTO dbo.Table01 VALUES('55555'); --success
INSERT INTO dbo.Table01 VALUES('55555'); --duplicate key error
GO
编辑:
如果索引中有两列,应该如何定义视图?CREATE UNIQUE INDEX UIX_01 ON Table01(column01,column02)WHERE LEN(column01)> = 5
通过向视图定义和索引添加其他键列,可以为复合键扩展索引视图方法。视图定义中应用了相同的过滤器,但是由复合键而不是单列值强制的限定行的唯一性:
CREATE TABLE dbo.Table01 (
Column01 NVARCHAR(100)
,Column02 NVARCHAR(100)
);
GO
CREATE VIEW dbo.vw_Table01_Column01_LenOver5Unique
WITH SCHEMABINDING AS
SELECT Column01, Column02
FROM dbo.Table01
WHERE LEN(Column01) >= 5;
GO
CREATE UNIQUE CLUSTERED INDEX cdx
ON dbo.vw_Table01_Column01_LenOver5Unique(Column01, Column02)
GO
INSERT INTO dbo.Table01 VALUES('1','A'); --success
INSERT INTO dbo.Table01 VALUES('1','A'); --success
INSERT INTO dbo.Table01 VALUES('55555','A'); --success
INSERT INTO dbo.Table01 VALUES('55555','B'); --success
INSERT INTO dbo.Table01 VALUES('55555','B'); --duplicate key error
GO