Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Can I use GO inside a T-SQL transaction?

Author  Topic 

sql-lover
Yak Posting Veteran

99 Posts

Posted - 2012-09-10 : 11:44:36
Hi,

An easy one. I just want to confirm.

I know GO is a Microsoft stuff. But can I use it inside a transaction, assuming I'm running my T-SQL snippet from Management Studio?

I understand it should be avoided if it's being called from a programming language code, as GO is not pure SQL. But I am going to run the script via Management Studio.

Here's a pseudo code with what I'm saying

SET XACT_ABORT ON

Do something here
GO

Do extra stuff
GO

SET XACT_ABORT OFF


Or, will it create problems in case of a failure and a rollback is needed?

Thanks,

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2012-09-10 : 12:06:16
transactions can cross batches no problem.

And even across databases:

BEGIN TRAN

USE tempdb
GO

SELECT 'foo' AS [HAHA] INTO bar
Go

USE model
GO

SELECT 'woo' AS [HOHO] INTO sho
GO

SELECT * FROM tempdb.INFORMATION_SCHEMA.TABLES WHERE [TABLE_NAME] = 'bar'
SELECT * FROM model.INFORMATION_SCHEMA.TABLES WHERE [TABLE_NAME] = 'sho'
GO

ROLLBACK

SELECT * FROM tempdb.INFORMATION_SCHEMA.TABLES WHERE [TABLE_NAME] = 'bar'
SELECT * FROM model.INFORMATION_SCHEMA.TABLES WHERE [TABLE_NAME] = 'sho'


However, just because it *can* doesn't mean that you should.....



Transact Charlie
Msg 3903.. The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
http://nosqlsolution.blogspot.co.uk/
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-09-10 : 12:18:14
quote:
Originally posted by sql-lover

Hi,

An easy one. I just want to confirm.

I know GO is a Microsoft stuff. But can I use it inside a transaction, assuming I'm running my T-SQL snippet from Management Studio?

I understand it should be avoided if it's being called from a programming language code, as GO is not pure SQL. But I am going to run the script via Management Studio.

Here's a pseudo code with what I'm saying

SET XACT_ABORT ON

Do something here
GO

Do extra stuff
GO

SET XACT_ABORT OFF


Or, will it create problems in case of a failure and a rollback is needed?

Thanks,


GO is just a batch separator

so it just starts a new batch. no problem in wrapping transaction over multiple batches

see this too

http://visakhm.blogspot.com/2010/02/custom-batch-separator-in-t-sql.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -