You are on page 1of 9

16/05/13

SQL Server Management Studio tips for improving the TSQL coding process - Stack Overflow

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Tell me more

SQL Server Management Studio tips for improving the TSQL coding process

I used to work in a place where a common practice was to use Pair Programming. I remember how many small things we could learn from each other when working together on the code. Picking up new shortcuts, code snippets etc. with time significantly improved our efficiency of writing code. Since I started working with SQL Server I have been left on my own. The best habits I would normally pick from working together with other people which I cannot do now. So here is the question: What are you tips on efficiently writing TSQL code using SQL Server Management Studio? Please keep the tips to 2 3 things/shortcuts that you think improve you speed of coding Please stay within the scope of TSQL and SQL Server Management Studio 2005/2008 If the feature is specific to the version of Management Studio please indicate: e.g. Works with SQL Server 2008 only" EDIT: I am afraid that I could have been misunderstood by some of you. I am not looking for tips for writing efficient TSQL code but rather for advice on how to efficiently use Management Studio to speed up the coding process itself. The type of answers that I am looking for are: use of templates, keyboard-shortcuts, use of IntelliSense plugins etc. Basically those little things that make the coding experience a bit more efficient and pleasant.
sql-server tsql optimization keyboard-shortcuts

edited Mar 12 '12 at 19:02

community wiki kristof

locked by Bill the Lizard Nov 30 '12 at 2:05


This question exists because it has historical significance, but it is not considered a good, on-topic question for this site , so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: FAQ.

30 Answers
Take a look at Red Gate's SQL Prompt - it's a great product (as are most of Red Gate's contributions) SQL Inform is also a great free (online) tool for formatting long procedures that can sometimes get out of hand. Apart from that, I've learned from painful experience it's a good thing to precede any D E L E T E statement with a B E G I NT R A N S A C T I O N. Once you're sure your statement is deleting only what it should, you can then C O M M I T. Saved me on a number of occasions ;-)
edited Sep 19 '08 at 11:22 community wiki Galwegian

SQL Prompt is most definitely for the win. Big thumbs up from me. Charles Roper Sep 19 '08 at 18:20

stackoverflow.com/questions/101079/sql-server-management-studio-tips-for-improving-the-tsql-coding-process

1/9

16/05/13

SQL Server Management Studio tips for improving the TSQL coding process - Stack Overflow
Hear hear for the BEGIN TRANSACTION tip - that's saved me many times! Luke Bennett Sep 23 '08 at 7:49 Some updates are just as damaging as deletes, because they annihilate the data stored in a particular (set of) column(s). Mark Rogers Feb 9 '09 at 17:48 +1 on Red Gate's tools being very useful. I use only SQL Compare, Data Compare, and an old free beta of SQL prompt callisto Jun 2 '09 at 18:50 +1 on the transactions, it took me a few 'ah sh#t' moments in SSMS before I learned, now I never leave the house without them J Cooper Feb 29 '12 at 2:46

community owned wiki Answer - feel free to edit or add comments: Keyboard Shortcuts
F5

CTRL

CTRL CTRL CTRL

+ + +

R N L

+ E or ALT + X - execute currently selected TSQL code show/hide Results Pane Open New Query Window Display query execution plan

Editing Shortcuts
CTRL + K + C and CTRL + K + U - comment/uncomment selected block of code (suggested by Unsliced) CTRL + SHIFT + U and CTRL + SHIFT + L - changes selected text to UPPER/lower case SHIFT + ALT + Selecting text - select/cut/copy/paste a rectangular block of text

Addons Red Gate's SQL Prompt - IntelliSense (suggested by Galwegian) SQLinForm - formatting of TSQL (suggested by Galwegian) Poor Man's T-SQL Formatter - open-source formatting add-in Other Tips Using comma prefix style (suggested by Cade Roux) Using keyboard accelerators (suggested by kcrumley) Useful Links SQL Server Management Studio Keyboard Shortcuts (full list)
edited Jul 19 '12 at 20:01 community wiki 13 revs, 7 users 72% kristof

4 1 1

F5 will also execute only selected text if there is active selection. Pasi Savolainen Apr 24 '09 at 10:57 Drag and drop columns from the object browser rather than use select * For that matter draga and drop object names of all types to prevent mistyping HLGEM Aug 12 '09 at 20:57 I comment/uncomment selected blocks of code so often, I assigned them to [ALT-C] & [ALT-B], respectively (using Accelerator Keys, since SSMS08 doesn't do real Keyboard Mapping). kmote Jun 28 '12 at 17:46

+1 for SQL Prompt. Something real simple that I guess I had never seen - which will work with just about ANY SQL environment (and other languages even): After 12 years of SQL coding, I've recently become a convert to the comma-prefix style after seeing it in some SSMS generated code, I have found it very efficient. I was very surprised that I had never seen this style before, especially since it has boosted my productivity immensely. S E L E C T t . a , t . b , t . c , t . d F R O Mt

stackoverflow.com/questions/101079/sql-server-management-studio-tips-for-improving-the-tsql-coding-process

2/9

16/05/13

SQL Server Management Studio tips for improving the TSQL coding process - Stack Overflow
It makes it really easy to edit select lists, parameter lists, order by lists, group by lists, etc. I'm finding that I'm spending a lot less time fooling with adding and removing commas from the end of lists after cut-andpaste operations - I guess it works out easier because you almost always add things at the end, and with postfix commas, that requires you to move the cursor more. Try it, you'll be surprised - I know I was.
answered Sep 19 '08 at 22:08 community wiki Cade Roux

+1 - I found this very useful as well Burt May 29 '09 at 11:15

3 1

This makes sense... for large lists. Otherwise it's just ugly and a little trickier to read. Joe Philllips Sep 24 '09 at 1:03 I almost always use this format, it makes it easy to comment out columns when testing different result sets. Another format I find useful is keeping a cte's open and close parens above and below its contained sql so I can readily select those lines and hit F5 if I want to see only the cte results Scot Hauder Mar 24 '10 at 4:11 @Scot Hauder - I also do that, I think it merits its own answer. Cade Roux Mar 24 '10 at 15:14

My favorite quick tip is that when you expand a table name in the object explorer, just dragging the word colums to the query screen will put a list of all the columns in the table into the query. Much easier to just delete the ones you don't want than to type the ones you do want and it is so easy, it prevents people from using the truly awful select * syntax. And it prevents typos. Of course you can individually drag columns as well.
answered Sep 19 '08 at 14:16 community wiki HLGEM

Highlighting an entity in a query and pressing ALT + breakdown of any columns, indexes, parameters etc.
edited Jul 19 '12 at 20:55

F1

will run sp_help for it, giving you a

community wiki Luke Bennett

I love Alt-F1; use it almost everyday. Makes for easy shortcutting of column names when I am writing an insert or update statement. p.campbell Feb 9 '09 at 21:07

Try to use always the smallest datatype that you can and index all the fields most used in queries. Try to avoid server side cursors as much as possible. Always stick to a 'set-based approach' instead of a 'procedural approach' for accessing and manipulating data. Cursors can often be avoided by using SELECT statements instead. Always use the graphical execution plan in Query Analyzer or SHOWPLAN_TEXT or SHOWPLAN_ALL commands to analyze your queries. Make sure your queries do an "Index seek" instead of an "Index scan" or a "Table scan." A table scan or an index scan is a very bad thing and should be avoided where possible. Choose the right indexes on the right columns. Use the more readable ANSI-Standard Join clauses instead of the old style joins. With ANSI joins, the WHERE clause is used only for filtering data. Where as with older style joins, the WHERE clause handles both the join condition and filtering data. Do not let your front-end applications query/manipulate the data directly using SELECT or INSERT/UPDATE/DELETE statements. Instead, create stored procedures, and let your applications access these stored procedures. This keeps the data access clean and consistent across all the modules of your application, and at the same time centralizing the business logic within the database. Speaking about Stored procedures, do not prefix your stored procedure names with "sp_". The prefix sp_ is reserved for system stored procedure that ship with SQL Server. Whenever SQL Server encounters a procedure name starting with sp_, it first tries to locate the procedure in the master database, then it looks for any qualifiers (database, owner) provided, then it tries dbo as the owner. So you can really save time in locating the stored procedure by avoiding the "sp_" prefix. Avoid dynamic SQL statements as much as possible. Dynamic SQL tends to be slower than static SQL, as SQL Server must generate an execution plan every time at runtime. When is possible, try to use integrated authentication. It means, forget about the sa and others SQL users, use the microsoft user provisioning infra-structure and keep always your SQL server, up-to-date with all required patches. Microsoft do a good job developing, testing and releasing patches but it's your job to apply it. Search at amazon.com books with good reviews about it and buy it!

stackoverflow.com/questions/101079/sql-server-management-studio-tips-for-improving-the-tsql-coding-process

3/9

16/05/13

SQL Server Management Studio tips for improving the TSQL coding process - Stack Overflow
answered Sep 19 '08 at 11:47 community wiki VP.

Thanks VP for some good pointers here, but in my question I was looking more into different aspects of writing TSQL namely on tips on how to improve the speed of coding itself, not the quality of code. The quality is obviously more important but not the main scope of the question. kristof Sep 19 '08 at 13:31 Perhaps we could add a "community owned wiki" type of question to address those more generic guidelines that you have mentioned kristof Sep 19 '08 at 13:34

CTRL

for incremental search. Hit

F3

or

CTRL

to cycle through the results.

edited Nov 21 '12 at 20:03

community wiki Reddy

If you drag from Object Explorer Columns node for a table it puts a CSV list of columns in the Query Window for you
answered Jan 25 '12 at 18:11 community wiki gbn

shut up! AWESOME jcolebrand Jan 25 '12 at 18:12 Wow, It's help me alot, thanks Conan Apr 12 '12 at 4:57

Keyboard accelerators. Once you figure out what sorts of queries you write a lot, write utility stored procedures to automate the tasks, and map them to keyboard shortcuts. For example, this article talks about how to avoid typing "select top 10 * from SomeBigTable" every time you want to just get a quick look at sample data from that table. I've got a vastly expanded version of this procedure, mapped to CTRL + 5 . A few more I've got: 1. 2. + 0 : Quickly script a table's data, or a proc, UDF, or view's definition + 9 : find any object whose name contains a given string (for when you know you there's a procedure with "Option" in the name, but you don't know what its name starts with) 3. CTRL + 7 : find any proc, UDF, or view that includes a given string in its code 4. CTRL + 4 : find all tables that have a column with the given name
CTRL CTRL

... and a few more that don't come to mind right now. Some of these things can be done through existing interfaces in SSMS, but SSMS's windows and widgets can be a bit slow loading up, especially when you're querying against a server across the internet, and I prefer not having to pick my hands up off the keyboard anyway.
edited Jul 19 '12 at 20:51 community wiki kcrumley

If you could paste in the SQL you use for each of those commands that would be super useful. fatcat1111 Aug 12 '09 at 20:35

Just a tiny one - rectangular selections ALT + D R A G come in really handy for copying + pasting vertically aligned column lists (e.g. when manually writing a massive UPDATE). Writing TSQL is about the only time I ever use it!
edited Jul 19 '12 at 20:56 community wiki Jon M

The thing is, that all those tiny bits when added together and used properly can make a real difference kristof Apr 24 '09 at 13:27 I've tried this once but I always forget it exists! Joe Philllips Sep 24 '09 at 0:52

For Sub Queries


stackoverflow.com/questions/101079/sql-server-management-studio-tips-for-improving-the-tsql-coding-process 4/9

16/05/13

SQL Server Management Studio tips for improving the TSQL coding process - Stack Overflow
object explorer > right-click a table > Script table as > SELECT to > Clipboard Then you can just paste in the section where you want that as a sub query.

Templates / Snippets
Create you own templates with only a code snippet. Then instead opening the template as a new document just drag it to you current query to insert the snippet. A snippet can simply be a set of header with comments or just some simple piece of code.

Implicit transactions
If you wont remember to start a transaction before your delete statemens you can go to options and set implicit transactions by default in all your queries. They require always an explicit commit / rollback.

Isolation level
Go to options and set isolation level to READ_UNCOMMITED by default. This way you dont need to type a NOLOCK in all your ad hoc queries. Just dont forget to place the table hint when writing a new view or stored procedure.

Default database
Your login has a default database set by the DBA (To me is usually the undesired one almost every time). If you want it to be a different one because of the project you are currently working on. In 'Registered Servers pane' > Right click > Properties > Connection properties tab > connect to database.

Multiple logins
(These you might already have done though) Register the server multiple times, each with a different login. You can then have the same server in the object browser open multiple times (each with a different login). To execute the same query you already wrote with a different login, instead of copying the query just do a right click over the query pane > Connection > Change connection.
answered Oct 3 '08 at 6:41 community wiki Ricardo C

Another thing that helps improve the accuracy of what I do isn't really a management studio tip but one using t-sql itself. Whenever I write an update or delete statement for the first time, I incorporate a select into it so that I can see what records will be affected. Examples: s e l e c tt 1 . f i e l d 1 , t 2 . f i e l d 2 u p d a t et s e tf i e l d 1=t 2 . f i e l d 2 f r o m m y t a b l et 1 j o i nm y o t h e r t a b l et 2o nt 1 . i d f i e l d= t 2 . i d f i e l d w h e r et 2 . f i e l d 1> 1 0 s e l e c tt 1 . * d e l e t et 1 f r o mm y t a b l et 1 j o i nm y o t h e r t a b l et 2o nt 1 . i d f i e l d= t 2 . i d f i e l d w h e r et 2 . f i e l d 1=' t e s t ' (note I used select * here just for illustration, I would normally only select the few fields I need to see that the query is correct. Sometimes I might need to see fields from the other tables inthe join as well as the records I plan to delete to make sure the join worked the way I thought it would) When you run this code, you run the select first to ensure it is correct, then comment the select line(s) out and uncomment the delete or update parts. By doing it this way, you don't accidentally run the delete or update before you have checked it. Also you avoid the problem of forgetting to comment out the select causing the update to update all records in the database table that can occur if you use this syntax and uncomment the select to run it:

stackoverflow.com/questions/101079/sql-server-management-studio-tips-for-improving-the-tsql-coding-process

5/9

16/05/13

SQL Server Management Studio tips for improving the TSQL coding process - Stack Overflow
s e l e c tt 1 . f i e l d 1 , t 2 . f i e l d 2 u p d a t et s e tf i e l d 1=t 2 . f i e l d 2 s e l e c tt 1 . f i e l d 1 , t 2 . f i e l d 2 f r o m m y t a b l et 1 j o i nm y o t h e r t a b l et 2o nt 1 . i d f i e l d= t 2 . i d f i e l d w h e r et 2 . f i e l d 1> 1 0 As you can see from the example above, if you uncomment the select and forget to re-comment it out, oops you just updated the whole table and then ran a select when you thought to just run the update. Someone just did that in my office this week making it so only one person of all out clients could log into the client websites. So avoid doing this.
edited Sep 24 '09 at 0:53 community wiki HLGEM

Use the Filter button in the Object Explorer to quickly find a particular object (table, stored procedure, etc.) from partial text in the name or find objects that belong to a particular schema.
answered Nov 29 '12 at 18:19 community wiki ptilton

I have a scheduled task that each night writes each object (table, sproc, etc.) to a file. I have full-text search indexing set on the output directory, so when I'm looking for a certain string (e.g., a constant) that is buried somewhere in the DB I can very quickly find it. Within Management Studio you can use the Tasks > Generate Scrips... command to see how to perform this.
answered Aug 12 '09 at 20:45 community wiki fatcat1111

Care to share that code? Simple as it may seem ... Some of us are learning SSMS for the first time ;) jcolebrand May 5 '10 at 20:41

