Hello everyone!
I have a script that when I run it in parts, it works perfectly, but if I compile it into one, it wont run, keep saying that the column that was added in the script before it doesnt exist. Here is how I am doing it:
USE myTable IF (NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'temp_act_bk') AND type in (N'U'))) BEGIN CREATE TABLE dbo.temp_act_bk ( id INTEGER IDENTITY NOT NULL, title NVARCHAR(100), project_id INTEGER, active BIT, jpa_version BIGINT CONSTRAINT pk_temp_act_bk PRIMARY KEY (ID)); CREATE TABLE dbo.temp_status_migration( id TINYINT NOT NULL, migrated BIT NOT NULL DEFAULT 0, CONSTRAINT pk_temp_status_migration PRIMARY KEY (ID)); INSERT INTO dbo.temp_act_bk ( title, project_id, active, jpa_version ) SELECT title, project_id, active, jpa_version FROM activities ALTER TABLE dbo.item ADD old_id INTEGER NULL -- Insert the data from backup table into the items INSERT INTO dbo.item ( project_id, code, shortname, type_id, description, quantity, quantity_unity_id, jpa_version, active, old_id ) SELECT project_id, title, title, 1, title, 0, 1, jpa_version, active, id FROM dbo.temp_act_bk -- Add column item_id to w_items ALTER TABLE dbo.w_items ADD item_id INTEGER NULL END USE myTable IF NOT EXISTS (SELECT NULL FROM temp_status_migration WHERE id = 0) BEGIN UPDATE dbo.w_items SET item_id = ( SELECT TOP 1 id FROM item WHERE old_id = activity_id ) ALTER TABLE dbo.w_items ADD CONSTRAINT FK_w_items_item FOREIGN KEY (item_id) REFERENCES dbo.item(id) INSERT INTO dbo.temp_status_migration (id,migrated) VALUES (0,1) END
This doesnt get along pretty well if runned in a single script, as I said, but if I run a block and then the other, it runs smoothly. I wouldn`t mind if I didnt have to compile it into a big script, but the big script is needed.
I also tried opening a transaction and commiting in the end, same result, it doesnt work, keep saying that item_id doesnt exists