I have a user-defined SQL function that returns 1 or 0 and I want to call it from a column CHECK constraint.
+3
A:
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;
Breck Carter
2009-05-04 12:30:53
And it took you only 1 min to find such a long answer to you own question??
Stefan Steinegger
2009-05-04 12:38:19
@Stefan: I had the answer ready, so "1 min" actually reflects how slow I am, not fast. AFAIK it's OK to post questions with answers, at least according to the FAQ.
Breck Carter
2009-05-04 13:59:24