I like to setup the keyboard shortcut of CTRL + F1 as sp_helptext, as this allows you to highlight a stored procedure and quickly look at it's code. I find it is a nice complement to the default ALT + F1 sp_help shortcut.
edited Jul 19 '12 at 20:52 community wiki scott

And before hitting Ctrl-F1 hit Ctrl-T first to output the results to text so you can copy it. Geert Immerzeel Jul 27 '10 at 8:44

I suggest that you create standards for your SQL scripting and stick to them. Also use templates to quickly create different types of stored procedures and functions. Here is a question about templates in SQL Server 2005 Management Studio How do you create SQL Server 2005 stored procedure templates in SQL Server 2005 Management Studio?
answered Sep 19 '08 at 11:03 community wiki Chris Woodruff

I am developer of SSMSBoost add-in that was recently released for SSMS2008/R2, the intention was to add add features that speed up daily routine tasks: Shorcuts:
F2

- (in SQL Editor): script object located unted cursor

CTRL + F2 - (in SQL Editor): find object located under cursor in object explorer and focus it +It includes Shortcut editor, that is missing in SSMS2008 (is coming in SSMS2012)

also SSMSBoost adds toolbar with buttons:

stackoverflow.com/questions/101079/sql-server-management-studio-tips-for-improving-the-tsql-coding-process

