How to find matching BEGIN END pairs in complex SQ

2019-05-23 05:08发布

问题:

I'm reverse engineering a gigantic stored procedure. There are tons of BEGIN ENDs in it, not all indented properly, many levels deep, and I am having a heck of a time finding which BEGIN END pairs match each other.

Is there an easy way to find out which pairs match each other. I know in Visual studio you can jump from opening bracket to closing bracket with ctr+] and same thing in SSMS 2008. But I'm using 2005.

Any ideas?

回答1:

In SQL Server 2005, ctrl+] still works for }, it just doesn't work for BEGIN END. SQL Server 2005 doesn't distinguish between commented out brackets and uncommented brackets, so my solution was to replace all BEGINs with BEGIN/*{*/ and all ENDs with END/*}*/.

So I had something like this:

BEGIN/*{*/

    BEGIN/*{*/

    END/*}*/

END/*}*/

With that I was able to jump back and forth to the paired BEGIN and END.

Look out for BEGIN TRANSACTION commands though, you don't want them included in the replace.



回答2:

I would use a good text editor (like Vim) to replace each BEGIN with { and END with }, like so:

:%s/\<BEGIN\>/{/g
:%s/\<END\>/}/g

Note, the \< and \> are regex metacharacters to ensure you don't match anything other than complete words.

Then in normal mode, place the cursor over the brace character of interest, and hit the % key. Vim will take you to the matching brace.

When you are done reformatting to your satisfaction, replace the brace characters with their original keywords.