Reputation: 351
I have a user-defined SQL function that returns 1 or 0 and I want to call it from a column CHECK constraint.
Upvotes: 4
Views: 6183
Reputation: 351
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;
Upvotes: 5