6/9

16/05/13

SQL Server Management Studio tips for improving the TSQL coding process - Stack Overflow
Syncronize SQL Editor connection to Object Explorer (focuses current database in Object Explorer) Manage your own preferred connections and switch between them through combo-box (including jumps between servers) Auto-replacements: typing "sel" will replace it by s e l e c t*f r o mand you can also add your own token-replacement pairs and some more useful features

edited Jul 19 '12 at 20:56

community wiki Andrei Rantsevich

Display the Query Designer with


edited Nov 30 '12 at 2:05

CTRL

SHIFT

community wiki 3 revs, 3 users 60% Peter Gfader

Also don't be afraid/ashamed to use it. It's good place to forge connections & join directions. Pasi Savolainen Apr 24 '09 at 10:59

Make use of the TRY/CATCH functionality for error catching. Adam Machanic's Expert SQL Server 2005 Programming is a great resource for solid techniques and practices. Use ownership chaining for stored procs. Make use of schemas to enforce data security and roles.
answered Sep 19 '08 at 12:42 community wiki Jeremiah Peschka

Use Object Explorer Details instead of object explorer for viewing your tables, this way you can press a letter and have it go to the first table with that letter prefix.
answered May 15 '09 at 17:50 community wiki Nathan Koop

If you work with developers, often get a sliver of code that is formatted as one long line of code, then sql pretty printer add-on for SQL Server management Studio may helps a lot with more than 60+ formatter options. http://www.dpriver.com/sqlpp/ssmsaddin.html
answered Jul 31 '09 at 6:53 community wiki James

