In the Computer Programming world, a snippet is a piece of reusable source code that can be easily incorporated into larger sections of code. Similarly, in SQL Server, a T-SQL snippet is a template of code containing the basic structure of a T-SQL statement or block.

There are two types of T-SQL snippets: (i) Expansion, (ii) Surround-with.

Expansion T-SQL snippets, when used, are added in your code right after the cursor.

Surround-with snippets, when used, encapsulate the highlighted T-SQL code. An example of the Surround-with snippets is the IF statement or BEGIN…END etc.

 

Snippet Usage Options in SQL Server Management Studio

 

The below screenshot shows an example on how you can use a snippet in SQL Server Management Studio. After right clicking within the Query Window, in this example I selected “Insert Snippet” (you can also make use of the key combination Ctrl+K and Ctrl+X) and then selected the “Create Index Basic” snippet:

 

Example of using a snippet in SQL Server Management Studio

As you can see, the result was to get the template T-SQL code of a CREATE INDEX statement in the Query Window:

 

Using a snippet in SQL Server Management Studio

 

Now, the question everybody might have: How do I create a T-SQL snippet?

Well, you have two options towards creating a new T-SQL snippet:

  • You can either do this manually by following the instructions in this article, or:
  • You can use a Graphical User Interface tool for this purpose.

A recommended tool for easily creating T-SQL Snippets for SQL Server Management Tool 2012 or later, is SQLNetHub’s Snippets Generator (see below screenshot).

With Snippets Generator, you can create and modify T-SQL snippets, apply syntax highlighting and code formatting, as well as store your T-SQL snippets as templates.

Snippets Generator Screenshot

 

With the Snippet Templates library, you can use built-in templates for creating your own T-SQL snippets, but also store your snippets as templates in order to be able to create more complex snippets at any time in the future.

Snippets Generator Screenshot

 

Learn more about SQLNetHub’s Snippets Generator.