CHECK Constraint with UDF
CHECK Constraint with UDF is a SQL statement in the Constraints category. CHECK constraints can call user-defined functions for complex validation logic beyond simple expressions. The syntax is CONSTRAINT name CHECK (dbo.function_name(column) = 1). It returns uDF-backed check constraint. A typical example: CREATE FUNCTION dbo.fn_ValidateEmail(@email VARCHAR(255)) RETURNS BIT AS BEGIN RETURN CASE WHEN @email LIKE '%@%.%' AND @email NOT LIKE '%@%@%' THEN 1 ELSE 0 END END; CREATE TABLE users ( id INT PRIMARY KEY, email VARCHAR(255), CONSTRAINT ck_valid_email CHECK (dbo.fn_ValidateEmail(email) = 1) ); -- INSERT with invalid email fails -- Note: UDF-based CHECK can impact performance on large tables A close relative is PRIMARY KEY, which a column or set of columns that uniquely identifies each row. Only one PK per table. Automatically creates a unique index. A close relative is FOREIGN KEY, which ensures referential integrity: values in this column must exist in the referenced parent table.