Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server / SQL-Server-2012

Quick Safe SQL Snippet

0.00/5 (No votes)
9 Aug 2013CPOL 5.7K  
SQL 2012 Code Snippet for quick blank transaction

Introduction

This snippet creates a blank safe transaction in which to perform database CRUD operations.

SQL 2012 Managment Studio only :( 

Background  

I frequently find myself needing to update database table values in databases which shouldn't really be manipulated manually, but sometimes need to be.

Using the code 

Save this code in a file called "SafeSQLSnippet.snippet" (or whatever you want) in C:\Users\USERNAME\Documents\SQL Server Management Studio\Code Snippets\SQL\My Code Snippets.

XML
<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>SafeSQL Template</Title>
            <Author>Ken Ehrman</Author>
            <Description>Inserts a TRAN-TRY-CATCH.</Description>
            <Shortcut>SafeSQL</Shortcut>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Code Language="SQL">
                <![CDATA[
/* SAFE SQL */
BEGIN TRAN
BEGIN TRY
    /* PUT USEFUL STUFF HERE */
    
    /* WHEN YOU FEEL SAFE, CHANGE THIS TO COMMIT TRAN */
    ROLLBACK TRAN
END TRY
BEGIN CATCH        
    ROLLBACK TRAN
    PRINT 'AT LINE: ' + CAST(ERROR_LINE() AS varchar(10));
    PRINT ERROR_MESSAGE();
END CATCH 

]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

Points of Interest 

Should serve as a sort-of tutorial for creating other snippets.

History 

Got tired of writing this code over and over, or remembering were to copy/paste it from.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)