是否可以配置检查约束,以便在每次修改时都应用(检查)它?即,无论特定的检查字段是否实际被修改。
CREATE TABLE dbo.SomeTable (
Id INT IDENTITY(1, 1) NOT NULL
, Name NVARCHAR(50) NOT NULL
, Who NVARCHAR(128) NOT NULL
, CONSTRAINT PK_SomeTable PRIMARY KEY CLUSTERED (Id ASC)
)
GO
ALTER TABLE dbo.SomeTable ADD CONSTRAINT DF_dbo_SomeTable_Who DEFAULT (SUSER_SNAME()) FOR Who;
GO
ALTER TABLE dbo.SomeTable WITH CHECK ADD CONSTRAINT CHK_dbo_SomeTable_WhoEqualsUser CHECK (Who = SUSER_NAME());
GO
INSERT INTO dbo.SomeTable (Name) VALUES (N'SomeBody');
EXECUTE AS USER = N'NotMe';
GO
UPDATE dbo.SomeTable SET Name = N'SomebodyElse'; -- Want this update-attempt to throw an exception
-- But it doesn't throw here because the check constraint isn't checked
UPDATE dbo.SomeTable SET Name = N'SomebodyElse' -- Don't want this update-attempt to throw
, Who = N'NotMe' -- since Who = SUSER_NAME()
GO
REVERT