Using bookmarks is great way to keep your sanity if you're working with or troubleshooting a really long procedure. Let's say you're working with a derived field in an outer query and it's definition is another 200 lines down inside the inner query. You can bookmark both locations and then quickly go back and forth between the two.
answered Mar 30 '11 at 17:24 community wiki

stackoverflow.com/questions/101079/sql-server-management-studio-tips-for-improving-the-tsql-coding-process

7/9

16/05/13

SQL Server Management Studio tips for improving the TSQL coding process - Stack Overflow
traughber

(@ptilton: if you want to add some information to an answer, you should either comment or post your own answer instead of editing) For all others: @ptilton mentioned the following (useful) shortcuts for bookmarks: CTRL+K+K - Create/Remove a bookmark on current line in editor; CTRL+K+P-Navigate to previous bookmark; CTRL+K+P-Navigate to next bookmark MartinStettner Nov 29 '12 at 22:09

If you need to write a lot of sprocs for an API of some sort. You may like this tools I wrote when I was a programmer. Say you have a 200 columns table that need to have a sproc written to insert/update and another one to delete. Because you don't want your application to directly access the tables. Just the declaration part will be a tedious task but not if a part of the code is written for you. Here's an example... C R E A T EP R O Cu p s e r t _ T a b l e 1 ( @ c o l 1i n t ,@ c o l 2v a r c h a r ( 2 0 0 ) ,@ c o l 3f l o a t ,e t c . ) A S B E G I N U P D A T Et a b l e 1S E Tc o l 1=@ c o l 1 ,c o l 2=@ c o l 2 ,c o l 3=@ c o l 3 ,e t c . I F@ @ e r r o r< >0 I N S E R TT a b l e 1( c o l 1 ,c o l 2 ,c o l 3 ,e t c . ) V A L U E S ( @ c o l 1 ,@ c o l 2 ,@ c o l 3 ,e t c . ) E N D G O C R E A T EP R O Cd e l e t e _ T a b l e 1 ( @ c o l 1 ) A SD E L E T EF R O MT a b l e 1W H E R Ec o l 1=@ c o l 1 http://snipplr.com/view/13451/spcoldefinition-or-writing-upsert-sp-in-a-snap/ Note : You can also get to the original code and article written in 2002 (I feel old now!) http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=549&lngWId=5
answered May 31 '12 at 5:49 community wiki PollusB

