(The following SQL was from another post/user and is simulating a table-level assertion using CHECK constraint in SQL Server)
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
Does CHECK maintain the integrity from time t=0, without an insertion or other event having to occur (unlike triggers)?
Be very careful about using functions in check constraints, they don’t always work and they can often be a performance problem. Here are a couple of examples where this is severely broken:
https://web.archive.org/web/20171013131650/http://sqlblog.com/blogs/tibor_karaszi/archive/2009/12/17/be-careful-with-constraints-calling-udfs.aspx
https://web.archive.org/web/20180427092555/http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/06/25/scalar-udfs-wrapped-in-check-constraints-are-very-slow-and-may-fail-for-multirow-updates.aspx
Personally I would just use triggers for this. I’m not sure what you’re gaining by using a UDF and a check constraint, except that you can say “I didn’t use a trigger.” Also what kind of change would happen to suddenly violate your constraint that wouldn’t require some kind of event that would fire a trigger?