Shortcuts/Snippets to select a block of code

Using Autohotkey, I was able to develop a solution to select a block of code and here is the script I have:

!b::

send ^f

sendraw ^\r$

send {F3}

send +{F3}

send {Esc}

send {down}

send ^{=}

return

Specifically, pressing Alt + B will invoke this script, and the script will select the block of code where the cursor is in. Note that the block of code has to be separated from other blocks of code by blank lines, and the block of code cannot have blank of lines inside itself.

The key steps of the about script are

  • using regular expression "^\r$ " to locate the blank lines above and below the cursor

  • moving the cursor to these two blank lines one by one

  • using ctrl + = to select the block of code between these two blank lines.

Note that !/^/+ are alt/ctrl/shift separately.


I'm not affiliated to Red-Gate, but I would like to point out that if you hit Shift-F5, when you own a newish copy of SQL Prompt, then the query your cursor is on, will be marked green, and executed.

It has really saved me a lot of keystrokes.


One way to quickly select blocks of code within SSMS is to minimize the code using the - button next to the leading keyword in a SQL statement (e.g. SELECT, UPDATE, DELETE, WITH, etc.) then highlight that line and press F5 to execute it.

enter image description here

Depending on your version of SSMS (newer versions obviously being preferred in this case), there are also some keyboard shortcuts you can use to collapse/expand a section. The keyboard shortcut link provided by Simon Hellings' earlier response alludes to hotkeys already being set, but I cannot confirm they actually work. However, you can set some custom hotkeys to do this as follows:

  1. The functions we're concerned with setting hotkeys for are found under the Edit -> Outlining Menu Options: enter image description here

  2. To set the hotkeys, navigate to Tools -> Options... -> Environment -> Keyboard -> Keyboard. Type in Outlin into the Show commands containing: box. Then assign a new shortcut key combinations for Edit.ToggleAllOutlining and Edit.ToggleOutliningExpansion and press Assign: enter image description here

  3. Now, check the shortcuts took after pressing Ok and your shortcut keys should work as expected. As you can see, I assigned mine to CTRL+ALT+Left Arrow and CTRL+ALT+Right Arrow, but you can use whatever you want: enter image description here

Finally if this doesn't work, you may have to switch to a different SQL client. It sounds like the functionality you want is similar to executing an Oracle PL/SQL block via CTRL + ENTER within Oracle SQL Developer. You can use Oracle SQL Developer to connect to SQL Server using Third Party Database JDBC drivers (ref), but I don't recommend it.

Tags:

Ssms