Using Also,

TAB SHIFT

on highlighted text will indent it. Nice for easily arranging your code in a readable format. + TAB will unindent.
community wiki Joe Philllips

edited Jul 19 '12 at 20:51

F5 to run the current query is an easy win, after that, the generic MS editor commands of C to comment out the selected text and then CTRL + K + U to uncomment.
edited Jul 19 '12 at 20:57 community wiki Unsliced

CTRL

A L T + S H I F T+ Selection This is a great one I discovered recently - it lets you select a rectangular section of text regardless of line breaks. Very handy for clipping out a subquery or list quickly.
edited Jul 20 '12 at 2:15 community wiki JNK

Devart' SQL Complete express edition is an SSMS addon and is a free and useful addon. It provides much needed code formatting and intellisense features. I also use S S M S T o o l s P a c k addon and it is very good. I Love; 1. It's SQL snippets where you can create short keys for code snippets and it appends them automatically when you type these keys and press enter. 2. Search through history to retrieve your queries which you ran months ago and forgot, saved a lot of my time. 3. Restore last session. Now I never save my queries if I have to just restart my windows. I just click on restore last session and my last session gets and restored and connection created automatically. 4. Create insert statements from query results (very useful). Just love this addon.

stackoverflow.com/questions/101079/sql-server-management-studio-tips-for-improving-the-tsql-coding-process

8/9

16/05/13

SQL Server Management Studio tips for improving the TSQL coding process - Stack Overflow
A small catch recently introduced. SSMSToolsPack is not free anymore for SSMS 2012. It's still free for SSMS 2005 and SSMS 2008, till yet. Use it only if you want to buy it when you migrate to SSMS 2012. Otherwise may be it's a good idea to wean away from it.
edited Sep 21 '12 at 7:16 community wiki AbbsHere

I warmly recommend Red Gate's SQL Prompt. Auto-discovery (intellisense on tables, stored procedures, functions and native functions) is nothing short of awesome! :) It comes with a price though. There is no free-ware version of the thing.
answered Sep 23 '08 at 10:22 community wiki roosteronacid

Being aware of the two(?) different types of windows available in SQL Server Management Studio. If you right-click a table and select O p e n it will use an editable grid that you can modify the cells in. If you right-click the database and select N e wQ u e r y it will create a slightly different type of window that you can't modify the grid in but it gives you a few other nice features, such as allowing different code snippets and letting you execute them separately by selection.
edited Sep 24 '09 at 1:04 community wiki Joe Philllips

Use a S E L E C TI N T O query to quickly/easily make backup tables to work and experiment with.
edited Sep 24 '09 at 1:05 community wiki Joe Philllips

Not the answer you're looking for? Browse other questions tagged sql-server tsql
optimization keyboard-shortcuts or ask your own question.

stackoverflow.com/questions/101079/sql-server-management-studio-tips-for-improving-the-tsql-coding-process

9/9

You might also like