Reputation: 103
We have a table 'XYZ' in which we are inserting data for different tables -
ID TableName RowID
1 Person 1
2 Company 1
3 Employee 5
If we want to maintain the referential integrity for column RowID, I think of only two options:
Base Table: In which we create the unique ID for every table row through column BaseID in all tables,and use Base Table Column BaseID in XYZ rather than RowID through that we maintain the referential integrity.
Allowing the same column to store FKs to multiple tables, This also not a very efficient way.
So please advise if you know the efficient way to maintain integrity.
Thanks for Help.
Upvotes: 0
Views: 73
Reputation: 11571
You have following method for this purpose:
1- Have one reference table for each table, and use view for have XYZ:
PersonRows Table
ID RowId
CompanyRows Table
ID RowId
EmployeeRows Table
ID RowId
Create View XYZ AS
Select 'Person' AS TableName, RowID From PersonRows
UNION ALL
Select 'Company' AS TableName, RowID From CompmayRows
UNION ALL
Select 'Employee' AS TableName, RowID From EmployeeRows
2- Use after trigger (Insert, Update, Delete) for each of Person, Company and Employee table in order to check integrity.
For Example:
Create Trigger tr_Person_Del ON Person
After Delete
AS Begin
Delete From XYZ Where TableName = 'Person' and RowID in (Select Person.Id From Deleted)
End
3- Use following table (In this method I suggest to use sparse column for PersonRowID, CompanyRowID and EmployeeRowId)
XYZ(ID, TableName, PersonRowId, CompanyRowId, EmployeeRowId)
Upvotes: 3
Reputation: 10191
This is very much a judgement call. As you say you have three options:
Use a single RowID column, however you can't enforce RI.
You can create a set of nullable columns PersonRowID, CompanyRowID, EmployeeRowID and so on. Each of these has an FK onto the appropriate table and is null if the entity is not a Person/Company/Employee.
Your other option is to create a base table and another table for each type. This in my opinion is overkill, for three child tables you end up with a Base table plus one for each entity!.
My suggestion would be to have:
ID TableName PersonRowID CompanyRowID EmployeeRowID
1 Person 1 null null
2 Company null 1 null
3 Employee null null 5
You would then have FKs from PersonRowID to the Person table, CompanyRowID to the Company table and EmployeeRowID to the Employee table.
I have to admit though - I question the reason for this table in the first place... perhaps you should think about whether this table is correct before progressing much further?
Upvotes: 1
Reputation: 13960
You don't need to mantain a table with table names, SQL Server already do that.
SELECT * FROM sys.tables
http://msdn.microsoft.com/es-es/library/ms187406.aspx
Upvotes: 0