HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

What is the current state (2022) of using UDFs in a CHECK constraint in SQL Server?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
thewhat2022sqlconstraintudfsstatecurrentusingserver

Problem

SQL Server allows the use of User-Defined Functions (UDFs) in CHECK constraints - which has a number of use-cases - which I won't get into - but I was recently faced with implementing a non-trivial business/domain constraint that validated data in one table based on non-unique, non-key data from another table - which means the constraint cannot be implemented using any of the built-in constraints (FOREIGN KEY, UNIQUE, or a normal row-value based CHECK constraint).

My immediate go-to was a TRIGGER, as Microsoft's own documentation states that TRIGGER objects are the intended way to implement non-trivial constraints:

DML triggers are most useful when the features supported by constraints cannot meet the functional needs of the application. [...] Unlike CHECK constraints, DML triggers can reference columns in other tables. For example, a trigger can use a SELECT from another table to compare to the inserted or updated data and to perform additional actions, such as modify the data or display a user-defined error message.

Hang a second: Microsoft wrote "Unlike CHECK constraints, DML triggers can reference columns in other tables" - but that's misleading! CHECK constraints can reference columns in other tables indirectly via a UDF.

...so methinks there's a bit of vague and outdated information out there - so let's do more research to see if CHECK constraints with a UDF is the right way to go or not...

...well, it seems that UDFs in CHECK constraints seem have a bad rep: with critical remarks concerning poor performance and their lack of formal correctness (a winning combination...), but I noticed that the articles and posts I read, including practically all of the Google search results concerning UDFs and CHECK constraints was just old...

-
The #1 Google search result for "sql server check constraint udf" is an article dating back to 2001 - which doesn't give any performance advice, but the fact this is still the top result shows there's

Solution

Partial answer. Requirements to inline scalar function specifically states it cannot be in a computed column or check constraint.

The UDF is not used in a computed column or a check constraint definition

Context

StackExchange Database Administrators Q#313310, answer score: 2

Revisions (0)

No revisions yet.