What is SQL Code Snippet?
MS Visual Studio is one of the richest editors that has an advanced intellisense support. Many of the full stack MS developers always complaint about the lack of rich intellisense support in the MS SQL Server editor (i.e. SQL Server Management Studio, Query window). SQL code snippet is a feature that helps you to write quick code as it populates the basic structure of a Table (Create), Stored Procedure, Function, Index etc. with a template that can serve as starting point.
Apart from the predefined templates available by default you can create your own templates for re-usability purpose.
For me it’s like a productivity tool, start using it and you will experience increased productivity.
SQL Server 2012 / 2014.
P.S. – In earlier versions also some sort of code snippet features were there but SQL Server 2012/14 supports a rich and advance code snippet feature. This example is created using SQL Server 2014 Express edition.
Inserting Transact-SQL Snippets
There are three ways to launch Snippet Picker tool-tip in SSMS (SQL Server Management Studio) Query Editor. Point your cursor to the place in query editor where you want to insert the snippet.
- First way:
- Press Ctrl+K immediately followed by Ctrl+X. You will find something like this:
- Second way:
- SSMS > Edit menu> Intellisense > Insert Snippet
- Third way:
- Right Click the mouse then select Insert Snippet from the context menu.
Now once you choose anyone of the above ways and say for example you choose Stored Procedure > Create Procedure basic Template from the list you will instantly have the following snippet in your query window:
1. The first way is the smart and quick way.
2. To customize the auto-generated script for your use, once you get the code snippet (as in the above image) use Tab key to move from one replacement point to another. You can Shift+Tab to move to previous selection.
Insert Surround-with Transact-SQL snippets
This feature can be launched by any of the three ways described below. Go to the SSMS query editor:
- Press CTRL+K, followed by CTRL+S.
- Go to the Edit menu, point to IntelliSense, select the Surround With.
- Right-click in the Query window and from the context menu select Surround With command.
Once you choose any of the Begin / If / While from the above figure you’ll have the basic snippet for the selected keyword.
Tip: The quickest way to use Surround With is to press Ctrl+K followed by Ctrl+S and then start typing the name of the Snippet and press Tab or Enter key.
Add Transact-SQL Snippets
As said earlier in the beginning of the article, you can create and register your own code snippets. This is out of the scope of this article and I’ll soon plan another article for it. Please share your views in the comment section.