Published on

August 20, 2015

Exploring Regular Expressions in SQL Server

Regular expressions are a powerful tool that can greatly enhance your SQL Server querying and data manipulation capabilities. Whether you’re a seasoned SQL Server professional or just starting out, understanding regular expressions can be a game-changer in your day-to-day tasks.

Recently, I came across a webshow where regular expressions were discussed, and it piqued my interest. I had heard of regular expressions before, but I had never delved deep into their usage. However, a few days later, I found myself in a situation where regular expressions came to my rescue.

I had a long comma-delimited list of names that I needed to convert into one name per line. With the help of regular expressions, I was able to effortlessly convert the commas to carriage returns, saving me a significant amount of time and effort.

Excited about my newfound knowledge, I shared my experience on Twitter, and Sean McCown, one of the experts from the webshow, recommended watching his session on regular expressions. I took his advice and spent an hour watching the session, and boy, was it worth it!

During the session, I learned several useful codes that can be used with regular expressions. Some of my favorites include:

  • ^ – Matches the beginning of a line
  • $ – Matches the end of a line
  • \n – Represents a line break
  • \t – Represents a tab

These codes opened up a whole new world of possibilities for me. I can’t wait to start using them in my SQL Server queries and data manipulations.

As a bonus, I’d like to share my first real use of regular expressions. I had a comma-delimited list of names from Outlook, and I needed to reformat it. Here’s how I achieved it:

Starting with a comma-delimited list:

Mabon, Sam <SMabon@MyCompany.com>; Kale, Matt <MKale@MyCompany.com>; Fisher, Kenneth <KFisher@MyCompany.com

I performed the following search and replace operations:

  1. Replace all "; " with "\n"
  2. Replace all "{.+}, {.+}[ ]\" with "\2 \1"

And I obtained the desired result:

Sam Mabon
Matt Kale
Kenneth Fisher

As you can see, regular expressions can save a significant amount of time and effort when dealing with complex data transformations. If you ever need to revert the formatted names back to a comma-delimited list, you can easily achieve it by replacing "\n" with ", ".

Regular expressions are a valuable addition to your SQL Server toolkit. They can simplify complex data manipulations and save you precious time. So, if you haven’t explored regular expressions yet, I highly recommend diving into this topic. You’ll be amazed at the possibilities they offer.

Happy querying!

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.