I have a database running in Microsoft Azure.
I want to run a script in it. The problem is that the script only works if the SQL commands are run one at a time. So several commands are executed at the same time. For example, SQL wants to update a column before the column is even created.
E.g. I want to make sure that the SQL command ADD is executed first before UPDATE is executed.
How can I make it so that all commands in the script are executed one after the other and not in parallel?
As an error I get
Failed to execute query. Error: Invalid column name 'table_1_id'
Here is my code:
BEGIN TRY
BEGIN TRANSACTION
ALTER TABLE table_1
ADD table_1_id BIGINT;
UPDATE table_1 SET table_1_id = table_1_id2;
ALTER TABLE table2
DROP CONSTRAINT constraint1;
ALTER TABLE table_1
DROP CONSTRAINT PK_1;
ALTER TABLE table_1
DROP COLUMN table_1_id2;
ALTER TABLE table_1
ADD table_1_id2 BIGINT IDENTITY PRIMARY KEY;
COMMIT TRAN -- Transaction Success!
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN --RollBack in case of Error
-- <EDIT>: From SQL2008 on, you must raise error messages as follows:
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
-- </EDIT>
END CATCH
2
Answers
Putting it in answer instead:
This allows the new column to be visible to the update.
You can use the same technique for other parts if they’re crashing
Testscript:
Here in below code I have changed update statement to run in dynamic sql and it is working fine.
Code
Result