Sunday, April 12, 2015

SQL Server Brain Basher of the Week #007

Not a new one but still I do not get proper answers when a question is asked on this. See whether you can select accurate statement(s) before reading the rest. This is all about the "GO" keyword we used with TSQL.


What do you think? Let's go through one by one. GO is not a TSQL statement. It is a command only recognized by the sqlcmd and Management Studio. Based on this fact, 1st statement is false and 3rd statements is true. If you execute a TSQL code that contains GO keyword through C#.Net, you will get an error because engine cannot recognize the keyword.

GO is treated as the batch separator in Management Studio and SqlCmd tools. This makes the 2nd statement true. All your statements either start from the top or since last GO statement till next GO statement are considered as a batch and will be executed as a single batch. Objects like Variables cannot be shared among batches. Here is an example;

DECLARE @MyVariable int = 100;

-- This statement runs without any issue
SELECT @MyVariable;
GO -- Batch separator

-- This statement throws an error:
-- "Must declare the scalar variable "@MyVariable"."
SELECT @MyVariable;

Can we replace GO  with any other word? Yes, it is possible. This option is available with Options menu item that comes under Tools menu in Management Studio. Considering this, forth statement is true too.


No comments:

Post a Comment