SlideShare a Scribd company logo
SSMS for the Accidental DBA
Eric Selje
Geeks and Gurus, Inc.
1308 Spring Street
Madison, WI 53711
Voice: 608/213-9567
Twitter: EricSelje
Email: eselje@geeksandgurus.com
You're a database application developer who's using SQL Server now, but you're no DBA. Sure
you use SQL Server Management Studio (SSMS), and maybe you're even pretty good at
designing tables and executing queries. But there's a whole lot more functionality in this
seemingly simple program than you may realize. In this session we'll share features in SSMS
that you may have overlooked but will make your life as a developer a lot easier.
You Are a DBA
A lot of us Visual FoxPro developers didn’t plan it, but we ended up becoming “accidental”
DBAs. It may happen organically: our application grew until we reached the point where
we needed to migrate the database from Visual FoxPro tables to a “real” database. Other
times we’re thrust into an existing project that already has all the data in a back-end
database.
For Visual FoxPro developers who have grown comfortable in the Microsoft environment,
SQL Server is the natural choice for the back-end database. And since the free SQL Server
Express version was released a few years ago, many developers have chosen to forego
FoxPro’s native database and start directly with that. Its limitation of 10 GB per database is
usually ample for our Visual FoxPro applications, which were effectively capped at 2GB.
There are other options available to us, including the intriguing SQLAnywhere from Sybase,
the open source MySQL and PostgreSQL, and of course the big boys Informix and Oracle.
Some of the concepts presented in this paper may well be applicable to those database
engines as well, but this guide is focused on SQL Server Management Studio (SSMS). The
ideas will be applicable to all versions of Microsoft SQL Server up to 2012, including the
Express versions. The screenshots and examples are done in the version that is currently
most popular, SSMS 2008.
This whitepaper is not a comprehensive how-to guide for SQL Server. It will not teach you
everything you know to become a SQL Server DBA or even how to get started with SQL
Server. If you need a starting reference, Microsoft Press offers the free eBook “Introducing
SQL Server 2012” at their site (http://www.microsoft.com/sqlserver/en/us/default.aspx).
I’m going to assume you’ve already got SQL Server installed either locally or on a server
(including Azure) and already have some databases installed. If you don’t have any SQL
Server databases yet, you can download the sample databases from Microsoft including the
ubiquitous and oft-cited “Northwind” database and the newer and more complex
“AdventureWorks” database, which I’ll be using in this paper.
This document contains tips and tricks for database developers who are not full time DBAs
but are using SQL Server Management Studio regularly and want to go beyond the basics
and explore some of the power of this seemingly-simple tool. These are tips that I’ve jotted
down as I’ve used it as well as many that I’ve collected from other users on blogs, in user
groups, and even while presenting this session at SQL Saturdays in my area.
So here then I present to you my Top Tips in SSMS for the Accidental DBA.
Get Organized With Solutions and Projects
Can you imagine using Visual FoxPro without using the Project Manager? Perhaps many of
you can remember the time before that tool was introduced, with PRG files scattered hither
and yon. Remember then the feeling of power and organization you got when you first
encountered the Project Manager in FoxPro?
Using “Solutions” in SMSS is similar to using projects in VFP, and exactly like using
Solutions in Visual Studio (because SSMS is actually built using the same IDE as Visual
Studio, which will be a recurring theme in this document).
Solutions are the way to organize all of the little snippets of SQL that you don’t keep in your
database. These might be utility scripts that you use often for wiping out or adding in test
data, tests you’ve written to verify your database’s stored procedures, or whatever other
miscellaneous thing you have.
Surprisingly many users of SQL Server Management Studio, including full time DBAs, don’t
take advantage of Solutions and Projects in SSMS. Instead they rely on the file system to
organize their odd collection of scripts that remain outside of the database proper. If you
don’t believe me just watch any of the training videos available on the SQL PASS
(Professional Association for SQL Server) website and you’ll see plenty of opportunities for
the presenters to use Solutions to organize their scripts, and yet they don’t do it. Part of the
problem may be that the Solution Explorer is not visible by default in SSMS, so let’s start by
making that visible by choosing View | Solution Explorer.
It’s important to note that Solutions are stored in the file system and not in the database, so
if you want to share them with your co-developers you need to save the solutions in a
shared space. However because they’re stored as ASCII files, you can add them to a Source
Control provider (unlike the stored procedures and functions in the database, though there
are 3rd Party Tools to add those into a version control system as well. That’s beyond the
scope of this paper).
To create a new Solution in SSMS, you (counter intuitively) select File | New Project from
the menu. On that dialog (Figure 1) you’ll have the option to create a new solution or add the
new project to an existing solution. Solutions can contain multiple projects. This is where
you indicate the Source Control provider, if you’ve installed one SSMS via the Tools |
Options | Source Control dialog (Figure 3). If you don’t initially hook up your solution to a
version control provider, you can go back later and right click on the project to add it (Error!
Reference source not found.).
Figure 3: Source Control Options for your Scripts
Figure 1: New Project/Solution Dialog, with option for Source Control
Figure 2: Retroactive Source Control
A solution can contain many projects, and each project contains three types of objects:
Connections (to a database)
Queries (T-SQL scripts)
“Miscellaneous” (whatever you want)
Connections hold a, you guessed it, connection to a server. Each project can hold as
many connections as you want, but only one for each named server/login combination
which means I can’t have one to the AdventureWorks database on my local server, and
another one to the AdventureWorks2008 database on my local server in the same project.
When you add a connection you get a dialog® that you probably recognize (Figure 4, upper
left). Here you specify the server you want to connect to, the authentication method, and
optionally but optimally the default database name (on the Connection Properties tab).
It is a little frustrating that you can’t add more than one connection to the same server with
the same login. You can get around this limitation by creating new logins or aliasing your
Figure 4: You can't have two connections to the same server, and a manual workaround doesn't help.
database different ways but in the end SSMS might be saving us from some self-inflicted
confusion here. I’d prefer to have the option though.
I tried to be clever and manually modify the actual text file that holds the project (Figure 4,
upper right), but changing the ConnectionNode “name” attribute is not what shows up in the
tree view of the connection (Figure 4, bottom), and now I’m really confused about which
connection is for which database. I think it might be best to just live within SSMS’s
restriction until they include the ability to rename a connection.
As a recommended practice, include connections to point to each client’s Live Production
server, their Test server, and Development database server in a project. Set the default
database for each connection. This saves me a ton of time over trying to find the server in
my usual “Connect” dialog’s long list of servers (Error! Reference source not found.).
What saves even more time however is that by double clicking on a connection in my
project I’m immediately brought to a New Query window, connected to the right server and
defaulting to the right database in one easy
step.
Queries or more accurately, “scripts”
organize the .SQL files for your database.
These are not the stored procedures, of
course, as they are contained in the
database itself. The scripts are the
miscellanea that you might use to automate
repetitive tasks or tests.
For example you might have a script that
SELECTs all columns from your largest
table. Why would you want a script to do
this? So that when your database goes
down you have a quick way of “priming”
the cache memory of the server with data in
order to speed up subsequent queries. This
could be a stored procedure as well, but do
you really want a stored procedure that
does this?
Another good script to have ready to go at all times is one that restores the database. It
wouldn’t make any sense to have this as a stored procedure, since you can’t get at the
stored procedures if the database is down.
Adding queries to the project can be done one of three ways. If you simply right+click on
the Queries folder and select “New Query” (or double-click, as mentioned) you’ll get a blank
tab where you can start scripting away. It will give a generic sequential name and
automatically be included in your project, so once you’re happy with your script you’ll have
to manually rename it to something meaningful. Be sure to keep the .SQL extension or SSMS
will move it from Queries to Miscellaneous.
Figure 5: The long list of every server ever
You can also right+click on the Project and select Add | New Query (Figure 6Error! Reference
source not found.) to accomplish the same thing.
The other way to add a query to your project is to right+click on the Project itself and
choose Add | New Item… (also Figure 6). By choosing this option you will see a dialog (Figure
7) that is chock full of Query Templates that you can use to do routine tasks, such as the
aforementioned Database Restore script. It also lets you name the query immediately
rather than having to remember to do it afterwards, and it defaults to a meaningful name.
This is a great way to get a head start on any T-SQL script, because who can ever remember
anything beyond the everyday syntax?
Figure 6: Add new query or "item" to project
Figure 7: Adding a new ITEM allows you to select from a plethora of script templates
Figure 8: The "Restore Database" script, in the project and properly name
The Miscellaneous group under the project holds any file that doesn’t have a .SQL
extension. That could be notes to yourself, task lists, Analysis Services Queries (if that’s
your thing, but way beyond the scope), etc. Don’t put anything sensitive in here, as these
are just files stored on your drive and aren’t encrypted or protected in any way.
Solutions are an excellent organizational tool. Use them. One shortcoming of solutions is
that you can only have one open at a time. But since a solution can contain multiple
projects, what works for me is to have one solution called “All Clients,” and then have a
separate project for each client. That way everything I need is available to me without
opening and closing multiple solutions.
.
Figure 9: Projects show in the QuickList, and your favorites can be pinned.
Bonus tip: When you use solutions in Windows Vista and up, the solution is available to you
via a “QuickList” (Figure 9). You can even pin your favorite(s) to make sure they don’t drop
off the list.
Find that Needle
Developers, and consultants particularly, are often called in to quickly troubleshoot a
database they’ve never even seen before. When time is of the essence these tips will help
you quickly discover what’s going on inside the database. If you’re paid by the hour and
your client has an unlimited budget, you can ignore this section.
Filter, Don’t Search
Nothing will slow you down quite like scrolling through a long list of objects in the Object
Explorer (Figure 10, Left), trying to find the one thing that you’re looking for. Instead, right
click on the category you’re looking for and click “Filter Settings”. You can then filter out
the list not just by the name, schema, owner, or creation date. So you can show, for
example, all the views created in the last month.
Figure 10: Filtering Long Lists
Search, Don’t Filter
Filters unfortunately aren’t that powerful. For example you might want to see the views
modified in the last 30 days, and you might want that list in the Output window. For cases
like that you cannot merely filter because a) modified date isn’t one of the fields you can
filter on for views, and b) the results are only in the filtered list and that doesn’t lend itself
to output.
You’re going to need to query the metadata of the database. SQL Server keeps everything
about itself in SQL Server itself, which you can then query. To get that aforementioned list,
you can issue this command in the Query Window:
Example 1: Get views modified within the last 30 days.
SELECT OBJECT_NAME(object_id), * FROM sys.views WHERE views.modify_date >
GETDATE()-30
You can now export that output into any number of formats (more on that later).
Bonus Tip: Hey, that’s a handy query! Save it in your project.
Here’s another handy search, which will list all of the objects in the database that have the
string ‘txtCounty’, a field that I’m interested in because my application uses it:
Example 2: Show me every module (function, stored procedure, triggers, view) that has
needs the ‘Email’ field.
SELECT OBJECT_NAME(object_id), * FROM sys.sql_modules WHERE definition LIKE '%Email%'
What other metadata can you query? The system views in the sys schema can give up just
about all the information about the database, including tables, columns, views, stored
procedures, indexes, triggers, partitions, and so much more. Just try typing…
SELECT * FROM sys.
…and look at the long list in the Intellisense.
Bonus Tip: RedGate makes a ton of excellent tools, most of which cost money. SQL Search
makes querying SQL Server as easy as GoFish makes querying Visual FoxPro, and it is free on
RedGate.com
The Devil’s in the Details
Well, maybe. But you won’t know unless you view the details. Hit F7 (or View | Object
Explorer Details) to do that, and you’ll see the details of whatever category you highlight in
the Object Explorer. Select “Tables” and you’ll see list of all of the tables, along with the
schema, row count, and creation date (Figure 11). Select “Columns” and you’ll see a list of all
the columns for that table. Select … well you get the idea.
Notice the toolbar at the top of the Object Explorer Details pane. There’s a “Search” pane
here that allows you filter the results list to quickly find what you’re looking for.
But wait, there’s more!
Right+click on the column
headings and you can add
columns for Data Space Used
(table size), a handy way to see
how big your tables are.
Unfortunately there isn’t a “Last
Update” column, so it still has a
little ways to go before catching
up with Visual Foxpro’s “DIR”
command.
And speaking of FoxPro tables,
here’s a quick way in SQL
Server to get something
approximately equal to the LIST
STRUCTURE command.
Figure 11: Object Explorer Details Pane
1. In a Query window, type in the name of a table. Fully qualify it if it’s not in the ‘dbo’
schema of the current database (a quick way to do this is to just right+click the table
and choose “Select Top 1000 Rows”).
2. Highlight the complete name of the table in the query window by double-clicking on
it. If it has the schema name in it, it must be encased in square brackets.
3. Hit Alt+F1. The schema of the table and more will appear in the results window
(Figure 12). This looks good in a grid, but might be extra useful if you send the results
to text or to a file, where they could be shared with someone, searched, or archived.
Bonus Tip: If you hit Alt+F1 and get a very large unexpected resultset back, you didn’t have
anything highlighted and thus got the schema for the entire database and not just the table
you were looking for. That may also be handy.
We’ll talk more about System Stored Procedures later, but for fun try highlighting different
things and hitting Alt+F1.
What kind of magic is this? Alt+F1 is really just a shortcut (see Figure 16) to a System Stored
Procedure named sp_help. We could have manually just typed in sp_help
[database.schema.table] in our query window, but that takes away the magic.
Figure 12: The "List Structure" of the SQL Server world.
Claim those Dependencies
Have you ever thought right before you change the schema of a table, “I wonder what this is
going to break?” Wouldn’t it be nice to see which views and stored procedures are going to
be affected by your change to a table? In SSMS, just right+click and select View
Dependencies and you will get that very information (Figure 13).
Conversely, if you have a large stored procedure and don’t want to have to thoroughly
peruse it to see which tables it uses, right+click on it and select View Dependencies, and
then toggle the option at the top to “Objects on which [procedure] depends (Figure 14).
Get the Big Picture
If you’re a visual person, you’ll appreciate the ability of SSMS to provide you with a visual
interpretation of the entire database, or a subset thereof. Simply right+click the Database
Diagrams node in Object Explorer and select New Database Diagram. Then add all the
tables from your database into your diagram ().
Tip: You can also drag table names from the Object Explorer and drop them in your
diagram later.
Don’t worry about placing the tables nicely, because when you’ve got all the tables you
want loaded, you can simply right+click on the diagram’s canvas and select Arrange Tables,
and SSMS will lay them out nicely.
By default SSMS shows you the names of the columns and the relationship lines between
the tables, but you can configure this. For example if you hit Ctrl+A to select all of the
tables, then right+click on a table name and select Table View | Standard, you’ll see the data
types and the nullability of the tables as well. You can also right+click on the canvas and
select Show Relationship Labels to toggle those on or off.
Figure 13: These Items are Dependents Figure 14: This Item Claims These Dependents
One thing you should be aware of is these diagrams are “live” in the sense that you can
change the schema by changing the diagram! Thoughtfully, SSMS asks us to save and warns
us the tables are going to be updated.
Viewing a database diagram is a quick way to ascertain a database’s schema.
Figure 15: Database Diagram
Quicken the Pace
There are an enormous number of shortcuts to get around SSMS quickly. The first thing a
developer needs to know is that many of them are the same ones as available in Visual
Studio (again, because they’re based on the same IDE framework). So if you want to
comment a block of code in a T-SQL query or stored procedure, just hit Ctrl+K, C. I could go
on, but there’s a full list of SSMS shortcuts available at http://msdn.microsoft.com/en-
us/library/ms174205.aspx that you can peruse.
Here are some that I find myself using all the time.
Ctrl+E: Execute the current query. This one seems so obvious that I’m almost afraid to
mention it, but I see enough people that do this the hard way (Query | Execute) that I feel I
must mention it. You can also hit F5, which is the same as running your app in Visual
Studio.
Ctrl+U: This one probably saves more total time than any other. How many times have you
typed a query, say SELECT * FROM MyTable, only to have SQL Server come back and say
“Could not find MyTable.” Argh. Of course not! Because MyTable is actually in a database
that’s not the “current” database. You could type USE database before you’re SELECT (that’s
the equivalent of SET DATABASE TO and a little counterintuitive for us FoxPro folks). Or
you could spell out the entire name of the table, a la SELECT * FROM
MyDatabase.MySchema.MyTable, but that’s a lot of typing and you don’t want to have to do
that every time.
The quickest way is to just indicate to SSMS which database you’d like to be current, and
there’s a dropdown for that right in the toolbar. But rather than reach for that mouse, just
hit Ctrl+U, start typing the name of the database you want to be current, and then hit Enter
to jump back into your query.
Ctrl+W: Another one that’s completely counterintuitive for a FoxPro coder, Ctrl+W selects
the word under the cursor. I find this handy for deleting fields, parameters, or any other
extraneous optional fields in my code. Keep this one in mind and you’ll find yourself using
it quite a bit, especially in combination with that Alt+F1 shortcut from earlier.
Tip: If there’s not a shortcut for your favorite stored procedure, you can create one yourself
with Tools | Options, Keyboard, under Query Shortcuts (Figure 16). Here it also becomes
clear why Alt+F1 fired the sp_help
stored procedure! It can be your own
stored procedure or a System Stored
Procedure. For a complete list of
available System Stored Procedures,
simply expand the Programmability |
Stored Procedures | System Stored
Procedures in your database’s Object
Explorer. Whatever is highlighted will
become the first parameter sent to the
stored procedure.
Figure 16: Set your own Keyboard Shortcuts
Bonus Tip: An easy way to learn the SSMS shortcuts is to have SSMS tell you what they are.
It will, but this feature is turned off by
default. To turn it back on, select Tools
| Customize (Figure 17), and check the
box to show ScreenTips and the box to
show Shortcut Keys. Then you’ll get
hints to what things do and any
shortcut that might help you do it
quicker (Figure 18).
Mouse Shortcuts
You never have to type the name of a
database, table or column again.
Simply drag the name over from the
Object Explorer and SSMS will insert
the name for you. When you drag a table name, it doesn’t put the database name in so you
may have to use the Ctrl+U trick to set the database to the current table.
While you’re looking at the table in Object Explorer, you can drag the word Columns over to
the query window and SSMS will insert the name of each and every column in the table.
You can then use the Ctrl+W trick to remove any columns you don’t want.
Another handy thing you can do with your mouse is Alt+Select, which allows you to select a
rectangle of text and then manipulate within that rectangle. You can delete it, move it over,
or search/replace within that selection. This is very handy when you want remove an alias
in front of a set of column fields, for instance.
Figure 17: Help SSMS Help You
Figure 18: ScreenTip with shortcut
Science!
SQL Server Management Studio includes much better tools for analyzing what’s going on
behind the scenes than Visual FoxPro does. Learning to use those tools to their full
potential is the subject of entire books, but be aware that they’re there and what they do.
Display Actual Execution Plans
Vaguely reminiscent of VFP’s SYS(3054), the Execution Plans (Figure 19) shows exactly how
SQL Server processed your query. You can include that along with the query results by
hitting Ctrl+M before running your query.
Alternatively you can choose to display the Estimated Execution Plan instead. With an
Estimated Plan, you don’t actually have to run the query in order to see what SQL Server
may do with your query. This is great for avoiding long running queries, but it may not be
entirely accurate.
Figure 19: An Estimated Execution Plan with One Operation Highlighted
Things to Look For in Execution Plans
Just like FoxPro, you want to see indexes being used for as much as possible. There’s a real
science to interpreting Execution Plans, but a here are some tips:
(Clustered) Index Seek: This means SQL Server is going to use an Index, which is of course
desirable. It may use the “Clustered” index (which stores not just the key but also all of
fields in the table, which is why there can be only one per table) or not.
Things to Avoid
(Clustered) Table Scans: This means your entire table had to be searched in order to find
the values you wanted. A large table means slow results and an index on the WHERE value
needs to be added.
Key Lookups/Nested Loops: This means the query had to go back to the clustered index in
order to retrieve the fields you wanted. If this is a query you run often, consider adding the
fields you need as “covered” fields in the index that was used.
For a great read on interpreting execution plans, I recommend Grant Fritchley’s “SQL Server
Execution Plans.”
View Client Statistics
Ever wonder if it’s quicker to run a query one way or another? SSMS provides a fantastic
tool for accurately comparing the execution times of your queries. In Visual FoxPro we
might try doing this by storing the DATETIME(), running the query, and then subtracting
the DATETIME() again afterwards. Toggle the Client Statistics (Query | Include Client
Statistics, or Shift+Alt+S) to have this all done for you (Figure 20).
Run a query once, change it around, then run it again. Do it a few times. You’ll see how long
everything took, trends, and even an average column. No more guessing or going by feel.
SQL Server Profiler
While technically not part of SSMS, SQL Server Profiler is another tool that developers
should keep in their belt. It’s particularly useful for those “black box” applications you
inherit and you have no idea what’s going on inside (perhaps you don’t even have the
source code), but it’s also great for figuring out which queries your Visual FoxPro
application are making through SQLExec() or remote views that are taking so long.
SQL Server Profiler comes with full version of SQL Server (not Express), but you can
download the trial version of the full version and it works fine. You can quickly access it
from the Tools menu in SQL Server Management Studio.
Once loaded (Figure 21), you set up a “trace” that will log the inner happenings of the server.
This is kind of similar to the Event Tracking feature in Visual FoxPro; in that you can select
which events you want to track and where to send the results (Figure 22).
Figure 20: Showing the Client Statistics with your Query
Figure 21: Starting a trace and selecting which events to Track in SQL Server Profiler
SQL Server Profiler has been supplanted in SQL Server 2008 by a new technology called
Extended Events (XEvents), but there’s no GUI for XEvents until SSMS 2012. XEvents
includes many more traces, as well as the ability to output to quite a few more targets,
including graphs and histograms. SQL Server Profiler has been officially deprecated, but it’s
still a useful tool for developers to get a handle on what’s going on inside SQL Server.
Go Off Script
One of the most difficult things that we’ll have to do as developers working with SQL Server
is keep the changes we make to our development environment in sync with what’s going on
in the live application (as well as a test environment, if we’re lucky enough to have one).
This means changes to the database schema as well as changes to the “code” included in the
database. You can spend some money on great 3rd party tools to help you manage this, but
here are a couple of tricks you can do using SSMS natively:
Script Your Databases
SSMS can generate all the code needed to recreate any and all of your databases, including
data, via scripting. You can then take the results and
compare them with previous version of your database or
store them in your version control system for an ad hoc
database version control.
To do this effectively, you don’t want to use the right
click, “Script Database As…” option however. There
aren’t enough options in there, you literally only get the
Figure 22: Profiler Results. Note this is from an application for which I don't have the Source Code!
script necessary to regenerate the database itself, not any tables, views, stored procedures,
etc. Instead, right click on the database name in Object Explorer and select Tasks | Generate
Scripts… ()
This will then walk you through a wizard that allows you to select which components of the
database you want scripted and gives you all sorts of options.
Bonus Tip: One option you’ll definitely want to turn off if you are going to compare
database schemas is the Include Descriptive Headers option. If you leave this on, you get
something like this at the top of each script:
/****** Object: Table [xxx].[xxx] Script Date: xxx ******/
Because the script date will be different every time you generate the script, this will be
flagged as a new version of the schema even if nothing else is changed, causing a bit of extra
chaos in your version control system.
Tip: I find myself using Beyond Compare so often that I added it to the Tools menu. You can
put any external tool you want on the menu via Tools | External Tools.
Programmatically Scripting
For views, stored procedures, and functions you can execute the sp_HelpText stored
procedure to have SSMS output the script used to create the object.
Another way to script programmatically is to use the SQLPubWiz.exe utility. This
command-line tool that comes with SQL Server allows you to generate output from the
database.
As a Visual FoxPro developer who uses SQL Server tables, I find it very helpful to call this
with a projecthook in my build process in order to generate a text file that I can then check
into my source control system. This helps me keep my development schema in sync with
the production server.
Go Commando
Speaking of command-line, you don’t have to drop to the SQL Command Line in order to
run scripts. By toggling into SQLCmd mode (Query | SQLCmd Mode), you can run
commands right from within the query window by starting the line with :R.
This is useful if, for example, you get sent a script (.SQL) file that’s too large for SSMS to
load into the editor window. (The limit of script size is available memory, so that may be a
pretty large script.) If you’re in SQLCmd mode can enter …
:R <scriptname>
…into the query window and it will execute that script name. I find this useful for those
times when someone sends me a large set of INSERT INTO commands in order to populate
the database (an alternative way of “backing up” I suppose, and one you can emulate by
choosing the “Script Data” option when you generate scripts).
Another handy command is :out, which redirects the output. Combine this with
sp_HelpText, for example, and you can dump the definition of anything right to a text file:
(The view definition of vEmployee is now in the file c:tempvEmployee.txt)
Viewing and Changing Your Data
Eventually it all comes down to the data itself, and sometimes the data isn’t quite right. In
Visual FoxPro we can just jump into a Browse window, but it’s not quite that easy in SQL
Server Management Studio.
Getting Data
The first thing we often do when we want to get a look at what kind of data is in our tables
is to right+click on the table and choose “SELECT TOP 1000 Rows” (by the way, that ‘1000’
is configurable in Tools | Options | SQL Server Object Explorer).
Getting Random Data
The problem with this approach is that the first 1,000 records in our table may not
accurately represent the data that’s in our table. After all it’s likely that those were the very
first records inserted into the table, back when our application was young or perhaps even
as an import from another system altogether.
Indeed it would be better to pull 1,000 random records out of the table, and there are a
couple of ways to do this. The easiest would be to append an ORDER BY NewId() clause to
the end of the query. Another way is to replace the TOP clause with the TABLESAMPLE
clause of the SELECT command, like this
SELECT * [AdventureWorks].[Person].[Contact] TABLESAMPLE (45 ROWS)
The TABLESAMPLE clause isn’t very precise though. It won’t likely return exactly how
many rows you ask for whether you ask for a specific number of rows or a percent of the
table.
Generating Random Data If you need to populate your development databases with some
random data and can’t get a copy of your live database, there are tools available that can
help you do that. It’s also possible to write scripts that can evaluate the schema of tables
and come up with suitable test data – hey you’re a developer, why not try to write
something like that?
Editing Specific Rows
If you want to change some data in your table, you could of course issue the UPDATE
command. For GUI editing, you can right+click on a table in Object Explorer click EDIT TOP
200 ROWS.
:out c:tempvEmployee.txt
sp_HelpText [HumanResources.vEmployee]
But what do you do in the (likely) event that the data you want to change isn’t in the TOP
200? It’d be great if you could just run any SELECT in the query window and then toggle
the output window into an Editable grid, but that just isn’t possible.
I suppose you could go to Tools | Options | SQL Server Object Explorer and enlarge the
sample size (or change it to 0 to get the entire table) but then you’d have to scroll down
among all the rows to find the rows you’re looking for. Eesh.
A much better solution is to click on the Show SQL Pane (Ctrl+3) and add a WHERE clause
to the SQL that pulled the data. Rerun the query (Ctrl+R this time, not Ctrl+E or F5) and you
can now edit a nice subset of records.
Debugging
First tip for debugging: You should never debug on a live server. In fact you as a developer
shouldn’t even have the sys_admin rights necessary to debug on a live server. Even if you
are the de facto sys admin, don’t use that login when you’re on the server as you’re opening
up yourself to the possibility of locking up that server while you figure out what’s wrong
with your code. Debug your scripts on a development server and deploy it live only after
it’s been tested, just like your regular code.
Debugging in SQL Server works just like debugging in Visual Studio. You can set
breakpoints, step through code, inspect variables, etc. And just like your regular code,
sometimes your scripts will throw an error.
Bonus Tip: You could turn your line numbering on (Tools | Options | Text Editor | Transact-
SQL) and scroll your way down to the line with the error, but SSMS makes it easier than that.
Simply double-click on the error message and SSMS will take you right to the line with the
error.
Learn Your Tool
Take the time to learn about what SQL Server provides for you in terms of built-in stored
procedures and functions. We already talked about sp_Help and sp_HelpText, but there is a
long list of System Stored Procedures available. There are also a ton of built-in global
Figure 23: Editing the Records of the Employees Born After 1980.
variables that start with @@ that are useful in your scripts (e.g. @@ROWCOUNT is useful
for returning the number of rows a query produced).
On the flip side, know what SSMS does not include and which 3rd Party tools fill in the gaps.
There are some great free utilities as well as commercial ones. RedGate of course is the first
name in 3rd party utilities for SQL Server, and I included a few in Appendix B.
Speaking of RedGate, they provide free eBooks for all sorts of topics at http://www.red-
gate.com/community/books/. Check that out along with some of these other links that I
found helpful when putting this list together.
There’s so much more to SSMS than I could cover here, but I hope this session opened up
some possibilities for making you more efficient when using this tool. This list gets larger
every time I give this session, so if you have ideas that you think I should add to this session
please get in touch via email or Twitter and I’ll definitely include them.
Appendix A: References
These websites and books were integral in compiling this list, as well as the users in the
Geek Lunch, MadFox, and ChicagoFUDG who listened to a preview of this session and
contributed to it.
 Full List of Keyboard Shortcuts: http://msdn.microsoft.com/en-
