Monday, August 06, 2007

RegEx trick for sql field names

A new guy at work has shown me how powerful regular expressions are. Following is a trick for formatting the columns names of a SQL table.

Do a query in SQL Query Analyzer on your table like:
SELECT * FROM table WHERE 1=0

Results in

Column1 Column2 Column3 Column4

It will return 0 rows. Be sure to return the results as text (ctrl + T), so you can just copy the header row that will have all the field names, separated by a ton of spaces. Paste the results in Notepad++. Open up the replace dialog. Check the "Regular expressions".

Find \s+

"\s" means find any white space. "+" means repeat the previous character until you don't find it anymore.

Replace with \n,

That is a new line and a comma.

The final result is

Column1
,Column2
,Column3
,Column4

Notepad++ uses the POSIX regular expression language. I look forward to using it more.

No comments: