How to create and manage T SQL code snippets

How to create and manage T SQL code snippets

How to create and manage T-SQL code snippets

SQLShack

SQL Server training Español

How to create and manage T-SQL code snippets

October 28, 2016 by Artemakis Artemiou

Introduction

Transact-SQL (T-SQL) snippets were first introduced in SQL Server 2012 Management Studio. T-SQL snippets are templates containing one or more T-SQL statements which you can easily use them when you develop T-SQL scripts. The main concept behind code snippets is code reuse. With code reuse you develop faster, easier and with less syntax errors. If you frequently use specific T-SQL statements, then you should consider creating snippets with these statements as they will help you a lot. There are two types of T-SQL snippets: (i) Expansion, and (ii) SurroundsWith. Expansion snippets are full T-SQL statements which can be added in your T-SQL scripts. SurroundsWith snippets is code which can surround other T-SQL statements. For example, you can have a snippet that has the “BEGIN…END” block, “IF” block, “WHILE” block, “TRY…CATCH” block, etc. Even though snippets were first introduced in SQL Server 2012 Management Studio, they existed in Visual Studio long before SQL Server 2012 so their benefits and usage are well known to the technical community.

Using T-SQL snippets in SSMS

Now let’s see a simple example on how we can use a built-in snippet in SQL Server Management Studio. If you right click in SQL Server Management Studio’s (SSMS) Query Window, then among other, you will be presented with the following two options: Insert Snippet… Surround With…
Figure 1: Right-Clicking in Query Window in SSMS (snippet options). If you select the “Insert Snippet…” action, you are presented with the available snippet categories from which you can use the snippet to use.
Figure 2: Inserting Expansion T-SQL Snippet in SSMS – Part 1. In this example I used the “Inline Table Function” snippet and here’s what I got in my query window:
Figure 3: Inserting Expansion T-SQL Snippet in SSMS – Part 2. If you select the “Surround With…” action, you are then presented with the below built-in snippets:
Figure 4: Available Built-In SurroundsWith Snippets in SSMS. So if you have a statement in your query window (i.e. “SELECT * FROM tbl1”) and select it, and then you use the SurroundWith snippet “If”, your T-SQL statement will be automatically surrounded by an IF block.
Figure 5: Inserting an ‘IF’ T-SQL Snippet in SSMS Query Window.

Creating custom T-SQL snippets – The manual way

When I first checked out T-SQL snippets in SQL Server Management Studio 2012, I was excited as it was a long-awaited feature. However, right after the excitement, I wondered how it could be possible to create my own snippets. I found out that this was not very straightforward as in order to create a custom T-SQL snippet for SSMS you need to write XML code. Below you can see the XML template for creating a T-SQL snippet.
Figure 6: The XML T-SQL Snippets Template for SSMS. As you can see, even it’s not difficult, each time you want to create or modify a custom T-SQL snippet, you will need to write or modify XML code. For example, consider that we want to create the corresponding T-SQL snippet for the below T-SQL script:
Listing 1: Sample T-SQL Script to Include in Snippet. If we were about to create the snippet manually, we would have to write the below XML code:
Listing 2: Creating the Snippet Using XML (based on Listing 1 query). Even though I enjoy writing code, because the purpose of snippets is to make our life easier, I would prefer an easier way as well to create and manage my custom T-SQL Snippets. For this reason, within the context of my initiative SQLArtBits, I have developed a free tool called “Snippets Generator” which can be used for this exact purpose.

Creating custom T-SQL snippets with Snippets Generator

