Domanda

I have table A and B which cannot be edited and both using composite primary keys (region_id, number).

I have N tables, so called Information, each has its own ID as primary key.

A(or B) <-> Info Tables are M:N relationship and I need such a table. So I designed a table CtoInfo (where C is either A or B) with these columns

CREATE TABLE CtoInfo (
region_id ..
c_number ..
c_type // either A or B

info_id 
info_type
.. //some other columns
)

first 3 columns identify A or B, other 2 columns, the info. (type says which table and id is the PK)

Now I want to make a Primary key on this table. But it looks like I need to include 5 columns in that PK constraint !?

È stato utile?

Soluzione

SQL Server allows up to 16 columns to be included in a constraint. So five columns is not a problem.

When working with natural keys, you often get into multi-column primary key constraints. A "link" table with 5 or 6 columns as the key is not uncommon in such a design.

Now, there are a few problems with your design. In general you want to keep the primary key as short as possible for performance reasons. A single integer surrogate key is often the better choice from a performance perspective.

You also are defining a foreign key relationship that you cannot enforce. This usually points to a problem in the database schema. You are linking to 2 different entities from the same column. That means that they represent something very similar and should probably live in the same table. Then you can provide additional tables that contain the information that is specific to one of them but not the other. sys.objects, sys.tables and sys.procedures give you an example of how that could work. (In this case sys.tables and sys.procedures are views that also include columns form sys.objects. In your case you would not need to repeat that information.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top