Save Time Writing T-SQL With Templates and Code Snippets

t-sql

Time-savers are most important when you are busy – that seems obvious. The unfortunate irony is that when you are busy you cannot take the time to create them. The creation of time-savers drops to low priority the minute the rush is over. Well, today I am going to fight my natural laziness and create a T-SQL template and some code snippets to ease my work in the Management Studio.

Templates

Creating templates is so very easy we won’t spend too much time discussing them. You can right-click on the Templates folder in the Template Explorer and create a folder for your templates. If the Template Explorer is not visible, you can select it from the View menu or simply hit <ctrl><alt> T . I’ll create a template for a frequent JOIN written for the ContosoRetailDW database.

CreateNewTemplate

After the new folder is created, you can right-click on it and choose New Template. Be sure to choose a good descriptive name for each template you create.

EditTemplate

After the new template is named, DO NOT double-it on it. Double-clicking opens a new sql query window based on your template, which at the moment is still blank. You need to right-click the new template name and choose Edit. Double-check that the new window that appears has the new template name in the tab at the top. After that, you can enter the template for the query. I do not find the definition of query parameters feature useful for SELECT statements, so I simply leave out the column names.

When you are finished, click the save button, but no filename dialog will appear, since you have not created an SQL query. Now it would be appropriate to double-click the template, add the necessary column names and expressions. If you click Save, you will be prompted for a filename for your new query.

Snippets

Snippets are T-SQL fragments that you can insert into T-SQL code you are writing or, perhaps, wrap around a block of T-SQL code. Snippets take more time to create than do templates, and furthermore require a bit of extra knowledge. It is not surprising, then, that many SSMS users have not taken the time to create snippets.

We’ll choose an example similar to, but a bit more detailed than the example provided in the Microsoft Developer Network.

Snippet XML

Snippets are defined in XML files. If you have any XML experience at all, you know that XML demands complete adherence to the rules of structure and is absolutely unforgiving of typographical errors. This includes case sensitivity.

Let’s take a look at the most important XML elements in the snippet file.

<Header>

<Title>Extended Try-Catch Template</Title>

<Shortcut></Shortcut>

<Description>Example Snippet for Try-Catch</Description>

<Author>LearningTree.com</Author>

<SnippetTypes>

<SnippetType>SurroundsWith</SnippetType>

</SnippetTypes>

</Header>

The <Title> element determines what the user will see when they are looking for a suitable snippet in the Management Studio.

<Header>

<Title>Extended Try-Catch Template</Title>

<Shortcut></Shortcut>

<Description>Example Snippet for Try-Catch</Description>

<Author>LearningTree.com</Author>

<SnippetTypes>

<SnippetType>SurroundsWith</SnippetType>

</SnippetTypes>

</Header>

“Description” is the tooltip the user will see if they select this snippet in SSMS.

SurroundWithErrorTrappingTooltip

<SnippetTypes>

<SnippetType>SurroundsWith</SnippetType>

</SnippetTypes>

Is this snippet an Insert snippet or a Surrounds With snippet?

<Declarations>

<Literal>

<ID>MyTooltip01</ID>

<ToolTip>Additional error handling code goes here.</ToolTip>

<Default>MyTooltip01</Default>

</Literal>

</Declarations>

A very nice feature of snippets is that you can insert markers to tell the user where additional T-SQL is required. You will probably want to choose a better name than the insipid “Mytooltip01”, but whatever you choose the text within the TootTip element will be displayed in the SSMS query window if the user hovers over your marker text with the mouse.

ToolTipText

<Code Language=”SQL“>

You must declare the code type. The only permissible value other than SQL is XML. I am very disappointed that neither MDX nor DAX are supported.

<Code Language=”SQL”><![CDATA[

BEGIN TRY

$selected$ $end$

END TRY

BEGIN CATCH

DECLARE @ERROR INT = ERROR_NUMBER()

$MyTooltip01$

IF @ERROR = 0

BEGIN

END

ELSE IF @ERROR = 0

BEGIN

END

IF XACT_STATE() = -1 — existing transaction is not commitable

ROLLBACK

ELSE IF XACT_STATE() = 1 — some changes are able to be committed

— Be careful what you do here!

— obviously, these are T-SQL comments

END CATCH;

]]>

</Code>

The actual T-SQL is within a CDATA block, which is not parsed by the XML machinery. This is necessary so that the code does not have to worry about characters that would cause errors in XML, such as the “<” character.

