SQL Server – GO command

GO is the command SQL Server, that inform server to send all T-SQL statements before GO to an instance SQL Server as one batch.

GO is set after one or several statements as one batch. In example below You see one batch with several statements.

create table person (
  id int primary key,
  name varchar(100) not null
);
insert into person(name) values('Muller');
insert into person(name) values('Davis');
select * from person;
GO

Result:

Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'id', table 'BazaTest.dbo.person'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Msg 515, Level 16, State 2, Line 2
Cannot insert the value NULL into column 'id', table 'BazaTest.dbo.person'; column does not allow nulls. INSERT fails.
The statement has been terminated.

(0 row(s) affected)

The insert statements had exception so SELECT statement don’t execute.  So If You correct insert statements, the select statements will be execute. Below is the correct batch:

insert into person(id,name) values(1,'Muller');
insert into person(id,name) values(2,'Davis');
select * from person;
GO

Result:
dd1

 

The statemnts don’t be write in the same line as GO command.

select * from person;  GO

Result:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'GO'.

In GO line You may only set comment line.

insert into person(id,name) values(5,'Burger');
select * from person;  
GO -- insert one person and select all records

Result:
dd2

 

 

Either the local variable must be define and execute in the same batch so You may not execute this variable after GO command.

DECLARE @a int = 12;
GO
SELECT @a;
GO

Result:

Msg 137, Level 15, State 2, Line 1
Must declare the scalar variable "@a".

The correct batch:

DECLARE @a int = 12;
SELECT @a;
GO

The multiple statements before GO will be compile and execute as one. After GO don’t use semicolon.

                                                                           GO [count]
After GO command may be either set positive integer. The statements before this command( in this single batch ) will be execute the specific number of times.

select top 2 * from person;  
GO 3

Result:
dd3

 

 

 

 

 

GO may be use to insert a lot of records into table for the test. It is example to set 10 rows into table contains only one column with identity primary key.

create table test_tab (
id int primary key identity,
);
GO
insert into test_tab DEFAULT VALUES;
GO 10
select * from test_tab

Result:
dd4