us/library/ms174205.aspx
 http://www.mssqltips.com/sqlservertip/2415/ssms-keyboard-shortcuts-part-2-of-
2/
 http://www.mssqltips.com/sqlservertip/2145/starting-your-sql-server-career-
path/?utm_source=dailynewsletter&utm_medium=email&utm_content=headline&u
tm_campaign=2012411
 http://www.databasejournal.com/features/article.php/3593466/MS-SQL-
Series.htm
 http://SQLServerCentral.com
 http://Blog.SQLAuthority.com
 http://http://www.mssqltips.com/
 http://www.codeproject.com/Articles/39131/Global-Variables-in-SQL-Server
 http://www.sqlservercurry.com/2011/08/net-developer-database-
knowledge.html
 http://SQLPass.com
Appendix B: Useful Free 3rd
Party Tool
There could easily be another session done just on great, free, 3rd party tools available for
SQL Server Management Studio. In fact, there is! I saw it done by Rick Krueger and Dave
Valentine at a SQL Saturday (great events, by the way).
Here’s a short list of some of the free 3rd party tools that I’m aware of:
 T-SQL Formatter: http://www.architectshack.com/PoorMansTSqlFormatter.ashx
and PoorSQL.com
 SSMS Tools Pack :http://www.ssmstoolspack.com/ (include Poor Man’s formatter)
 RedGate SQL Search http://www.redgate.com
 BIDS Helper http://bidshelper.codeplex.com
 SSMS Boost http://www.ssmsboost.com
