GO keyword in SQL Server 2008

In this article I describe how to use GO keyword in SQL Server 2008
  • 2718

Introduction

There is so much confusion while using semicolon (;) or GO keyword. The semicolon (;) is a statement terminator i.e. it is used to terminate SQL statements while GO keyword is used as batch terminator. This means that in that batch everything is local to that particular batch. GO keyword only relates to SSMS. Semicolon (;) is used where CTE (Common Table Expression) is used.  Lets take a practical example for using GO keyword.

Example:

Create a table named Test:

create table Test (id int, name varchar(10))
insert into Test
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d' union all
select 5,'e'
select * from Test

Output:

TestTable-in-sql.jpg

 Using GO keyword

GO is a batch terminator. GO can be used when multiple SQL statements are used in Query Window. GO indicates the end of batch. Any declarations of Variables, Table Variables, etc do not go across GO statements.

Select two table. One of them does not exist. Type following code:

select * from def -- table does not exist
select * from Test

Output:

GO-keyword-in-sql.jpg

Now use GO keyword between two statements. Type following code:

select * from def
GO
select * from Test
GO

Output:

UseGoKeyword.jpg                                    


UseGoKeyword-in-sql.jpg


Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.