Snippets Generator is a free, lightweight program which makes it easy for anyone to create a T-SQL snippet for SSMS 2012 or later.
Figure 7: Snippets Generator – Creating a New T-SQL Snippet. As you can see in the above screenshot, Snippets Generator provides a convenient GUI environment in which you just need to complete 5 simple fields: Title: The title of your custom T-SQL snippet. Description: Your custom T-SQL snippet’s description. Author: The snippet’s author name. Snippet Type: The snippet’s type, meaning whether is an “Expansion” or “SurroundsWith” snippet. Snippet T-SQL Code: As the name implies, in this textbox you write the T-SQL statement that you want to be included in the snippet. In order to further assist you in the process of creating a new T-SQL snippet, Snippets Generator provides different code formatting options as well as the below additional functionality: Open existing SQL files in order to generate snippets based on the SQL files’ contents. The ability to set a “Default Author” name in order not to have to manually enter it each time. A “Snippet Templates” library. This library contains built-in snippet templates which you can use them to create your own T-SQL snippets. The ability to save your T-SQL snippet as template and thus add it to the Snippet Templates library for future use. Below you can see a screenshot of the Snippet Templates library.
Figure 8: Snippets Generator – Snippet Templates Library. Now let’s create the snippet for the query of Listing 1 using Snippets Generator.
Figure 9: Creating a Snippet for Listing 1. If you compare the two methods for creating the snippet, I’m sure you will agree with me that using Snippets Generator is a much easier and faster method for creating the snippet. Now let’s import the snippet into SSMS in order to verify its correctness.
Figure 10: Importing the Snippet Created Using Snippets Generator – Part 1. We will import the snippet in the snippets category ‘My Code Snippets’:
Figure 11: Importing the Snippet Created Using Snippets Generator – Part 2. Now that the snippet was imported in SSMS, let’s use it in a Query Window:
Figure 12: Using the T-SQL Snippet.
Figure 13: Using the T-SQL Snippet and Running the Script.

Conclusion

Code reuse in SQL Server Management Studio with the use of T-SQL snippets is a handy way to be more productive with less effort. Snippets Generator is a free, lightweight program which makes it easy for anyone to create a T-SQL snippet. With Snippet Generator’s assistance, you can easily create snippets for your everyday T-SQL scripting needs, so that whenever you need to run certain queries, to just call them via the snippets functionality in SSMS. Therefore, with the use of snippets, you will no longer need to remember complex T-SQL queries, as you will just be able to use them via your custom T-SQL snippets.
Author Recent Posts Artemakis ArtemiouArtemakis Artemiou is a Senior SQL Server and Software Architect, Author, and a former Microsoft Data Platform MVP (2009-2018). He has over 15 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and TechHowTos.com. Artemakis is the creator of the well-known software tools Snippets Generator, DBA Security Advisor and In-Memory OLTP Simulator. Moreover, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Artemakis's official website can be found at aartemiou.com. You can follow Artemakis on Twitter

View all posts by Artemakis Artemiou Latest posts by Artemakis Artemiou (see all) Certificate Management in SQL Server 2019 - May 31, 2019 SQL Server consolidation – Hosting multiple databases on a single SQL Server instance - December 2, 2016 How to create and manage T-SQL code snippets - October 28, 2016

Related posts

SQL Code Snippets in Azure Data Studio SQL snippets in SQL Server Management Studio Manage SQL code formatting using SQL formatter options How to create and customize SQL Server Templates How to create a linked server to an Azure SQL database 26,819 Views

Follow us

Popular

SQL Convert Date functions and formats SQL Variables: Basics and usage SQL PARTITION BY Clause overview Different ways to SQL delete duplicate rows from a SQL Table How to UPDATE from a SELECT statement in SQL Server SQL Server functions for converting a String to a Date SELECT INTO TEMP TABLE statement in SQL Server SQL WHILE loop with simple examples How to backup and restore MySQL databases using the mysqldump command CASE statement in SQL Overview of SQL RANK functions Understanding the SQL MERGE statement INSERT INTO SELECT statement overview and examples SQL multiple joins for beginners with examples Understanding the SQL Decimal data type DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key SQL Not Equal Operator introduction and examples SQL CROSS JOIN with examples The Table Variable in SQL Server SQL Server table hints – WITH (NOLOCK) best practices

Trending

SQL Server Transaction Log Backup, Truncate and Shrink Operations Six different methods to copy tables between databases in SQL Server How to implement error handling in SQL Server Working with the SQL Server command line (sqlcmd) Methods to avoid the SQL divide by zero error Query optimization techniques in SQL Server: tips and tricks How to create and configure a linked server in SQL Server Management Studio SQL replace: How to replace ASCII special characters in SQL Server How to identify slow running queries in SQL Server SQL varchar data type deep dive How to implement array-like functionality in SQL Server All about locking in SQL Server SQL Server stored procedures for beginners Database table partitioning in SQL Server How to drop temp tables in SQL Server How to determine free space and file size for SQL Server databases Using PowerShell to split a string into an array KILL SPID command in SQL Server How to install SQL Server Express edition SQL Union overview, usage and examples

