Published on

December 3, 2023

Using Regular Expressions in SQL Server Management Studio (SSMS) 2017

SQL Server Management Studio (SSMS) 2017 introduced a new and improved Regular Expression (RegEx) syntax, making it easier to perform complex find and replace operations. In this article, we will explore how to use RegEx in SSMS 2017 to format queries, remove blank lines and comments, and add schema names to table objects.

1. Formatting Text

One common requirement is to format queries by placing the “FROM” and “WHERE” clauses on new lines. In SSMS 2017, you can achieve this easily using RegEx in the find and replace function.

For example, to place the “FROM” clause on a new line, you can use the following RegEx in the find box: \s+from\s+. In the replace box, enter \nfrom (note the trailing space). Click “Replace All” to see the formatted query.

You can also apply the same technique to place the “WHERE” clause on a new line by using the RegEx \s+where\s+ in the find box and \nwhere in the replace box.

2. Removing Multiple Blank Lines

If you have a script with multiple blank lines that you want to clean up, you can use RegEx to remove them. Simply use the RegEx [^\s*\n] in the find box and leave the replace box empty. Click “Replace All” to remove the blank lines.

3. Removing Comment Lines

To remove comment lines from a script, you can use the RegEx ^\s*--.* in the find box and leave the replace box empty. Click “Replace All” to remove the comment lines.

4. Adding Schema Names to Table Objects

If you have table objects without schema names and you want to add the default schema name (e.g., “dbo”) to them, you can use RegEx to accomplish this. For example, use the RegEx \s*(from|join)\s+([^\.\s]+)\s+? in the find box and $1 dbo.$2 in the replace box. Click “Replace All” to add the schema name to the table objects.

These are just a few examples of how you can use RegEx in SSMS 2017 to manipulate and format your queries. By understanding the key elements of RegEx, such as quantifiers, special characters, anchors, grouping constructs, and substitutions, you can perform powerful find and replace operations.

Remember, learning and mastering RegEx takes time and practice. With a little effort, you can become proficient in using RegEx to enhance your SQL Server scripting and query formatting skills.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.