There are many, many more, as well as excellent non-free tools.
Copyright, 2012, Eric Selje
Figure 1: New Project/Solution Dialog, with option for Source Control...............................4
Figure 2: Retroactive Source Control............................................................................................................4
Figure 3: Source Control Options for your Scripts...................................................................................4
Figure 4: You can't have two connections to the same server, and a manual workaround
doesn't help.............................................................................................................................................................5
Figure 5: The long list of every server ever ................................................................................................6
Figure 6: Add new query or "item" to project............................................................................................7
Figure 7: Adding a new ITEM allows you to select from a plethora of script templates...........7
Figure 8: The "Restore Database" script, in the project and properly name.................................7
Figure 9: Projects show in the QuickList, and your favorites can be pinned.................................8
Figure 10: Filtering Long Lists.........................................................................................................................9
Figure 11: Object Explorer Details Pane................................................................................................... 10
Figure 12: The "List Structure" of the SQL Server world.................................................................... 11
Figure 13: These Items are Dependents ................................................................................................... 12
Figure 14: This Item Claims These Dependents..................................................................................... 12
Figure 15: Database Diagram........................................................................................................................ 13
Figure 16: Set your own Keyboard Shortcuts......................................................................................... 14
Figure 17: Help SSMS Help You.................................................................................................................... 15
Figure 18: ScreenTip with shortcut............................................................................................................ 15
Figure 19: An Estimated Execution Plan with One Operation Highlighted................................. 16
Figure 20: Showing the Client Statistics with your Query ................................................................. 18
Figure 21: Starting a trace and selecting which events to Track in SQL Server Profler......... 18
Figure 22: Profiler Results. Note this is from an application for which I don't have the
Source Code! ........................................................................................................................................................ 19
Figure 23: Editing the Records of the Employees Born After 1980. .............................................. 22

