SQL Server 2012:在 CHECK 约束中调用用户定义的函数

SQL Server 2012: Invoke user defined function in CHECK constraint

我写了一个函数 returns int 仍然,我不能在 CHECK 约束中使用它,输出这个错误:

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

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

我也试过了

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

我看到有人写道不可能在 CHECK 约束中调用用户定义的函数,但是 here 写的是可能的:

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.

调用scalar function时需要使用schema name

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

如 Damien_The_Unbeliever 所述,在 check constraint 中使用 UDF 有一些缺点以获取更多信息 check here