Search code examples
sql-serversql-server-2012check-constraint

SQL Server 2012: Invoke user defined function in CHECK constraint


I've written a function that returns int Still, I can't use it in CHECK constraint, this error is output:

'myFunction' is not a recognized built-in function name.

create table MyTable(
attr varchar(100) CHECK(myFunction(attr)=1)
);

I also tried

create table MyTable(
attr varchar(100)
);
alter table MyTable
add constraint CheckAttr
CHECK(myFunction(attr)=1);

I saw people wrote that it is not possible to invoke user defined functions in CHECK constraint, but here it's written it is possible:

CHECK constraints User-defined functions that return scalar values can be invoked in CHECK constraints if the argument values passed to the function reference columns only in the table or constants. Each time the query processor checks the constraint, query processor calls the function with the argument values associated with the current row being checked. The owner of a table must also be the owner of the user-defined function invoked by a CHECK constraint on the table.

Solution

  • You need to use schema name when you are calling scalar function

    create table MyTable(
    attr varchar(100) CHECK(schema_name.myFunction(attr)=1)
    );
    

    As mentioned by Damien_The_Unbeliever there are drawbacks in using UDF in check constraint for more info check here