Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Proper Error Handling in Transaction when including DDL

$
0
0

Hi All,

When creating a new table in SQL Server 2008 R2, I receive the following DDL (edited for readability):

IF OBJECT_ID('dbo.TestA', 'U') IS NULL
    DROP TABLE [dbo].[TestA]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TestA]
    (
    [PKID] [varchar](50) NOT NULL,
    [Description] [varchar](100) NULL,
    [Inactive] [bit] NULL,
    CONSTRAINT [DF_TestA_PKID] PRIMARY KEY CLUSTERED ([PKID] ASC)
    WITH
        (
        PAD_INDEX = OFF,
        STATISTICS_NORECOMPUTE = OFF,
        IGNORE_DUP_KEY = OFF,
        ALLOW_ROW_LOCKS = ON,
        ALLOW_PAGE_LOCKS = ON
        )
    ON [PRIMARY]
    )
ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[TestA] ADD CONSTRAINT [DF_TestA_Inactive] DEFAULT ((0)) FOR [Inactive]
GO

Now assume that I'm creating three different tables, all within the same script.  I want the script to run the DDL inside a transaction, so that if anything fails, it all rolls back.  I'm aware of the traditional method of encapsulating statements inside a transaction, and use that method for DML scripts.  (Begin the transaction, execute statement, check @@ERROR, if not equal to 0, GOTO TRAN_ERROR).  The problem is this all falls apart when the statements above are separated into batches using GO.  I understand that using named transactions in SSMS will get you around the GO statement but it still causes issues with the GOTO error, namely:

A GOTO statement references the label TRAN_ERROR but the label has not been declared.

So I guess my question is this: when issuing DDL statements, complete with error checking after each one, is it necessary to use GO after each statement?  If I can get rid of these I'm assuming my script will function as desired.

All responses are greatly appreciated!

Best Regards

Brad


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>