More Related Content

Similar to Selje_SSMS for the Accidental DBA.pdf

Migrate Access to SQL Server/Azure
Migrate Access to SQL Server/AzureMigrate Access to SQL Server/Azure
Migrate Access to SQL Server/Azure
ADNUG
 
Common Database Challenges faced by DevOps team and how to solve them
Common Database Challenges faced by DevOps team and how to solve themCommon Database Challenges faced by DevOps team and how to solve them
Common Database Challenges faced by DevOps team and how to solve them
Muhammad Imran Riaz
 
Database Basics Taac 2005
Database Basics Taac 2005Database Basics Taac 2005
Database Basics Taac 2005
AmyBlankenship
 
SELJE_Database_Unit_Testing.pdf
SELJE_Database_Unit_Testing.pdfSELJE_Database_Unit_Testing.pdf
SELJE_Database_Unit_Testing.pdf
Eric Selje
 
Care and feeding notes
Care and feeding notesCare and feeding notes
Care and feeding notes
Perrin Harkins
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
PVS-Studio
 
Introduction to sql server
Introduction to sql serverIntroduction to sql server
Introduction to sql serverVinay Thota
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#
Michael Heron
 
Installing ms sql server 2012 express edition
Installing ms sql server 2012 express editionInstalling ms sql server 2012 express edition
Installing ms sql server 2012 express editionWally Pons
 
4) databases
4) databases4) databases
4) databasestechbed
 
CIT499 Semester Project
CIT499 Semester ProjectCIT499 Semester Project
CIT499 Semester Project
dumwalke
 
MS SQL SERVER: Using the data mining tools
MS SQL SERVER: Using the data mining toolsMS SQL SERVER: Using the data mining tools
MS SQL SERVER: Using the data mining tools
DataminingTools Inc
 
MS SQL SERVER: Using the data mining tools
MS SQL SERVER: Using the data mining toolsMS SQL SERVER: Using the data mining tools
MS SQL SERVER: Using the data mining tools
sqlserver content
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Alicia Buske
 
Access tips access and sql part 4 building select queries on-the-fly
Access tips  access and sql part 4  building select queries on-the-flyAccess tips  access and sql part 4  building select queries on-the-fly
Access tips access and sql part 4 building select queries on-the-fly
quest2900
 
Sql interview question part 8
Sql interview question part 8Sql interview question part 8
Sql interview question part 8
kaashiv1
 
Enhance Your Flask Web Project With a Database Python Guide.pdf
Enhance Your Flask Web Project With a Database  Python Guide.pdfEnhance Your Flask Web Project With a Database  Python Guide.pdf
Enhance Your Flask Web Project With a Database Python Guide.pdf
Inexture Solutions
 

Similar to Selje_SSMS for the Accidental DBA.pdf (20)

Migrate Access to SQL Server/Azure
Migrate Access to SQL Server/AzureMigrate Access to SQL Server/Azure
Migrate Access to SQL Server/Azure
 
Common Database Challenges faced by DevOps team and how to solve them
Common Database Challenges faced by DevOps team and how to solve themCommon Database Challenges faced by DevOps team and how to solve them
Common Database Challenges faced by DevOps team and how to solve them
 
Database Basics Taac 2005
Database Basics Taac 2005Database Basics Taac 2005
Database Basics Taac 2005
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
SELJE_Database_Unit_Testing.pdf
SELJE_Database_Unit_Testing.pdfSELJE_Database_Unit_Testing.pdf
SELJE_Database_Unit_Testing.pdf
 
Care and feeding notes
Care and feeding notesCare and feeding notes
Care and feeding notes
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
 
Introduction to sql server
Introduction to sql serverIntroduction to sql server
Introduction to sql server
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#
 
Installing ms sql server 2012 express edition
Installing ms sql server 2012 express editionInstalling ms sql server 2012 express edition
Installing ms sql server 2012 express edition
 
4) databases
4) databases4) databases
4) databases
 
CIT499 Semester Project
CIT499 Semester ProjectCIT499 Semester Project
CIT499 Semester Project
 
MS SQL SERVER: Using the data mining tools
MS SQL SERVER: Using the data mining toolsMS SQL SERVER: Using the data mining tools
MS SQL SERVER: Using the data mining tools
 
MS SQL SERVER: Using the data mining tools
MS SQL SERVER: Using the data mining toolsMS SQL SERVER: Using the data mining tools
MS SQL SERVER: Using the data mining tools
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
 
Access tips access and sql part 4 building select queries on-the-fly
Access tips  access and sql part 4  building select queries on-the-flyAccess tips  access and sql part 4  building select queries on-the-fly
Access tips access and sql part 4 building select queries on-the-fly
 
Sql interview question part 8
Sql interview question part 8Sql interview question part 8
Sql interview question part 8
 
Ebook8
Ebook8Ebook8
Ebook8
 
