Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - How to use GO inside of a BEGIN .. END block?

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?

like image 459
BlueRaja - Danny Pflughoeft Avatar asked Jun 16 '11 18:06

BlueRaja - Danny Pflughoeft


People also ask

Can you have a begin and end block within another begin and end block?

The statement block can be nested. It simply means that you can place a BEGIN... END statement within another BEGIN... END statement.

Do you need begin end SQL?

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.

Is it mandatory to enclose every SQL query with the semicolon at the end?

Problem. The semicolon (;) is used in SQL code as a statement terminator. For most SQL Server T-SQL statements it is not mandatory.

What does the go do in SQL?

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.


1 Answers

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;  
like image 95
Mina Jacob Avatar answered Oct 15 '22 20:10

Mina Jacob