سؤال

I need to retrieve a report of the affected rows when a table has been altered with the following commands:

1.- Changing the engine:

ALTER TABLE <table> ENGINE=INNODB;

2.- Adding constraints:

ALTER TABLE nombre_tabla ADD PRIMARY KEY símbolo_clave_foránea;
ALTER TABLE nombre_tabla DROP PRIMARY KEY símbolo_clave_foránea;

ALTER TABLE nombre_tabla ADD FOREIGN KEY símbolo_clave_foránea;
ALTER TABLE nombre_tabla DROP FOREIGN KEY símbolo_clave_foránea;

3.- Adding a UNIQUE constraint.

هل كانت مفيدة؟

المحلول

Primary or Unique Key failure is look for duplicates, if you have nulls in there you'll need to sort them first.

E.g given MyTable(KeyField int not null) then

Select KeyField From MyTable
inner join (Select KeyField,Count() as NumberOfTimes Group By KeyField) Duplicates
Where NumberOfTimes > 1

Then you'll have to come up with something to do with them. Delete or rekey.

Foreign Keys just a outer join query with where key is null

e.g Given MyTable (KeyField int not null, ForeignKeyField int not null) and MyLookUpTable(LookUpkey int not null, Description VarChar(32) not null) then

Select KeyField From MyTable 
Left Join MyLookUpTable On MyTable.LookUpField = MyLookUpTable.LookUpKey
Where MyTable.LookUpField Is Null

Again you'll have to decide what to do with them. You could delete them, but this might help. One way is to insert a "Missing" Record in the look Up Table, grab it's key, then do an update with join. So given that key is 999

Update m
Set LookUpField = 999
From MyTable m 
Left Join MyLookUpTable On m.LookUpField = MyLookUpTable.LookUpKey
Where m.LookUpField Is Null

Now you can dig out 999s and deal with them at your leisure.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top