Enhance Your Flask Web Project With a Database Python Guide.pdf
Enhance Your Flask Web Project With a Database  Python Guide.pdfEnhance Your Flask Web Project With a Database  Python Guide.pdf
Enhance Your Flask Web Project With a Database Python Guide.pdf
 

More from Eric Selje

SELJE - VFP and IT Security.pptx
SELJE - VFP and IT Security.pptxSELJE - VFP and IT Security.pptx
SELJE - VFP and IT Security.pptx
Eric Selje
 
SELJE - VFP and IT Security.pdf
SELJE - VFP and IT Security.pdfSELJE - VFP and IT Security.pdf
SELJE - VFP and IT Security.pdf
Eric Selje
 
SELJE - VFP Advanced.pdf
SELJE - VFP Advanced.pdfSELJE - VFP Advanced.pdf
SELJE - VFP Advanced.pdf
Eric Selje
 
SELJE - VFP Advanced.pptx
SELJE - VFP Advanced.pptxSELJE - VFP Advanced.pptx
SELJE - VFP Advanced.pptx
Eric Selje
 
SELJE - Look at X Sharp.pptx
SELJE - Look at X Sharp.pptxSELJE - Look at X Sharp.pptx
SELJE - Look at X Sharp.pptx
Eric Selje
 
SELJE - Look at X Sharp.pdf
SELJE - Look at X Sharp.pdfSELJE - Look at X Sharp.pdf
SELJE - Look at X Sharp.pdf
Eric Selje
 
OneNote to Rule Them All.pdf
OneNote to Rule Them All.pdfOneNote to Rule Them All.pdf
OneNote to Rule Them All.pdf
Eric Selje
 
FoxUnit in Depth.pptx
FoxUnit in Depth.pptxFoxUnit in Depth.pptx
FoxUnit in Depth.pptx
Eric Selje
 
OneNote to Rule Them All Slides.pptx
OneNote to Rule Them All Slides.pptxOneNote to Rule Them All Slides.pptx
OneNote to Rule Them All Slides.pptx
Eric Selje
 
SELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdfSELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdf
Eric Selje
 
Selje_SSMS (Slides).pdf
Selje_SSMS (Slides).pdfSelje_SSMS (Slides).pdf
Selje_SSMS (Slides).pdf
Eric Selje
 
Selje_Fox on the Run.ppt
Selje_Fox on the Run.pptSelje_Fox on the Run.ppt
Selje_Fox on the Run.ppt
Eric Selje
 
Selje_Fox on the Run.pdf
Selje_Fox on the Run.pdfSelje_Fox on the Run.pdf
Selje_Fox on the Run.pdf
Eric Selje
 
Selje_Extending Web Apps.ppt
Selje_Extending Web Apps.pptSelje_Extending Web Apps.ppt
Selje_Extending Web Apps.ppt
Eric Selje
 
Selje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdfSelje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdf
Eric Selje
 
Don't Be a Target!
Don't Be a Target! Don't Be a Target!
Don't Be a Target!
Eric Selje
 
Energy audit tablet screenshots
Energy audit tablet screenshotsEnergy audit tablet screenshots
Energy audit tablet screenshots
Eric Selje
 

More from Eric Selje (17)

SELJE - VFP and IT Security.pptx
SELJE - VFP and IT Security.pptxSELJE - VFP and IT Security.pptx
SELJE - VFP and IT Security.pptx
 
SELJE - VFP and IT Security.pdf
SELJE - VFP and IT Security.pdfSELJE - VFP and IT Security.pdf
SELJE - VFP and IT Security.pdf
 
SELJE - VFP Advanced.pdf
SELJE - VFP Advanced.pdfSELJE - VFP Advanced.pdf
SELJE - VFP Advanced.pdf
 
SELJE - VFP Advanced.pptx
SELJE - VFP Advanced.pptxSELJE - VFP Advanced.pptx
SELJE - VFP Advanced.pptx
 
SELJE - Look at X Sharp.pptx
SELJE - Look at X Sharp.pptxSELJE - Look at X Sharp.pptx
SELJE - Look at X Sharp.pptx
 
SELJE - Look at X Sharp.pdf
SELJE - Look at X Sharp.pdfSELJE - Look at X Sharp.pdf
SELJE - Look at X Sharp.pdf
 
OneNote to Rule Them All.pdf
OneNote to Rule Them All.pdfOneNote to Rule Them All.pdf
OneNote to Rule Them All.pdf
 
FoxUnit in Depth.pptx
FoxUnit in Depth.pptxFoxUnit in Depth.pptx
FoxUnit in Depth.pptx
 
OneNote to Rule Them All Slides.pptx
OneNote to Rule Them All Slides.pptxOneNote to Rule Them All Slides.pptx
OneNote to Rule Them All Slides.pptx
 
SELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdfSELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdf
 
Selje_SSMS (Slides).pdf
Selje_SSMS (Slides).pdfSelje_SSMS (Slides).pdf
Selje_SSMS (Slides).pdf
 
Selje_Fox on the Run.ppt
Selje_Fox on the Run.pptSelje_Fox on the Run.ppt
Selje_Fox on the Run.ppt
 
Selje_Fox on the Run.pdf
Selje_Fox on the Run.pdfSelje_Fox on the Run.pdf
Selje_Fox on the Run.pdf
 
Selje_Extending Web Apps.ppt
Selje_Extending Web Apps.pptSelje_Extending Web Apps.ppt
Selje_Extending Web Apps.ppt
 
Selje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdfSelje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdf
 
Don't Be a Target!
Don't Be a Target! Don't Be a Target!
Don't Be a Target!
 
Energy audit tablet screenshots
Energy audit tablet screenshotsEnergy audit tablet screenshots
Energy audit tablet screenshots
 

Recently uploaded

RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Zilliz
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 

Recently uploaded (20)

RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 

