2

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?

2
  • Please edit your question to include ddl+dml for some sample data. Also, include the UDF you are currently using. Jun 2, 2015 at 14:12
  • @ZoharPeled: Question edited with data definition. Thanks
    – Sylvain C.
    Jun 2, 2015 at 21:37

1 Answer 1

1

You are right, having UDF in CHECK constraints can be tricky and some UPDATE statements may bypass the check:

http://sqlblog.com/blogs/tibor_karaszi/archive/2009/12/17/be-careful-with-constraints-calling-udfs.aspx

MSSQL: Update statement avoiding the CHECK constraint

As you can see in that SO question the answer recommended to use trigger for the check. Writing a correct efficient trigger is also not an easy task.


I assume that your bridge_table contains this data:

type_id    analysis_id
BL         1
BL         3
ST         2
ST         4

I would set up these constraints using only foreign keys, without UDF. It would require some (minimal) duplication of the data, though. I assume that real table_A and table_B have more columns than this example.

1. In table_A include type_id in the primary key:

CREATE TABLE [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,
    [type_id] ASC
))

2. Add a column type_id to the table_B. Yes, the same column as you already have in table_A. This is that duplication of data that I mentioned above:

CREATE TABLE [table_B](
    [table_B_id] [int] IDENTITY(1,1) NOT NULL,
    [table_A_id] [int] NOT NULL,
    [type_id] [nvarchar](2) NOT NULL,
    [analysis_id] [tinyint] NOT NULL
CONSTRAINT [PK_table_B] PRIMARY KEY CLUSTERED 
(
    [table_B_id] ASC
))

3. Make foreign key that links table_B with table_A on two columns (table_A_id, type_id):

ALTER TABLE [table_B] WITH CHECK 
ADD CONSTRAINT [FK_table_B_table_A] FOREIGN KEY([table_A_id], [type_id])
REFERENCES [table_A] ([table_A_id], [type_id])

This constraint guarantees that type_id values that are duplicated in table_B will be consistent with original values from table_A.

4. Make foreign key that links table_B with bridge_table again on two columns (type_id, analysis_id):

ALTER TABLE [table_B] WITH CHECK 
ADD CONSTRAINT [FK_table_B_bridge_table] FOREIGN KEY([type_id], [analysis_id])
REFERENCES [bridge_table] ([type_id], [analysis_id])

5. Now you can test that everything works as intended.

Add few rows to table_A:

INSERT INTO [table_A] ([type_id]) 
VALUES ('BL'), ('BL'), ('ST'), ('ZZ');

table_A_id    type_id
1             BL
2             BL
3             ST
4             ZZ

Try to insert valid data into table_B:

INSERT INTO [dbo].[table_B] ([table_A_id],[type_id],[analysis_id])
VALUES (1,'BL',1)

INSERT INTO [dbo].[table_B] ([table_A_id],[type_id],[analysis_id])
VALUES (1,'BL',3)

INSERT INTO [dbo].[table_B] ([table_A_id],[type_id],[analysis_id])
VALUES (2,'BL',3)

INSERT INTO [dbo].[table_B] ([table_A_id],[type_id],[analysis_id])
VALUES (3,'ST',2)

INSERT INTO [dbo].[table_B] ([table_A_id],[type_id],[analysis_id])
VALUES (3,'ST',2)

table_B_id    table_A_id    type_id    analysis_id
1             1             BL         1
2             1             BL         3
3             2             BL         3
4             3             ST         2
5             3             ST         2

Try to insert invalid data:

INSERT INTO [dbo].[table_B] ([table_A_id],[type_id],[analysis_id])
VALUES (3,'ST',1)

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_table_B_bridge_table". 
The conflict occurred in database "tempdb", table "dbo.bridge_table".
The statement has been terminated.

Which means, that ST can't have analysis_id=1

INSERT INTO [dbo].[table_B] ([table_A_id],[type_id],[analysis_id])
VALUES (3,'BL',1)

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_table_B_table_A". 
The conflict occurred in database "tempdb", table "dbo.table_A".
The statement has been terminated.

Which means, that the row in table_A with table_A_id=3 doesn't have BL in type_id.

Foreign keys would keep checking data consistency for all UPDATE statements as well:

UPDATE [dbo].[table_B]
SET [type_id] = 'ST'
WHERE [table_B_id] = 1

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_table_B_table_A". 
The conflict occurred in database "tempdb", table "dbo.table_A".
The statement has been terminated.

UPDATE [dbo].[table_B]
SET [analysis_id] = 2
WHERE [table_B_id] = 1

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_table_B_bridge_table". 
The conflict occurred in database "tempdb", table "dbo.bridge_table".
The statement has been terminated.

But this one works:

UPDATE [dbo].[table_B]
SET [analysis_id] = 3
WHERE [table_B_id] = 1

(1 row(s) affected)
2
  • 2
    For (3) I'd possibly recommend "ON UPDATE CASCADE" so that updates in table A "just work". I might also recommend renaming table B and creating a view called B querying the old table that doesn't have the type_id column. Finally, an INSERT trigger on that view would ensure the correct value is inserted. The application continues to work with A and B and they look the same as before, and so the duplication is "hidden". Jun 3, 2015 at 5:56
  • @Vladimir Baranov Thanks, this is exactly what i was looking for. The duplication of data is not an issue in my case especially with a nvarachr(2). I had to adapt your code using an unique index instead of a multicolumn primary key at step 1, but it works beautifully.
    – Sylvain C.
    Jun 3, 2015 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.