I am generating a script for automatically migrating changes from multiple development databases to staging/production. Basically, it takes a bunch of change-scripts, and merges them into a single script, wrapping each script in a IF whatever BEGIN ... END
statement.
However, some of the scripts require a GO
statement so that, for instance, the SQL parser knows about a new column after it's created.
ALTER TABLE dbo.EMPLOYEE ADD COLUMN EMP_IS_ADMIN BIT NOT NULL GO -- Necessary, or next line will generate "Unknown column: EMP_IS_ADMIN" UPDATE dbo.EMPLOYEE SET EMP_IS_ADMIN = whatever
However, once I wrap that in an IF
block:
IF whatever BEGIN ALTER TABLE dbo.EMPLOYEE ADD COLUMN EMP_IS_ADMIN BIT NOT NULL GO UPDATE dbo.EMPLOYEE SET EMP_IS_ADMIN = whatever END
It fails because I am sending a BEGIN
with no matching END
. However, if I remove the GO
it complains again about an unknown column.
Is there any way to create and update the same column within a single IF
block?
The statement block can be nested. It simply means that you can place a BEGIN... END statement within another BEGIN... END statement.
BEGIN and END keywords are not required in Transact-SQL. BEGIN and END are used in Transact-SQL to group a set of statements into a single compound statement, so that control statements such as IF … ELSE, which affect the performance of only a single SQL statement, can affect the performance of the whole group.
Problem. The semicolon (;) is used in SQL code as a statement terminator. For most SQL Server T-SQL statements it is not mandatory.
GO is not a SQL keyword. It's a batch separator used by the SQL Server Management Studio code editor tool for when more than one SQL Statement is entered in the Query window. Then Go separates the SQL statements. We can say that Go is used as a separator between transact SQL Statements.
I had the same problem and finally managed to solve it using SET NOEXEC.
IF not whatever BEGIN SET NOEXEC ON; END ALTER TABLE dbo.EMPLOYEE ADD COLUMN EMP_IS_ADMIN BIT NOT NULL GO UPDATE dbo.EMPLOYEE SET EMP_IS_ADMIN = whatever SET NOEXEC OFF;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With