question

Magnus Ahlkvist avatar image
Magnus Ahlkvist asked

Regex for finding SQL Server strings

Hi all! I have done some SMO-programming in order to convert all varchar, char and text fields to nvarchar, nchar and nvarchar(max) in a database. I'm also using SMO and regular expressions to do the same thing in all stored procedures in the database. Replacing variables and parameters is no problem, I have working regular expressions for matching those. But I'm having some problems with string matchine - I need to replace all 'some string' with N'some string' in all stored procedures. The regex I'm using for that string matching right now is: **(['])(?:(?!\1)[^'']|''.|''''.)*\1** But that's not working perfectly. I'm using it now, and manually going through a text-file with all 1600 stored procedures, correcting where the regex hasn't made a correct match. I'm almost finished, but it struck me that I can't be the only who ever did this exercise... How would you do this? Would you say using SMO and Regex is the way to go? If so, does anyone have a regex that correctly matches SQL Server strings?
regexsmo
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Matt Whitfield avatar image
Matt Whitfield answered
The regex you want is the following: '([^']|'')*' Let me know if that works for you, but I've tested it with a few edge cases and it seems OK... By the way, if you don't use it, I heartily recommend [Expresso][1]. [1]: http://www.ultrapico.com/Expresso.htm
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Matt Whitfield avatar image Matt Whitfield ♦♦ commented ·
Yeah - of course. To be honest, I never use Regex's for parsing - I always use my own custom-written parser, simply because it is 100% to spec, and handles everything. It's not the simplest bit of C# on the planet though...
1 Like 1 ·
Magnus Ahlkvist avatar image Magnus Ahlkvist commented ·
Hi, Thanks for the suggestion. Where my own regex fails is when there are comments in stored procedures with single quotes - like **/\* this'll break things \*/**. One thing that I'd like to be able to handle automagically, but where I think I'll have to give up is being able to also N-prefix strings in dynamic SQL statements in stored procedures. Thanks for the link - I hadn't seen Expresso before. It goes into my "To explore" section of my Favorites.
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.