I am migrating data from a series of old data tables to new tables. In this process I came upon some issues.
I need to create a table, copy some data from old table to new one then drop old table. To achieve this, I need to write a script that does not show errors even if you run it on a migrated database, meaning even if the old tables are not there I should not see errors and simply skip the process.
Following is what I came up with up to now:
IF NOT EXISTS(SELECT * FROM sys.objects WHERE Object_ID = Object_ID('Old_Table'))
GOTO Migrated_Before
-- Drop OldTable Indexes, PK's and FK's;
-- CREATE newTable ....;
-- Add Indexes, PK's, Fk's;
-- INSERT INTO NewTable(someFields) FROM OldTable.Fields, OtherTable.Fields ...;
-- DROP OldTable;
Migrated_Before:
Here is the issue, Drop and Create need GO to commit changes before continue to next stage otherwise, next command will fail, however putting GO between GOTO and Label will make label undefined for GOTO.
How can I force each process to run before continue to next one without writing IF multiple times?
Solution: I leave the solution here as reference for others.
I added begin transaction before every statement that need to happen before proceeding to next statement, for example, create table or drop FK’s. and also replaced goto and label with begin end (my first solution)
Try using
begin transaction,commitinstead ofgo