Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Kristen
Test
22859 Posts |
Posted - 2004-06-15 : 12:47:11
|
I need to update a PK column that is referenced by a Foreign key.I can't use CASCADE on the FK definition (loads of FKs, circular reference warning etc.)I was assuming I could doBEGIN TRANSACTIONUPDATE MasterTable SET MyPKCol = 'NEW'WHERE MyPKCol = 'OLD'UPDATE ChildTable SET MyPKCol = 'NEW'WHERE MyPKCol = 'OLD'-- Check for errors & rollback if necessaryCOMMIT but I haven't got that cracked, am I on the right track or do I need to do something more clever?ThanksKristen |
|
|
X002548
Not Just a Number
15586 Posts |
Posted - 2004-06-15 : 13:00:58
|
| [code]USE NorthwindGOCREATE TABLE myTable99(Col1 int PRIMARY KEY, Col2 char(1))GOCREATE TABLE myTable00(Col1 int, Col2 int, Col3 char(1) , PRIMARY KEY(Col1,Col2),FOREIGN KEY(Col1) REFERENCES myTable99(Col1))GOINSERT INTO myTable99(Col1,Col2)SELECT 1,'A' UNION ALLSELECT 2,'B' UNION ALLSELECT 3,'C'GOINSERT INTO myTable00(Col1,Col2,Col3)SELECT 1,1,'A' UNION ALLSELECT 1,2,'B' UNION ALLSELECT 1,3,'C' UNION ALLSELECT 2,1,'A' UNION ALLSELECT 2,2,'B' UNION ALLSELECT 2,3,'C'GOSELECT * FROM myTable99 l JOIN myTable00 r ON l.Col1 = r.Col1GO-- Would fail-- UPDATE myTable99 SET Col1 = 4 WHERE Col1 = 1-- Need to doINSERT INTO myTable99(Col1,Col2)SELECT 4, 'A'INSERT INTO myTable00(Col1,Col2,Col3)SELECT 4, Col2, Col3 FROM myTable00 WHERE Col1 = 1DELETE FROM myTable00 WHERE Col1 = 1DELETE FROM myTable99 WHERE Col1 = 1GOSELECT * FROM myTable99 l JOIN myTable00 r ON l.Col1 = r.Col1GODROP TABLE myTable00DROP TABLE myTable99GO[/code]Brett8-) |
 |
|
|
Kristen
Test
22859 Posts |
Posted - 2004-06-15 : 17:48:05
|
| I was afraid that might be the case - so I've got to INSERT a dummy record in the "new" PK position, then UPDATE all the child records to point ot it, and then DELETE the old record having saved its column values so I can then UPDATE the new, dummy, record (there are a number of UNIQUE INDEXes on the table). What a load of hassle! pity that I can't just get everything "right" before doing a COMMIT!Thanks for pointing me on the right pathKristen |
 |
|
|
|
|
|
|
|