Can I call a user-defined function from a column CHECK constraint?

女生的网名这么多〃 提交于 2019-12-05 13:08:15

Yes. SQL Anywhere doesn't have a boolean data type so you have to code a predicate that yields TRUE, FALSE or UNKNOWN. In other words, if your function returns 1 or 0 for pass or fail, you have to code the constraint as CHECK ( f() = 1 ).

Note that TRUE and UNKNOWN both result in a "pass"; only a FALSE result causes the check to fail.

The following sample shows how to ALTER a table that already contains data, to add a column with such a CHECK constraint.

Breck

CREATE TABLE t (
   pkey INTEGER NOT NULL PRIMARY KEY );

INSERT t VALUES ( 1 );
COMMIT;

CREATE FUNCTION is_filled_in ( 
   IN @value VARCHAR ( 100 ) )
RETURNS TINYINT
BEGIN
   IF COALESCE ( @value, '' ) <> '' THEN
      RETURN 1;
   ELSE 
      RETURN 0;
   END IF;
END;

ALTER TABLE t ADD c VARCHAR ( 3 ) DEFAULT 'xxx'
   CHECK ( is_filled_in ( c ) = 1 );

-- Works ok...
INSERT t VALUES ( 2, 'yyy' );
COMMIT;

-- Throws SQLCODE -209 Invalid value for column 'c' in table 't'...
INSERT t VALUES ( 3, '' );
COMMIT;

SELECT * FROM t;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!