Domanda

I have a table

documents
(
    year int not null, 
    number int not null, 
    document_types_id int not null, 
    ...
)

The primary key is year + number + document_types_id.

I think that a better primary key would be year + document_types_id + number. Is there a way to reorder this composition (not columns in table, PK and FK combination) without deleting and recreation of PK, because this PK is used as a FK in many other tables.

Thanks.

È stato utile?

Soluzione

Your foreign keys are referencing your primary key, so your foreign keys are 3-dimensional (year + number + document_types_id). If you are going to get rid of a dimension then even if you try to modify your primary key your constraints will tell you that you can't get rid of the given column, so you should handle your foreign keys first and then you can modify your primary key. Steps:

  1. Write all your foreign keys into a list to enable you to know which were the foreign keys before.

  2. Get rid of all the foreign keys referencing your primary key

  3. Modify/recreate your primary key

  4. Recreate your foreign keys according to the new version of your primary key.

Altri suggerimenti

You have to drop the primary key first to alter it later. Otherwise you get a message, that there can't be two primary keys on one table.

But that's no problem, just do

Alter Table myTable NOCHECK Constraint All

then alter your tables as you like, then do

Alter Table myTable CHECK Constraint ALL

and you're fine.

The equivalent in MySQL would be:

SET FOREIGN_KEY_CHECKS = 0;

and

SET FOREIGN_KEY_CHECKS = 1;

If dropping the FK on other tables is a problem, then you can create a non-clustered index with those columns in that order and provide hints (WITH INDEX(ALTER TABLE syntax leaves no scope for an ALTER CONSTRAINT statement.

No. In the relational model, there is no meaningful ordering to the attributes in a key. But in SQL, there is. The correspondence of columns of a foreign key, to the columns of the primary or unique key the FK references, is by ordinal position, not by name.

So the ordering of the columns in the key declaration is meaningful, and if that meaning/ordering is currently used effectively, then you cannot change it without breaking the current use.

Besides. That the theory attaches no meaning to the ordering of the key attributes/columns, is not without reason. What exactly do you think is "better" with your "re-ordered" key, compared to the existing one ?

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