I want establish a one-to-one relationship between two columns (a program code and a test code) in the same table. I want all tests with the same test code to have the same program code.
My first thought was to use a UDF to find cases where the same test code corresponds to two different programs. I learned that this won't work because t-sql only checks UDFs in check constraints after
INSERTS
-- not afterUPDATES
why is t-sql allowing me to violate a check constraint that uses a UDP?My next thought was to move the logic from the UDF into the check constraint itself. But t-sql is saying that sub-queries are not allowed in the check constraint. This also means I can't use
EXISTS
syntax (which I think also uses a sub-query).ALTER TABLE [dbo].[mytable] WITH CHECK ADD CONSTRAINT [oneProgramPerTest] CHECK
( (select COUNT(*) from mydb.dbo.mytable u1 inner join mydb.dbo.mytable u2 on u1.testcode=u2.testcode and u1.progcode <> u2.progcode )=0 )
Unless there is some way to enforce this logic without (1) a udf or (2) a subquery then it seems like I need to create a "dummy" table of program codes and then enforce a one-to-one relationship between test codes from myTable and the dummy table. This seems really ugly so there has got to be a better way. Right?