(以下 SQL 来自另一个帖子/用户,正在使用 SQL Server 中的 CHECK 约束模拟表级断言)
CREATE FUNCTION dbo.fnRedRows()
RETURNS INT
AS
BEGIN
DECLARE @Return INT
SELECT @Return=COUNT(*) FROM dbo.Red
RETURN @Return
END
GO
CREATE TABLE dbo.Red
(
id INT IDENTITY(1,1),
test VARCHAR(max),
CONSTRAINT CK_MaxRows CHECK (dbo.fnRedRows()<5)
)
GO
INSERT INTO dbo.Red (test) VALUES ('HI')
INSERT INTO dbo.Red (test) VALUES ('The')
INSERT INTO dbo.Red (test) VALUES ('first four')
INSERT INTO dbo.Red (test) VALUES ('will work')
INSERT INTO dbo.Red (test) VALUES ('This one will fail')
GO
DROP TABLE dbo.Red
GO
DROP FUNCTION dbo.fnRedRows
GO
CHECK 是否从时间 t=0 开始保持完整性,而无需发生插入或其他事件(与触发器不同)?