How are SQL queries executed in SQL Server Management Studio with GO and without a GO statement?

I have a simple request

CREATE TABLE #tempTable (id int) DROP TABLE #tempTable CREATE TABLE #tempTable (id int) DROP TABLE #tempTable 

From my understanding, in the second part, it should create #tempTable .

But it shows the following error

Msg 2714, Level 16, State 1, Line 4
There is already an object in the database with the name "#tempTable".

I searched for the reason and found that it was because of the GO statement between the two parts of the request. Therefore, the correct request

 CREATE TABLE #tempTable (id int) DROP TABLE #tempTable GO CREATE TABLE #tempTable (id int) DROP TABLE #tempTable 

I also found that GO simply tells SSMS to send SQL statements between each GO in separate batches sequentially.

My question is: how are SQL statements executed? Is it running sequentially?

If it is executed sequentially, then why is my first request causing an error?

+7
sql-server tsql ssms
source share
2 answers

The SQL Server documentation explains this pretty well.

In your particular case, the problem is compile-time errors and runtime errors.

How it works? Without GO separating statements, everything compiles at the same time. The problem is that the third statement is a CREATE TABLE statement, and the table already exists. All that happened is that the instructions are parsed and compiled.

With GO first two statements are compiled and executed. Voila! In the third expression, there is no table for CREATE .

+5
source share

The main reason for this error is that the parsing of the request is done before the request is executed.

This is because all code runs as one batch. And SQL Server has one task to analyze and execute.

This is why the GO command (not the operator) avoids this problem. It signals the end of the party.

Here is a good topic to read about it: Understanding how SQL Server executes a query

+2
source share

All Articles