About Me

My photo
Mumbai, Maharastra, India
He has more than 7.6 years of experience in the software development. He has spent most of the times in web/desktop application development. He has sound knowledge in various database concepts. You can reach him at viki.keshari@gmail.com https://www.linkedin.com/in/vikrammahapatra/ https://twitter.com/VikramMahapatra http://www.facebook.com/viki.keshari

Search This Blog

Saturday, March 23, 2013

GO, is it a SQL command, a jump to pointer or what exactly?


Yesterday it happened one of my very good friend asked me, why it is necessary to write go statement in an arrangement like this

alter table tblPopulation
add street varchar(10) 
go
select country,state,street,population from tblPopulation

Let’s find out what the picture behind GO statement.

To understated this lets first execute the same statement without having GO in between the alter and select statement.

alter table tblPopulation
add street varchar(10)

select country,state,street,population from tblPopulation

Msg 207, Level 16, State 1, Line 4
Invalid column name 'street'.
Msg 207, Level 16, State 1, Line 4
Invalid column name 'population'.

From the error message it is clear that the new field which we are adding to the existing table tblPopulation has not been added yet and the SQL parser parse the select command, due to which it didn’t find the new coloum population and throws a error.

Where as if we add go in between select and alter statement, we will be able to execute the statement with all ease.  

alter table tblPopulation
add street varchar(10)
go
select country,state,street from tblPopulation

country state     street
----------------------------
India   Delhi     NULL
India   Delhi     NULL
India   Delhi     NULL
India   Karnataka NULL

(4 row(s) affected)

This shows, If you put a GO between the two statements, it'll work, because SSMS won't parse and verify the whole statement ahead of time - it will do the first part, and then only parse the second (after the GO).

LEARNING: They're not strictly required - they're just instructions for the SQL Server Management Studio to execute the statements up to this point now and then keep on going. GO is not a T-SQL keyword or anything - it's just an instruction that works in SSMS.

Conclusion: Sometimes, you need a GO - e.g. if you add a column to a table, and then want to select it again, you need to have a GO between the adding of the column, and the query of it.

Code it and live the moment to the utmost satisfaction


Post Reference: Vikram Aristocratic Elfin Share

No comments:

Post a Comment