Click here to Skip to main content
15,885,876 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi. I have some trouble. I have some database done and it has some table done with many FK (without option of update cascade). So i have some excess data (for example state, that doesn't exists) and this excess data is related with other tables. So i need to change primary key for excess data for some default key (999). Which would be the best way to do it? Modify every constraint? Write 50 update sentences? Or?
Posted

1 solution

Solved. First i get sysinfo about FK. Like this:

SELECT     A.FOREIGN_KEY_NAME, B.TABLE_NAME, B.COLUMN_NAME, A.REFERENCED_TABLE, A.REFERENCED_COLUMN FROM  INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS B RIGHT OUTER JOIN (SELECT DISTINCT so.name AS FOREIGN_KEY_NAME, OBJECT_NAME(sf.rkeyid) AS REFERENCED_TABLE, sc2.name AS REFERENCED_COLUMN FROM sysobjects AS so INNER JOIN sysforeignkeys AS sf ON so.id = sf.constid INNER JOIN syscolumns AS sc1 ON sf.fkeyid = sc1.id INNER JOIN syscolumns AS sc2 ON sf.rkeyid = sc2.id WHERE (so.xtype = 'F') AND (OBJECT_NAME(sf.rkeyid) = 'ESTADO') AND (sc2.name = 'ESTADO')) AS A ON B.CONSTRAINT_NAME = A.FOREIGN_KEY_NAME


Then, for every row of my catalog i check if it's "good" or "bad", if it's bad, than i make foreach cycle:

C#
foreach (DataRow DR_fk in DT_state_relation.Rows)
 {
  cmd = new SqlCommand("UPDATE bts." + DR_fk["TABLE_NAME"] + " SET " + DR_fk["COLUMN_NAME"] + " = 99 WHERE " + DR_fk["COLUMN_NAME"] + " = " + DR["ESTADO"], con);
 cmd.ExecuteNonQuery();
 }
 cmd = new SqlCommand("DELETE FROM bts.ESTADO WHERE ESTADO = " + DR["ESTADO"]);
 cmd.ExecuteNonQuery();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900