I have two tables: table A and table B. These two tables are linked with a primary key in A and a foreign key in B.
Table A:
CREATE TABLE [BIO].[table_A](
[table_A_id] [int] IDENTITY(1,1) NOT NULL,
[type_id] [nvarchar](2) NOT NULL
CONSTRAINT [PK_table_A] PRIMARY KEY CLUSTERED
(
[table_A_id] ASC
))
Table B:
CREATE TABLE [BIO].[table_B](
[table_B_id] [int] IDENTITY(1,1) NOT NULL,
[table_A_id] [int] NOT NULL,
[analysis_id] [tinyint] NOT NULL
CONSTRAINT [PK_table_B] PRIMARY KEY CLUSTERED
(
[table_B_id] ASC
))
ALTER TABLE [BIO].[table_B] WITH CHECK
ADD CONSTRAINT [FK_table_B_table_A] FOREIGN KEY([table_A_id])
REFERENCES [BIO].[table_A] ([table_A_id])
GO
ALTER TABLE [BIO].[table_B] CHECK CONSTRAINT [FK_table_B_table_A]
GO
Table B must contain only specific values according to the values in table A. For example, if I have BL in table A, I can only have 1 or 3 in table B; if I have ST in table A, I can only have 2 or 4 in table B.
I have setup a bridge table which defines these combinations: BL→1 or 3, ST→2 or 4.
Bridge table:
CREATE TABLE [QRY].[bridge_table](
[type_id] [nvarchar](2) NOT NULL,
[analysis_id] [tinyint] NOT NULL,
CONSTRAINT [PK_bridge_table] PRIMARY KEY CLUSTERED
(
[type_id] ASC,
[analysis_id] ASC
))
I am currently using one constraint per table to be sure that any insert or update is correct according to the combinations defined in the bridge table. These two constraints are based on UDFs.
Constraint on table B:
ALTER TABLE [BIO].[Table_B] WITH CHECK
ADD CONSTRAINT [CK_chkAnalysisType]
CHECK (([QRY].[TypeAnalysisMatch_table_B]([table_A_id])>(0)))
GO
UDF:
CREATE FUNCTION [QRY].[TypeAnalysisMatch_table_B] (@table_A_id int)
RETURNS int
AS
BEGIN
RETURN
(
SELECT
Count(BIO.table_A.table_A_id) AS cnt_rec
FROM
QRY.bridge_table
INNER JOIN BIO.table_A ON QRY.bridge_table.type_id = BIO.table_A.type_id
INNER JOIN BIO.table_B ON
QRY.bridge_table.analysis_id = BIO.table_B.analysis_id
AND BIO.table_A.table_A_id = BIO.table_B.table_A_id
WHERE
BIO.table_A.table_A_id = @table_A_id
)
END
It works well for the INSERT
but not consistently for the UPDATE
. Moreover, as I read that UDFs in constraints should be avoided, I am looking for a better solution.
What would be an efficient alternative to these constraints?