Solutions

Read a SQL Server transaction logSQL Server database auditing techniquesHow to recover SQL Server data from accidental UPDATE and DELETE operationsHow to quickly search for SQL database data and objectsSynchronize SQL Server databases in different remote sourcesRecover SQL data from a dropped table without backupsHow to restore specific table(s) from a SQL Server database backupRecover deleted SQL data from transaction logsHow to recover SQL Server data from accidental updates without backupsAutomatically compare and synchronize SQL Server dataOpen LDF file and view LDF file contentQuickly convert SQL code to language-specific client codeHow to recover a single table from a SQL Server database backupRecover data lost due to a TRUNCATE operation without backupsHow to recover SQL Server data from accidental DELETE, TRUNCATE and DROP operationsReverting your SQL Server database back to a specific point in timeHow to create SSIS package documentationMigrate a SQL Server database to a newer version of SQL ServerHow to restore a SQL Server database backup to an older version of SQL Server

Categories and tips

►Auditing and compliance (50) Auditing (40) Data classification (1) Data masking (9) Azure (295) Azure Data Studio (46) Backup and restore (108) ►Business Intelligence (482) Analysis Services (SSAS) (47) Biml (10) Data Mining (14) Data Quality Services (4) Data Tools (SSDT) (13) Data Warehouse (16) Excel (20) General (39) Integration Services (SSIS) (125) Master Data Services (6) OLAP cube (15) PowerBI (95) Reporting Services (SSRS) (67) Data science (21) ►Database design (233) Clustering (16) Common Table Expressions (CTE) (11) Concurrency (1) Constraints (8) Data types (11) FILESTREAM (22) General database design (104) Partitioning (13) Relationships and dependencies (12) Temporal tables (12) Views (16) ►Database development (418) Comparison (4) Continuous delivery (CD) (5) Continuous integration (CI) (11) Development (146) Functions (106) Hyper-V (1) Search (10) Source Control (15) SQL unit testing (23) Stored procedures (34) String Concatenation (2) Synonyms (1) Team Explorer (2) Testing (35) Visual Studio (14) DBAtools (35) DevOps (23) DevSecOps (2) Documentation (22) ETL (76) ►Features (213) Adaptive query processing (11) Bulk insert (16) Database mail (10) DBCC (7) Experimentation Assistant (DEA) (3) High Availability (36) Query store (10) Replication (40) Transaction log (59) Transparent Data Encryption (TDE) (21) Importing, exporting (51) Installation, setup and configuration (121) Jobs (42) ▼Languages and coding (686) Cursors (9) DDL (9) DML (6) JSON (17) PowerShell (77) Python (37) R (16) SQL commands (196) SQLCMD (7) String functions (21) T-SQL (275) XML (15) Lists (12) Machine learning (37) Maintenance (99) Migration (50) Miscellaneous (1) ►Performance tuning (869) Alerting (8) Always On Availability Groups (82) Buffer Pool Extension (BPE) (9) Columnstore index (9) Deadlocks (16) Execution plans (125) In-Memory OLTP (22) Indexes (79) Latches (5) Locking (10) Monitoring (100) Performance (196) Performance counters (28) Performance Testing (9) Query analysis (121) Reports (20) SSAS monitoring (3) SSIS monitoring (10) SSRS monitoring (4) Wait types (11) ►Professional development (68) Professional development (27) Project management (9) SQL interview questions (32) Recovery (33) Security (84) Server management (24) SQL Azure (271) SQL Server Management Studio (SSMS) (90) SQL Server on Linux (21) ►SQL Server versions (177) SQL Server 2012 (6) SQL Server 2016 (63) SQL Server 2017 (49) SQL Server 2019 (57) SQL Server 2022 (2) ►Technologies (334) AWS (45) AWS RDS (56) Azure Cosmos DB (28) Containers (12) Docker (9) Graph database (13) Kerberos (2) Kubernetes (1) Linux (44) LocalDB (2) MySQL (49) Oracle (10) PolyBase (10) PostgreSQL (36) SharePoint (4) Ubuntu (13) Uncategorized (4) Utilities (21) Helpers and best practices BI performance counters SQL code smells rules SQL Server wait types © 2022 Quest Software Inc. ALL RIGHTS RESERVED. GDPR Terms of Use Privacy
Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!