I agree with Michael McLoskey, to some extent.
The question in my opinion is: what is the technical cost of having multiple note tables?
In my opinion, it is preferable to consolidate the same functionality in one table. This makes reporting and other further development easier. Not to mention that the list of tables is smaller and easier to manage.
This is a balancing act, you need to try to predetermine the benefits and costs of doing something like that. My personal preference is the referential integrity of the database. The application of integrity management should, in my opinion, be limited to business logic. The database should ensure the constancy and reliability of the data ...
To answer your question ...
The option I would use is a check constraint using a user-defined function to check the values. This works in M $ SQL Server ...
CREATE TABLE Test_Table_1 (id INT IDENTITY(1,1), val INT) GO CREATE TABLE Test_Table_2 (id INT IDENTITY(1,1), val INT) GO CREATE TABLE Test_Table_3 (fk_id INT, table_name VARCHAR(64)) GO CREATE FUNCTION id_exists (@id INT, @table_name VARCHAR(64)) RETURNS INT AS BEGIN IF (@table_name = 'Test_Table_1') IF EXISTS(SELECT * FROM Test_Table_1 WHERE id = @id) RETURN 1 ELSE IF (@table_name = 'Test_Table_2') IF EXISTS(SELECT * FROM Test_Table_2 WHERE id = @id) RETURN 1 RETURN 0 END GO ALTER TABLE Test_Table_3 WITH CHECK ADD CONSTRAINT CK_Test_Table_3 CHECK ((dbo.id_exists(fk_id,table_name)=(1))) GO ALTER TABLE [dbo].[Test_Table_3] CHECK CONSTRAINT [CK_Test_Table_3] GO INSERT INTO Test_Table_1 SELECT 1 GO INSERT INTO Test_Table_1 SELECT 2 GO INSERT INTO Test_Table_1 SELECT 3 GO INSERT INTO Test_Table_2 SELECT 1 GO INSERT INTO Test_Table_2 SELECT 2 GO INSERT INTO Test_Table_3 SELECT 3, 'Test_Table_1' GO INSERT INTO Test_Table_3 SELECT 3, 'Test_Table_2' GO
In this example, the final insert statement will fail.
MatBailie
source share