I have two table called tbl_1 and tbl_2 with below schema
CREATE TABLE tbl_1(id int, disabled bit, qtype int)
and
CREATE TABLE tbl_2 (qtype int, qname nvarchar(MAX))
i want to add a constraint to the tbl_1 so that if (disabled=0 or disabled is null) qtype must be a number that exists in the tbl_2.qtype column?
I tried creating a function and added a check constraint
CREATE FUNCTION fn_Check_qtype(@qtype INT)
RETURNS int
AS
BEGIN
IF EXISTS(SELECT qtype from tbl_1 where (disabled=0 or disabled is null) and qtype=@qtype)
IF EXISTS (SELECT qtype FROM tbl_2 WHERE qtype is not null and qtype = @qtype)
return 1
return 0
END
Constraint
alter table tbl_1
add constraint ck_qtyppe
check (dbo.fn_Check_qtype(qtype) =1)
But even no non-matching records it is throwing error
The ALTER TABLE statement conflicted with the CHECK constraint "ck_qtyppe". The conflict occurred in database "TestDB", table "dbo.tbl_1", column 'qtype'.
But if i am deleting qtype null value from tbl_1 it is working no matter disabled=0, disabled=, disabled = null.