<Code Language=”SQL”><![CDATA[

BEGIN TRY

$selected$ $end$

END TRY

BEGIN CATCH

DECLARE @ERROR INT = ERROR_NUMBER()

$MyTooltip01$

IF @ERROR = 0

BEGIN

END

ELSE IF @ERROR = 0

BEGIN

END

IF XACT_STATE() = -1 — existing transaction is not commitable

ROLLBACK

ELSE IF XACT_STATE() = 1 — some changes are able to be committed

— Be careful what you do here!

— obviously, these are T-SQL comments

END CATCH;

]]>

</Code>

$selected$ and $end$ mark the location where the original highlighted text in SSMS will appear after the snippet has “surrounded” it.

<Code Language=”SQL”><![CDATA[

BEGIN TRY

$selected$ $end$

END TRY

BEGIN CATCH

DECLARE @ERROR INT = ERROR_NUMBER()

$MyTooltip01$

IF @ERROR = 0

BEGIN

END

ELSE IF @ERROR = 0

BEGIN

END

IF XACT_STATE() = -1 — existing transaction is not commitable

ROLLBACK

ELSE IF XACT_STATE() = 1 — some changes are able to be committed

— Be careful what you do here!

— obviously, these are T-SQL comments

END CATCH;

]]>

</Code>

“MyTooltip01” is the literal that was declared previously to provide a tooltip for the user. Remember that XML is always case sensitive and this applies to literal names as well.

Installing Code Snippets

SSMS code snippet files can be installed wherever you like, but when the Management Studio is installed it creates empty folders in the user’s Documents directory. Whichever folder you choose for your snippet files, you must let the Management Studio know. This is done with the Code Snippets Manager accessed from the Tools menu of SSMS.

Code Snippets Manager

While technically you do not need to click the “Import” button in the Code Snippets Manager to bring in new snippet files, there is one good reason for doing so. If you move a snippet file into your folder and there is some problem, perhaps a simple typo, you will not get an error message. The snippets in that file will simply not appear in SSMS. If, however, you import the new file using the Code Snippets Manager, the snippet file will be checked and an error message will inform you the file is not valid. Unfortunately, the error message will be of little help tracking down the error, but at least you know there is a problem with the file.

The Snippet Example

The contents of the file ErrorTrappingEx.snippet are shown here in their entirety. If you would prefer to download the file, always a helpful option with XML files, you can find the file here.

<CodeSnippets xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>

<_locDefinition xmlns=”urn:locstudio”>

<_locDefault _loc=”locNone” />

<_locTag _loc=”locData”>Title</_locTag>

<_locTag _loc=”locData”>Description</_locTag>

<_locTag _loc=”locData”>Author</_locTag>

<_locTag _loc=”locData”>ToolTip</_locTag>

<_locTag _loc=”locData”>Default</_locTag>

</_locDefinition>

<CodeSnippet Format=”1.0.0″>

<Header>

<Title>Extended Try-Catch Template</Title>

<Shortcut></Shortcut>

<Description>Example Snippet for Try-Catch</Description>

<Author>LearningTree.com</Author>

<SnippetTypes>

<SnippetType>SurroundsWith</SnippetType>

</SnippetTypes>

</Header>

<Snippet>

<Declarations>

<Literal>

<ID>MyTooltip01</ID>

<ToolTip>Additional error handling code goes here.</ToolTip>

<Default>MyTooltip01</Default>

</Literal>

</Declarations>

<!– A comment here must be an XML comment, not a T-SQL comment

<Code Language=”SQL”><![CDATA[

BEGIN TRY

$selected$ $end$

END TRY

BEGIN CATCH

DECLARE @ERROR INT = ERROR_NUMBER()

$MyTooltip01$

IF @ERROR = 0

BEGIN

END

ELSE IF @ERROR = 0

BEGIN

END

IF XACT_STATE() = -1 — existing transaction is not commitable

ROLLBACK

ELSE IF XACT_STATE() = 1 — some changes are able to be committed

— Be careful what you do here!

— obviously, these are T-SQL comments

END CATCH;

]]>

</Code>

</Snippet>

</CodeSnippet>

</CodeSnippets>

Conclusion

The many details involved in creating SSMS code snippets causes many folks to postpone, or perhaps forget, the task of creating useful snippets. However, once you have successfully created your first snippet, the second, third and Nth snippet are easy and have a big payoff in saving time in future T-SQL coding tasks.

Check out Learning Tree’s T-SQL programming course to learn more about using SQL Server to the fullest.

Type to search blog.learningtree.com

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.