Selje_SSMS for the Accidental DBA.pdf

  • 1. SSMS for the Accidental DBA Eric Selje Geeks and Gurus, Inc. 1308 Spring Street Madison, WI 53711 Voice: 608/213-9567 Twitter: EricSelje Email: eselje@geeksandgurus.com You're a database application developer who's using SQL Server now, but you're no DBA. Sure you use SQL Server Management Studio (SSMS), and maybe you're even pretty good at designing tables and executing queries. But there's a whole lot more functionality in this seemingly simple program than you may realize. In this session we'll share features in SSMS that you may have overlooked but will make your life as a developer a lot easier.
  • 2. You Are a DBA A lot of us Visual FoxPro developers didn’t plan it, but we ended up becoming “accidental” DBAs. It may happen organically: our application grew until we reached the point where we needed to migrate the database from Visual FoxPro tables to a “real” database. Other times we’re thrust into an existing project that already has all the data in a back-end database. For Visual FoxPro developers who have grown comfortable in the Microsoft environment, SQL Server is the natural choice for the back-end database. And since the free SQL Server Express version was released a few years ago, many developers have chosen to forego FoxPro’s native database and start directly with that. Its limitation of 10 GB per database is usually ample for our Visual FoxPro applications, which were effectively capped at 2GB. There are other options available to us, including the intriguing SQLAnywhere from Sybase, the open source MySQL and PostgreSQL, and of course the big boys Informix and Oracle. Some of the concepts presented in this paper may well be applicable to those database engines as well, but this guide is focused on SQL Server Management Studio (SSMS). The ideas will be applicable to all versions of Microsoft SQL Server up to 2012, including the Express versions. The screenshots and examples are done in the version that is currently most popular, SSMS 2008. This whitepaper is not a comprehensive how-to guide for SQL Server. It will not teach you everything you know to become a SQL Server DBA or even how to get started with SQL Server. If you need a starting reference, Microsoft Press offers the free eBook “Introducing SQL Server 2012” at their site (http://www.microsoft.com/sqlserver/en/us/default.aspx). I’m going to assume you’ve already got SQL Server installed either locally or on a server (including Azure) and already have some databases installed. If you don’t have any SQL Server databases yet, you can download the sample databases from Microsoft including the ubiquitous and oft-cited “Northwind” database and the newer and more complex “AdventureWorks” database, which I’ll be using in this paper. This document contains tips and tricks for database developers who are not full time DBAs but are using SQL Server Management Studio regularly and want to go beyond the basics and explore some of the power of this seemingly-simple tool. These are tips that I’ve jotted down as I’ve used it as well as many that I’ve collected from other users on blogs, in user groups, and even while presenting this session at SQL Saturdays in my area. So here then I present to you my Top Tips in SSMS for the Accidental DBA.
  • 3. Get Organized With Solutions and Projects Can you imagine using Visual FoxPro without using the Project Manager? Perhaps many of you can remember the time before that tool was introduced, with PRG files scattered hither and yon. Remember then the feeling of power and organization you got when you first encountered the Project Manager in FoxPro? Using “Solutions” in SMSS is similar to using projects in VFP, and exactly like using Solutions in Visual Studio (because SSMS is actually built using the same IDE as Visual Studio, which will be a recurring theme in this document). Solutions are the way to organize all of the little snippets of SQL that you don’t keep in your database. These might be utility scripts that you use often for wiping out or adding in test data, tests you’ve written to verify your database’s stored procedures, or whatever other miscellaneous thing you have. Surprisingly many users of SQL Server Management Studio, including full time DBAs, don’t take advantage of Solutions and Projects in SSMS. Instead they rely on the file system to organize their odd collection of scripts that remain outside of the database proper. If you don’t believe me just watch any of the training videos available on the SQL PASS (Professional Association for SQL Server) website and you’ll see plenty of opportunities for the presenters to use Solutions to organize their scripts, and yet they don’t do it. Part of the problem may be that the Solution Explorer is not visible by default in SSMS, so let’s start by making that visible by choosing View | Solution Explorer. It’s important to note that Solutions are stored in the file system and not in the database, so if you want to share them with your co-developers you need to save the solutions in a shared space. However because they’re stored as ASCII files, you can add them to a Source Control provider (unlike the stored procedures and functions in the database, though there are 3rd Party Tools to add those into a version control system as well. That’s beyond the scope of this paper). To create a new Solution in SSMS, you (counter intuitively) select File | New Project from the menu. On that dialog (Figure 1) you’ll have the option to create a new solution or add the new project to an existing solution. Solutions can contain multiple projects. This is where you indicate the Source Control provider, if you’ve installed one SSMS via the Tools | Options | Source Control dialog (Figure 3). If you don’t initially hook up your solution to a version control provider, you can go back later and right click on the project to add it (Error! Reference source not found.).
  • 4. Figure 3: Source Control Options for your Scripts Figure 1: New Project/Solution Dialog, with option for Source Control Figure 2: Retroactive Source Control
  • 5. A solution can contain many projects, and each project contains three types of objects: Connections (to a database) Queries (T-SQL scripts) “Miscellaneous” (whatever you want) Connections hold a, you guessed it, connection to a server. Each project can hold as many connections as you want, but only one for each named server/login combination which means I can’t have one to the AdventureWorks database on my local server, and another one to the AdventureWorks2008 database on my local server in the same project. When you add a connection you get a dialog® that you probably recognize (Figure 4, upper left). Here you specify the server you want to connect to, the authentication method, and optionally but optimally the default database name (on the Connection Properties tab). It is a little frustrating that you can’t add more than one connection to the same server with the same login. You can get around this limitation by creating new logins or aliasing your Figure 4: You can't have two connections to the same server, and a manual workaround doesn't help.
  • 6. database different ways but in the end SSMS might be saving us from some self-inflicted confusion here. I’d prefer to have the option though. I tried to be clever and manually modify the actual text file that holds the project (Figure 4, upper right), but changing the ConnectionNode “name” attribute is not what shows up in the tree view of the connection (Figure 4, bottom), and now I’m really confused about which connection is for which database. I think it might be best to just live within SSMS’s restriction until they include the ability to rename a connection. As a recommended practice, include connections to point to each client’s Live Production server, their Test server, and Development database server in a project. Set the default database for each connection. This saves me a ton of time over trying to find the server in my usual “Connect” dialog’s long list of servers (Error! Reference source not found.). What saves even more time however is that by double clicking on a connection in my project I’m immediately brought to a New Query window, connected to the right server and defaulting to the right database in one easy step. Queries or more accurately, “scripts” organize the .SQL files for your database. These are not the stored procedures, of course, as they are contained in the database itself. The scripts are the miscellanea that you might use to automate repetitive tasks or tests. For example you might have a script that SELECTs all columns from your largest table. Why would you want a script to do this? So that when your database goes down you have a quick way of “priming” the cache memory of the server with data in order to speed up subsequent queries. This could be a stored procedure as well, but do you really want a stored procedure that does this? Another good script to have ready to go at all times is one that restores the database. It wouldn’t make any sense to have this as a stored procedure, since you can’t get at the stored procedures if the database is down. Adding queries to the project can be done one of three ways. If you simply right+click on the Queries folder and select “New Query” (or double-click, as mentioned) you’ll get a blank tab where you can start scripting away. It will give a generic sequential name and automatically be included in your project, so once you’re happy with your script you’ll have to manually rename it to something meaningful. Be sure to keep the .SQL extension or SSMS will move it from Queries to Miscellaneous. Figure 5: The long list of every server ever
  • 7. You can also right+click on the Project and select Add | New Query (Figure 6Error! Reference source not found.) to accomplish the same thing. The other way to add a query to your project is to right+click on the Project itself and choose Add | New Item… (also Figure 6). By choosing this option you will see a dialog (Figure 7) that is chock full of Query Templates that you can use to do routine tasks, such as the aforementioned Database Restore script. It also lets you name the query immediately rather than having to remember to do it afterwards, and it defaults to a meaningful name. This is a great way to get a head start on any T-SQL script, because who can ever remember anything beyond the everyday syntax? Figure 6: Add new query or "item" to project Figure 7: Adding a new ITEM allows you to select from a plethora of script templates Figure 8: The "Restore Database" script, in the project and properly name
  • 8. The Miscellaneous group under the project holds any file that doesn’t have a .SQL extension. That could be notes to yourself, task lists, Analysis Services Queries (if that’s your thing, but way beyond the scope), etc. Don’t put anything sensitive in here, as these are just files stored on your drive and aren’t encrypted or protected in any way. Solutions are an excellent organizational tool. Use them. One shortcoming of solutions is that you can only have one open at a time. But since a solution can contain multiple projects, what works for me is to have one solution called “All Clients,” and then have a separate project for each client. That way everything I need is available to me without opening and closing multiple solutions. . Figure 9: Projects show in the QuickList, and your favorites can be pinned. Bonus tip: When you use solutions in Windows Vista and up, the solution is available to you via a “QuickList” (Figure 9). You can even pin your favorite(s) to make sure they don’t drop off the list. Find that Needle Developers, and consultants particularly, are often called in to quickly troubleshoot a database they’ve never even seen before. When time is of the essence these tips will help you quickly discover what’s going on inside the database. If you’re paid by the hour and your client has an unlimited budget, you can ignore this section. Filter, Don’t Search Nothing will slow you down quite like scrolling through a long list of objects in the Object Explorer (Figure 10, Left), trying to find the one thing that you’re looking for. Instead, right click on the category you’re looking for and click “Filter Settings”. You can then filter out
  • 9. the list not just by the name, schema, owner, or creation date. So you can show, for example, all the views created in the last month. Figure 10: Filtering Long Lists Search, Don’t Filter Filters unfortunately aren’t that powerful. For example you might want to see the views modified in the last 30 days, and you might want that list in the Output window. For cases like that you cannot merely filter because a) modified date isn’t one of the fields you can filter on for views, and b) the results are only in the filtered list and that doesn’t lend itself to output. You’re going to need to query the metadata of the database. SQL Server keeps everything about itself in SQL Server itself, which you can then query. To get that aforementioned list, you can issue this command in the Query Window: Example 1: Get views modified within the last 30 days. SELECT OBJECT_NAME(object_id), * FROM sys.views WHERE views.modify_date > GETDATE()-30 You can now export that output into any number of formats (more on that later). Bonus Tip: Hey, that’s a handy query! Save it in your project.
  • 10. Here’s another handy search, which will list all of the objects in the database that have the string ‘txtCounty’, a field that I’m interested in because my application uses it: Example 2: Show me every module (function, stored procedure, triggers, view) that has needs the ‘Email’ field. SELECT OBJECT_NAME(object_id), * FROM sys.sql_modules WHERE definition LIKE '%Email%' What other metadata can you query? The system views in the sys schema can give up just about all the information about the database, including tables, columns, views, stored procedures, indexes, triggers, partitions, and so much more. Just try typing… SELECT * FROM sys. …and look at the long list in the Intellisense. Bonus Tip: RedGate makes a ton of excellent tools, most of which cost money. SQL Search makes querying SQL Server as easy as GoFish makes querying Visual FoxPro, and it is free on RedGate.com The Devil’s in the Details Well, maybe. But you won’t know unless you view the details. Hit F7 (or View | Object Explorer Details) to do that, and you’ll see the details of whatever category you highlight in the Object Explorer. Select “Tables” and you’ll see list of all of the tables, along with the schema, row count, and creation date (Figure 11). Select “Columns” and you’ll see a list of all the columns for that table. Select … well you get the idea. Notice the toolbar at the top of the Object Explorer Details pane. There’s a “Search” pane here that allows you filter the results list to quickly find what you’re looking for. But wait, there’s more! Right+click on the column headings and you can add columns for Data Space Used (table size), a handy way to see how big your tables are. Unfortunately there isn’t a “Last Update” column, so it still has a little ways to go before catching up with Visual Foxpro’s “DIR” command. And speaking of FoxPro tables, here’s a quick way in SQL Server to get something approximately equal to the LIST STRUCTURE command. Figure 11: Object Explorer Details Pane
  • 11. 1. In a Query window, type in the name of a table. Fully qualify it if it’s not in the ‘dbo’ schema of the current database (a quick way to do this is to just right+click the table and choose “Select Top 1000 Rows”). 2. Highlight the complete name of the table in the query window by double-clicking on it. If it has the schema name in it, it must be encased in square brackets. 3. Hit Alt+F1. The schema of the table and more will appear in the results window (Figure 12). This looks good in a grid, but might be extra useful if you send the results to text or to a file, where they could be shared with someone, searched, or archived. Bonus Tip: If you hit Alt+F1 and get a very large unexpected resultset back, you didn’t have anything highlighted and thus got the schema for the entire database and not just the table you were looking for. That may also be handy. We’ll talk more about System Stored Procedures later, but for fun try highlighting different things and hitting Alt+F1. What kind of magic is this? Alt+F1 is really just a shortcut (see Figure 16) to a System Stored Procedure named sp_help. We could have manually just typed in sp_help [database.schema.table] in our query window, but that takes away the magic. Figure 12: The "List Structure" of the SQL Server world.
  • 12. Claim those Dependencies Have you ever thought right before you change the schema of a table, “I wonder what this is going to break?” Wouldn’t it be nice to see which views and stored procedures are going to be affected by your change to a table? In SSMS, just right+click and select View Dependencies and you will get that very information (Figure 13). Conversely, if you have a large stored procedure and don’t want to have to thoroughly peruse it to see which tables it uses, right+click on it and select View Dependencies, and then toggle the option at the top to “Objects on which [procedure] depends (Figure 14). Get the Big Picture If you’re a visual person, you’ll appreciate the ability of SSMS to provide you with a visual interpretation of the entire database, or a subset thereof. Simply right+click the Database Diagrams node in Object Explorer and select New Database Diagram. Then add all the tables from your database into your diagram (). Tip: You can also drag table names from the Object Explorer and drop them in your diagram later. Don’t worry about placing the tables nicely, because when you’ve got all the tables you want loaded, you can simply right+click on the diagram’s canvas and select Arrange Tables, and SSMS will lay them out nicely. By default SSMS shows you the names of the columns and the relationship lines between the tables, but you can configure this. For example if you hit Ctrl+A to select all of the tables, then right+click on a table name and select Table View | Standard, you’ll see the data types and the nullability of the tables as well. You can also right+click on the canvas and select Show Relationship Labels to toggle those on or off. Figure 13: These Items are Dependents Figure 14: This Item Claims These Dependents
  • 13. One thing you should be aware of is these diagrams are “live” in the sense that you can change the schema by changing the diagram! Thoughtfully, SSMS asks us to save and warns us the tables are going to be updated. Viewing a database diagram is a quick way to ascertain a database’s schema. Figure 15: Database Diagram Quicken the Pace There are an enormous number of shortcuts to get around SSMS quickly. The first thing a developer needs to know is that many of them are the same ones as available in Visual Studio (again, because they’re based on the same IDE framework). So if you want to comment a block of code in a T-SQL query or stored procedure, just hit Ctrl+K, C. I could go on, but there’s a full list of SSMS shortcuts available at http://msdn.microsoft.com/en- us/library/ms174205.aspx that you can peruse. Here are some that I find myself using all the time. Ctrl+E: Execute the current query. This one seems so obvious that I’m almost afraid to mention it, but I see enough people that do this the hard way (Query | Execute) that I feel I must mention it. You can also hit F5, which is the same as running your app in Visual Studio.
  • 14. Ctrl+U: This one probably saves more total time than any other. How many times have you typed a query, say SELECT * FROM MyTable, only to have SQL Server come back and say “Could not find MyTable.” Argh. Of course not! Because MyTable is actually in a database that’s not the “current” database. You could type USE database before you’re SELECT (that’s the equivalent of SET DATABASE TO and a little counterintuitive for us FoxPro folks). Or you could spell out the entire name of the table, a la SELECT * FROM MyDatabase.MySchema.MyTable, but that’s a lot of typing and you don’t want to have to do that every time. The quickest way is to just indicate to SSMS which database you’d like to be current, and there’s a dropdown for that right in the toolbar. But rather than reach for that mouse, just hit Ctrl+U, start typing the name of the database you want to be current, and then hit Enter to jump back into your query. Ctrl+W: Another one that’s completely counterintuitive for a FoxPro coder, Ctrl+W selects the word under the cursor. I find this handy for deleting fields, parameters, or any other extraneous optional fields in my code. Keep this one in mind and you’ll find yourself using it quite a bit, especially in combination with that Alt+F1 shortcut from earlier. Tip: If there’s not a shortcut for your favorite stored procedure, you can create one yourself with Tools | Options, Keyboard, under Query Shortcuts (Figure 16). Here it also becomes clear why Alt+F1 fired the sp_help stored procedure! It can be your own stored procedure or a System Stored Procedure. For a complete list of available System Stored Procedures, simply expand the Programmability | Stored Procedures | System Stored Procedures in your database’s Object Explorer. Whatever is highlighted will become the first parameter sent to the stored procedure. Figure 16: Set your own Keyboard Shortcuts
  • 15. Bonus Tip: An easy way to learn the SSMS shortcuts is to have SSMS tell you what they are. It will, but this feature is turned off by default. To turn it back on, select Tools | Customize (Figure 17), and check the box to show ScreenTips and the box to show Shortcut Keys. Then you’ll get hints to what things do and any shortcut that might help you do it quicker (Figure 18). Mouse Shortcuts You never have to type the name of a database, table or column again. Simply drag the name over from the Object Explorer and SSMS will insert the name for you. When you drag a table name, it doesn’t put the database name in so you may have to use the Ctrl+U trick to set the database to the current table. While you’re looking at the table in Object Explorer, you can drag the word Columns over to the query window and SSMS will insert the name of each and every column in the table. You can then use the Ctrl+W trick to remove any columns you don’t want. Another handy thing you can do with your mouse is Alt+Select, which allows you to select a rectangle of text and then manipulate within that rectangle. You can delete it, move it over, or search/replace within that selection. This is very handy when you want remove an alias in front of a set of column fields, for instance. Figure 17: Help SSMS Help You Figure 18: ScreenTip with shortcut
  • 16. Science! SQL Server Management Studio includes much better tools for analyzing what’s going on behind the scenes than Visual FoxPro does. Learning to use those tools to their full potential is the subject of entire books, but be aware that they’re there and what they do. Display Actual Execution Plans Vaguely reminiscent of VFP’s SYS(3054), the Execution Plans (Figure 19) shows exactly how SQL Server processed your query. You can include that along with the query results by hitting Ctrl+M before running your query. Alternatively you can choose to display the Estimated Execution Plan instead. With an Estimated Plan, you don’t actually have to run the query in order to see what SQL Server may do with your query. This is great for avoiding long running queries, but it may not be entirely accurate. Figure 19: An Estimated Execution Plan with One Operation Highlighted
  • 17. Things to Look For in Execution Plans Just like FoxPro, you want to see indexes being used for as much as possible. There’s a real science to interpreting Execution Plans, but a here are some tips: (Clustered) Index Seek: This means SQL Server is going to use an Index, which is of course desirable. It may use the “Clustered” index (which stores not just the key but also all of fields in the table, which is why there can be only one per table) or not. Things to Avoid (Clustered) Table Scans: This means your entire table had to be searched in order to find the values you wanted. A large table means slow results and an index on the WHERE value needs to be added. Key Lookups/Nested Loops: This means the query had to go back to the clustered index in order to retrieve the fields you wanted. If this is a query you run often, consider adding the fields you need as “covered” fields in the index that was used. For a great read on interpreting execution plans, I recommend Grant Fritchley’s “SQL Server Execution Plans.” View Client Statistics Ever wonder if it’s quicker to run a query one way or another? SSMS provides a fantastic tool for accurately comparing the execution times of your queries. In Visual FoxPro we might try doing this by storing the DATETIME(), running the query, and then subtracting the DATETIME() again afterwards. Toggle the Client Statistics (Query | Include Client Statistics, or Shift+Alt+S) to have this all done for you (Figure 20). Run a query once, change it around, then run it again. Do it a few times. You’ll see how long everything took, trends, and even an average column. No more guessing or going by feel.
  • 18. SQL Server Profiler While technically not part of SSMS, SQL Server Profiler is another tool that developers should keep in their belt. It’s particularly useful for those “black box” applications you inherit and you have no idea what’s going on inside (perhaps you don’t even have the source code), but it’s also great for figuring out which queries your Visual FoxPro application are making through SQLExec() or remote views that are taking so long. SQL Server Profiler comes with full version of SQL Server (not Express), but you can download the trial version of the full version and it works fine. You can quickly access it from the Tools menu in SQL Server Management Studio. Once loaded (Figure 21), you set up a “trace” that will log the inner happenings of the server. This is kind of similar to the Event Tracking feature in Visual FoxPro; in that you can select which events you want to track and where to send the results (Figure 22). Figure 20: Showing the Client Statistics with your Query Figure 21: Starting a trace and selecting which events to Track in SQL Server Profiler
  • 19. SQL Server Profiler has been supplanted in SQL Server 2008 by a new technology called Extended Events (XEvents), but there’s no GUI for XEvents until SSMS 2012. XEvents includes many more traces, as well as the ability to output to quite a few more targets, including graphs and histograms. SQL Server Profiler has been officially deprecated, but it’s still a useful tool for developers to get a handle on what’s going on inside SQL Server. Go Off Script One of the most difficult things that we’ll have to do as developers working with SQL Server is keep the changes we make to our development environment in sync with what’s going on in the live application (as well as a test environment, if we’re lucky enough to have one). This means changes to the database schema as well as changes to the “code” included in the database. You can spend some money on great 3rd party tools to help you manage this, but here are a couple of tricks you can do using SSMS natively: Script Your Databases SSMS can generate all the code needed to recreate any and all of your databases, including data, via scripting. You can then take the results and compare them with previous version of your database or store them in your version control system for an ad hoc database version control. To do this effectively, you don’t want to use the right click, “Script Database As…” option however. There aren’t enough options in there, you literally only get the Figure 22: Profiler Results. Note this is from an application for which I don't have the Source Code!
  • 20. script necessary to regenerate the database itself, not any tables, views, stored procedures, etc. Instead, right click on the database name in Object Explorer and select Tasks | Generate Scripts… () This will then walk you through a wizard that allows you to select which components of the database you want scripted and gives you all sorts of options. Bonus Tip: One option you’ll definitely want to turn off if you are going to compare database schemas is the Include Descriptive Headers option. If you leave this on, you get something like this at the top of each script: /****** Object: Table [xxx].[xxx] Script Date: xxx ******/ Because the script date will be different every time you generate the script, this will be flagged as a new version of the schema even if nothing else is changed, causing a bit of extra chaos in your version control system. Tip: I find myself using Beyond Compare so often that I added it to the Tools menu. You can put any external tool you want on the menu via Tools | External Tools. Programmatically Scripting For views, stored procedures, and functions you can execute the sp_HelpText stored procedure to have SSMS output the script used to create the object. Another way to script programmatically is to use the SQLPubWiz.exe utility. This command-line tool that comes with SQL Server allows you to generate output from the database. As a Visual FoxPro developer who uses SQL Server tables, I find it very helpful to call this with a projecthook in my build process in order to generate a text file that I can then check into my source control system. This helps me keep my development schema in sync with the production server. Go Commando Speaking of command-line, you don’t have to drop to the SQL Command Line in order to run scripts. By toggling into SQLCmd mode (Query | SQLCmd Mode), you can run commands right from within the query window by starting the line with :R. This is useful if, for example, you get sent a script (.SQL) file that’s too large for SSMS to load into the editor window. (The limit of script size is available memory, so that may be a pretty large script.) If you’re in SQLCmd mode can enter … :R <scriptname> …into the query window and it will execute that script name. I find this useful for those times when someone sends me a large set of INSERT INTO commands in order to populate the database (an alternative way of “backing up” I suppose, and one you can emulate by choosing the “Script Data” option when you generate scripts).
  • 21. Another handy command is :out, which redirects the output. Combine this with sp_HelpText, for example, and you can dump the definition of anything right to a text file: (The view definition of vEmployee is now in the file c:tempvEmployee.txt) Viewing and Changing Your Data Eventually it all comes down to the data itself, and sometimes the data isn’t quite right. In Visual FoxPro we can just jump into a Browse window, but it’s not quite that easy in SQL Server Management Studio. Getting Data The first thing we often do when we want to get a look at what kind of data is in our tables is to right+click on the table and choose “SELECT TOP 1000 Rows” (by the way, that ‘1000’ is configurable in Tools | Options | SQL Server Object Explorer). Getting Random Data The problem with this approach is that the first 1,000 records in our table may not accurately represent the data that’s in our table. After all it’s likely that those were the very first records inserted into the table, back when our application was young or perhaps even as an import from another system altogether. Indeed it would be better to pull 1,000 random records out of the table, and there are a couple of ways to do this. The easiest would be to append an ORDER BY NewId() clause to the end of the query. Another way is to replace the TOP clause with the TABLESAMPLE clause of the SELECT command, like this SELECT * [AdventureWorks].[Person].[Contact] TABLESAMPLE (45 ROWS) The TABLESAMPLE clause isn’t very precise though. It won’t likely return exactly how many rows you ask for whether you ask for a specific number of rows or a percent of the table. Generating Random Data If you need to populate your development databases with some random data and can’t get a copy of your live database, there are tools available that can help you do that. It’s also possible to write scripts that can evaluate the schema of tables and come up with suitable test data – hey you’re a developer, why not try to write something like that? Editing Specific Rows If you want to change some data in your table, you could of course issue the UPDATE command. For GUI editing, you can right+click on a table in Object Explorer click EDIT TOP 200 ROWS. :out c:tempvEmployee.txt sp_HelpText [HumanResources.vEmployee]
  • 22. But what do you do in the (likely) event that the data you want to change isn’t in the TOP 200? It’d be great if you could just run any SELECT in the query window and then toggle the output window into an Editable grid, but that just isn’t possible. I suppose you could go to Tools | Options | SQL Server Object Explorer and enlarge the sample size (or change it to 0 to get the entire table) but then you’d have to scroll down among all the rows to find the rows you’re looking for. Eesh. A much better solution is to click on the Show SQL Pane (Ctrl+3) and add a WHERE clause to the SQL that pulled the data. Rerun the query (Ctrl+R this time, not Ctrl+E or F5) and you can now edit a nice subset of records. Debugging First tip for debugging: You should never debug on a live server. In fact you as a developer shouldn’t even have the sys_admin rights necessary to debug on a live server. Even if you are the de facto sys admin, don’t use that login when you’re on the server as you’re opening up yourself to the possibility of locking up that server while you figure out what’s wrong with your code. Debug your scripts on a development server and deploy it live only after it’s been tested, just like your regular code. Debugging in SQL Server works just like debugging in Visual Studio. You can set breakpoints, step through code, inspect variables, etc. And just like your regular code, sometimes your scripts will throw an error. Bonus Tip: You could turn your line numbering on (Tools | Options | Text Editor | Transact- SQL) and scroll your way down to the line with the error, but SSMS makes it easier than that. Simply double-click on the error message and SSMS will take you right to the line with the error. Learn Your Tool Take the time to learn about what SQL Server provides for you in terms of built-in stored procedures and functions. We already talked about sp_Help and sp_HelpText, but there is a long list of System Stored Procedures available. There are also a ton of built-in global Figure 23: Editing the Records of the Employees Born After 1980.
  • 23. variables that start with @@ that are useful in your scripts (e.g. @@ROWCOUNT is useful for returning the number of rows a query produced). On the flip side, know what SSMS does not include and which 3rd Party tools fill in the gaps. There are some great free utilities as well as commercial ones. RedGate of course is the first name in 3rd party utilities for SQL Server, and I included a few in Appendix B. Speaking of RedGate, they provide free eBooks for all sorts of topics at http://www.red- gate.com/community/books/. Check that out along with some of these other links that I found helpful when putting this list together. There’s so much more to SSMS than I could cover here, but I hope this session opened up some possibilities for making you more efficient when using this tool. This list gets larger every time I give this session, so if you have ideas that you think I should add to this session please get in touch via email or Twitter and I’ll definitely include them.
  • 24. Appendix A: References These websites and books were integral in compiling this list, as well as the users in the Geek Lunch, MadFox, and ChicagoFUDG who listened to a preview of this session and contributed to it.  Full List of Keyboard Shortcuts: http://msdn.microsoft.com/en- us/library/ms174205.aspx  http://www.mssqltips.com/sqlservertip/2415/ssms-keyboard-shortcuts-part-2-of- 2/  http://www.mssqltips.com/sqlservertip/2145/starting-your-sql-server-career- path/?utm_source=dailynewsletter&utm_medium=email&utm_content=headline&u tm_campaign=2012411  http://www.databasejournal.com/features/article.php/3593466/MS-SQL- Series.htm  http://SQLServerCentral.com  http://Blog.SQLAuthority.com  http://http://www.mssqltips.com/  http://www.codeproject.com/Articles/39131/Global-Variables-in-SQL-Server  http://www.sqlservercurry.com/2011/08/net-developer-database- knowledge.html  http://SQLPass.com
  • 25. Appendix B: Useful Free 3rd Party Tool There could easily be another session done just on great, free, 3rd party tools available for SQL Server Management Studio. In fact, there is! I saw it done by Rick Krueger and Dave Valentine at a SQL Saturday (great events, by the way). Here’s a short list of some of the free 3rd party tools that I’m aware of:  T-SQL Formatter: http://www.architectshack.com/PoorMansTSqlFormatter.ashx and PoorSQL.com  SSMS Tools Pack :http://www.ssmstoolspack.com/ (include Poor Man’s formatter)  RedGate SQL Search http://www.redgate.com  BIDS Helper http://bidshelper.codeplex.com  SSMS Boost http://www.ssmsboost.com There are many, many more, as well as excellent non-free tools. Copyright, 2012, Eric Selje
  • 26. Figure 1: New Project/Solution Dialog, with option for Source Control...............................4 Figure 2: Retroactive Source Control............................................................................................................4 Figure 3: Source Control Options for your Scripts...................................................................................4 Figure 4: You can't have two connections to the same server, and a manual workaround doesn't help.............................................................................................................................................................5 Figure 5: The long list of every server ever ................................................................................................6 Figure 6: Add new query or "item" to project............................................................................................7 Figure 7: Adding a new ITEM allows you to select from a plethora of script templates...........7 Figure 8: The "Restore Database" script, in the project and properly name.................................7 Figure 9: Projects show in the QuickList, and your favorites can be pinned.................................8 Figure 10: Filtering Long Lists.........................................................................................................................9 Figure 11: Object Explorer Details Pane................................................................................................... 10 Figure 12: The "List Structure" of the SQL Server world.................................................................... 11 Figure 13: These Items are Dependents ................................................................................................... 12 Figure 14: This Item Claims These Dependents..................................................................................... 12 Figure 15: Database Diagram........................................................................................................................ 13 Figure 16: Set your own Keyboard Shortcuts......................................................................................... 14 Figure 17: Help SSMS Help You.................................................................................................................... 15 Figure 18: ScreenTip with shortcut............................................................................................................ 15 Figure 19: An Estimated Execution Plan with One Operation Highlighted................................. 16 Figure 20: Showing the Client Statistics with your Query ................................................................. 18 Figure 21: Starting a trace and selecting which events to Track in SQL Server Profler......... 18 Figure 22: Profiler Results. Note this is from an application for which I don't have the Source Code! ........................................................................................................................................................ 19 Figure 23: Editing the Records of the Employees Born After 1980. .............................................. 22