Category Archives: #SQLServer

All about Microsoft SQL Server

#0132 – SQL Server – SSMS – Tutorial – Part 07 – Database Administration and maintenance – Productivity enhancing features (L200


The SQL Server Management studio contains many pop-up utilities and tools that help in improving the productivity of our day-to-day database administration and maintenance tasks. While most of these would be implemented using T-SQL code in production, these tools & utilities are a great way to get started. Practice using these tools in your development environments, and then see if they suit your needs for production use.

Copying/Moving a database from one SQL Server instance to another

There are multiple ways to achieve this goal:

  1. Detach/Attach
  2. Backup/Restore
  3. Copy database wizard
  4. Script database wizard

The Detach/Attach and Backup/Restore are fairly common methods, and there is sufficient documentation in Books On Line (hyperlinks embedded above) to get started. However, I rarely see a database administrator using the Copy database wizard or the script database wizard. So, let’s take a look at these two methods.

Copy Database Wizard

The Copy Database wizard is nothing but a customized version of the Attach/Detach method and Integration services under the hood. Perhaps the only hesitation from an administration perspective is that this mechanism requires the SQL Server Agent to be running on the destination server. If you are not a system administrator, you must specify a SQL Server Agent Proxy account that has access to the Integration Services (SSIS) Package execution subsystem.

NOTE: This method is not available for moving system databases. That has to be done via the manual procedures documented on MSDN here.

Here are the brief steps involved in the copying of a database using the copy database wizard.

Right-click the database to copy/move >> Tasks >> Copy Database
Copy Database task option
Welcome page
image

Connect to the source & destination instances. Then select the transfer method. You have a choice between the following:

  1. Detach & Attach method – faster, requires source database to go offline
  2. SMO method – slower, source database remains online

For this demo, I will use the faster, detach-attach method.

image
Choose which databases are to be copied and/or moved.
image
Supply details of the destination database.
image
Choose which objects are to be copied/moved to the new database on the destination instance
image
Configure the SSIS package that would be used to transfer these objects.
image
Choose whether or not to run the transfer immediately
image
Point of no return: Verify the selected options
image
Monitor the progress. At the end of the process, the database has been copied/moved.
image

Script Database Wizard – Script database with data in it!

The above method is great when you can actually connect to both source and destination instances. But what do you do when the destination instance is a remote instance which you cannot connect to? The answer: Generate scripts!

But, generating scripts by default never scripts the associated data, which may be the real point of interest. We need to set a small option to ensure that associated data is scripted.

Right-click the database to copy/move >> Tasks >> Generate scripts
image
Welcome screen
image
Choose whether you need to script all the objects within the database, or script only one.
For demonstration purposes, we will only script one object (keep the check-box unchecked).
image
Choose Script Options: Change the scripting options as necessary by your database coding and deployment standards.

IMPORTANT STEP: Change the “Script data” option from False to True.

image
Choose the object types to script
image
Based on the options selected above, the wizard would ask you to choose the schemas, stored procedures and other objects to script.
image

Choose destination for the scripting process. You can:

  1. Script to File
  2. Script to clipboard
  3. Script to New Query Editor window (default)
image
The required objects are now scripted. Notice the INSERT statements for the pre-existing data.
image
image

You can now use this script to deploy this database on any SQL Server instance for which the script has been generated.

Multi-Sever queries – assisting the discovery process

Whenever I take charge of a server or a couple of servers, I like to know about the databases on the server and about the existing configuration. Not only that, I like to prepare an inventory of the details found, so that I can maintain a change log of whatever changes and tweaks I make going forward. Most of you from the audience would also have such pre-developed scripts that you would be using during the discovery process.

However when taking charge of an entire set of servers, running these scripts against each of these servers is a very time consuming (and depending upon whether you multi-task or not – possibly erroneous) process. SSMS allows us to run a single query against all “registered server” instance from a single window using multi-server query support. You can read more about this feature here: http://beyondrelational.com/blogs/nakul/archive/2011/02/04/multi-server-queries-underappreciated-features-of-microsoft-sql-server.aspx

Practice Exercises…

  • How can you upgrade your SQL Server 2000 database to a SQL Server 2008 database with the copy database wizard?
  • Adjust the options in the script database wizard to generate a database deployment script for your database that confirms to your organization’s standards

Further reading/Other tools & utilities…

Until we meet next time,

Be courteous. Drive responsibly.

Subscribe to my posts via E-mail: Subscribe here | Read my posts via your favourite RSS reader: Click Here! | Tweet to @nakulv_sql

#0131 – SQL Server – SSMS – Tutorial – Part 06 – Introduction to the Properties Window (L100)


The SQL Server Management Studio (SSMS) continues to fascinate me with it’s immense wealth of features geared towards developer & administrator usability. What’s more amazing is that some features perform multiple useful functions depending upon the context. Today, we will have a look at one such feature – the “Properties” window, which performs the following functions:

  1. Developer friendly features
    • Knowing your query options – ANSI_NULLS, QUOTED_IDENTIFIER, ARITHABORT and other SET options
  2. Administrator friendly features
    • Performance tuning

The “Properties” window is available in SQL Server 2005 and up.

Developer friendly features – knowing query options

Often, we multi-task and forget the exact set of SET options that a particular connection uses. The most frequently used SET options that one is worried about are:

  • ANSI_NULLS
  • QUOTED_IDENTIFIER
  • ARTIHABORT
  • NUMERIC_ROUNDABORT
  • ANSI_WARNINGS

The properties window provides us a way to check the various SET options used for a particular connection. Here’s a step-by-step guide:

  • Let’s run the following query in SQL Server Management Studio. Include the “Actual Execution Plan” by pressing Ctrl+M before running the query.
    USE AdventureWorks2008R2
    GO
    
    SELECT e.LoginID, e.JobTitle, e.HireDate, e.CurrentFlag
    FROM HumanResources.Employee e
  • Switch to the Actual Execution plan in the Results pane
  • Hit F4 to invoke the Properties Window (you may also use View->Properties Window menu option)
  • Select the top-most SELECT operator
  • Observe the Properties Window

Viewing SET options

As a cross-check, change the SET options on the query, or use the features of SSMS to change the SET options for just this connection.

USE AdventureWorks2008R2
GO

SET ANSI_NULLS OFF
GO

SELECT e.LoginID, e.JobTitle, e.HireDate, e.CurrentFlag
FROM HumanResources.Employee e

SET ANSI_NULLS ON
GO

Modifying SET options

Administrator friendly features – Performance tuning guidance

Please note that performance tuning itself is out of scope for this tutorial. What is covered though, is how the Properties window can help us when performing a performance tuning exercise.

Generally, a performance bottleneck is because of issues with the application code – this includes sub-standard T-SQL code.

If the SQL optimizer feels that an index would help it generate a better execution plan for any given query, SQL Server Management Studio provides us with an indication of it’s requirement when viewing the graphical execution plan.

If we run a query in SQL Server Management Studio with the graphical plan enabled, the missing index hint would show up in green-text as high-lighted in the screen-shot below.

USE AdventureWorks2008R2
GO

--Number of sales done in April, 2008
SELECT COUNT(*)
FROM Sales.SalesOrderHeader sh
WHERE MONTH(sh.OrderDate) = 4 AND YEAR(sh.OrderDate) = 2008
GO

SELECT COUNT(*)
FROM Sales.SalesOrderHeader sh
WHERE sh.OrderDate >= '2008-04-01' AND sh.OrderDate <= '2008-04-30'

Notice that the Properties page also displays the missing index information. In fact, the Properties page was the only place to get this information in SQL Server 2005.

Missing Index Hints

Practice Exercises…

Explore the “Properties” window that comes up in the following cases:

  1. Query editor window
  2. Query results window
  3. Table designer window

Further reading…

Until we meet next time,

Be courteous. Drive responsibly.

Subscribe to my posts via E-mail: Subscribe here | Read my posts via your favourite RSS reader: Click Here! | Tweet to @nakulv_sql

#0130 – SQL Server – SSMS – Tutorial – Part 05 – The Wizards of SSMS – Table Designer, Query designer & Template Explorer (L


The SQL Server Management Studio is truly an Integrated Development Environment. There are utilities, tools and graphical designers available within SSMS which are useful to audiences of multiple levels. The graphical designers are a set of utilities, which allow one to perform basic SQL Server development without writing a single line of T-SQL code.

In this tutorial, I will provide a basic introduction to these designers and also focus on how one can use these tutorials to enter the next level – that envious ability to write T-SQL code for almost anything that needs to be done in SQL Server.

Table Designer

Modifying an existing table

Let’s begin with something simple – modifying an existing table, using nothing but the graphical features of the SSMS table designer. Here are the steps:

  1. Using the Object Explorer, navigate to the database whose table needs to be modified
  2. Expand the database node, and navigate to the table requiring modifications from the Table node
  3. Right-click on the required table, and choose “Design”

image

This opens the table designer. The view has two parts:

image

  1. Basic editing of columns, which allows one to define:
    • The column name
    • Data-type
    • Null-ability
    • Configure Keys
    • Configure Indexes & relationships
  2. Advanced editing of column properties
    • Column Collation
    • Computed Column specification
    • Description
    • Read only property fields, like:
      • Deterministic
      • Is Indexable
      • Is Sparse

To extend the length of the “Job Title” column from 50 to 60, simply click in the “Data Type” column and make the necessary modifications. Simply click “Save” on the toolbar to commit the changes to the database.

Changing an existing column Saving the change
image image

Creating a new table

Creating a new table is just as simple as modifying an existing one. The steps involved are also similar:

  1. Using the Object Explorer, navigate to the database whose table needs to be modified
  2. Expand the database node, and navigate to the Table node
  3. Right click and choose “New Table”

image

An empty table designer window opens. Now, define create the new table as required, and save the changes.

Define the columns image
Define the primary keys image
Defined primary key image
Define the identify column properties image

NOTE that the options to change the table name and the associated schema are available in the Properties window, which is typically available to the right of the Table Designer. This window allows us to change the following (includes, but not limited to):

  1. Table Name
  2. Schema Name
  3. Lock Escalation
  4. File-group
  5. Description

image

Generating T-SQL Code from the designers

Here’s probably the one thing I would recommend each and every one working with the table designer to do – use it to learn how to write production-quality T-SQL code.

We made a change above wherein we changed the data-type of one of the columns. As soon as we make the modification, notice that a small icon becomes enabled on the toolbar. This icon enables a user to generate the T-SQL code for the change. The script can then save the script to a text file or copy-paste the change to a query editor window.

“Generate Change Script” icon T-SQL script for the associated changes
image image

Controlling Table Designer options

From an administration perspective, one might want to control the level of changes that can be made to the database. For example, an administrator may want to restrict changes that would require a user to recreate the table, pump data in from the old table and then discard the old table. The table designer allows the administrator to configure this option as follows:

  1. Go to Tools –> Options
  2. Navigate to “Designers”
  3. Drill down to “Table and Database designers”
  4. Set the options required

image

If we attempt to perform the same operation (changing the size of the “Job title” field as above), the user would encounter the following message indicating that the change is not allowed.

image

Query Designer

If you have an existing query in SSMS, just select the entire query, and use the Ctrl+Alt+Q shortcut key or use the Query –> Design Query in Editor menu option. You will see that your query is now available in the Query Designer, ready for some key-stroke-less, graphical editing.

Let’s begin with a basic query. Notice that the query is not formatted to our liking.

SELECT Employee.BusinessEntityID, Person.LastName, Person.FirstName,EmployeeDepartmentHistory.ShiftID,Department.GroupName,Department.Name
from HumanResources.Employee
INNER JOIN HumanResources.EmployeeDepartmentHistory ON Employee.BusinessEntityID = EmployeeDepartmentHistory.BusinessEntityID INNER JOIN HumanResources.Department ON EmployeeDepartmentHistory.DepartmentID = Department.DepartmentID
INNER JOIN Person.Person ON Employee.BusinessEntityID = Person.BusinessEntityID
order by Person.LastName, Person.FirstName

After selecting the query and pressing Ctrl+Alt+Q, the Query designer launches, which allows us to add/remove columns, define column aliases and format the query.

image

Click on “OK” and the user is returned to the SSMS Query Editor, with the query changes made. The updated query looks like:

SELECT     Employee.BusinessEntityID, Person.Person.LastName, Person.Person.FirstName, HumanResources.EmployeeDepartmentHistory.ShiftID, 
                      HumanResources.Department.GroupName AS [Department Group], HumanResources.Department.Name AS [Department Name], Employee.Gender
FROM         HumanResources.Employee AS Employee INNER JOIN
                      HumanResources.EmployeeDepartmentHistory ON Employee.BusinessEntityID = HumanResources.EmployeeDepartmentHistory.BusinessEntityID INNER JOIN
                      HumanResources.Department ON HumanResources.EmployeeDepartmentHistory.DepartmentID = HumanResources.Department.DepartmentID INNER JOIN
                      Person.Person ON Employee.BusinessEntityID = Person.Person.BusinessEntityID
ORDER BY Person.Person.LastName, Person.Person.FirstName

The query designer is not only suitable for existing queries, but can also be used in a similar fashion for new queries, which you can explore as an exercise to this tutorial.

Template Explorer

Per Microsoft SQL Server Books On Line, Template Explorer is a component in SQL Server Management Studio that presents templates to quickly construct code in the Code Explorer. The templates are grouped by the type of code being created, which in turn makes finding the right templates blazingly fast.

Navigating through the Template Explorer

To launch the Template Explorer launch the SQL Server Management Studio and simply use the Ctrl+Alt+T keyboard combination or go to View->Template Explorer.

Launching the Template Explorer

image

SQL Server provides the user the option to choose from any of the 3 families of templates:

  1. SQL Server
  2. Analysis Services
  3. SQL Compact

NOTE: Templates are stored in the user’s Documents and Settings folder when the Template Explorer is opened for the first time:

  • On SQL Server 2008, the templates are found under %APPDATA%MicrosoftMicrosoft SQL Server100ToolsShellTemplates
  • On the upcoming SQL Server 2012 (SQL 11/”Denali”), the templates are found under %APPDATA%MicrosoftSQL Server Management Studio11.0Templates

SQL Server Templates

For the purposes of this example, we will attempt to create a new stored procedure using SQL Server templates. All one needs to do is to navigate out to “Stored Procedures” folder in the Template Explorer and double-click on “Create Procedure Basic Template”.

image

The first thing that strikes us is that they contain parameters to help us customize the code. Per BOL, template parameter definitions use this format <parameter_name, data_type, value>, where:

  • parameter_name is the name of the parameter in the script
    • data_type is the data type of the parameter
  • value is the value that is to replace every occurrence of the parameter in the script

Replacing Parameters in SQL Server Templates

Replacing the parameters in a SQL Server Template to create an almost fully-functional script is a simple three step process, as under:

  1. On the Query menu, click Specify Values for Template Parameters
  2. In the Specify Values for Template Parameters dialog box, the Values column contains suggested value for the parameter. Accept the value or replace it with a new value as required, and then click OK to close the Replace Template Parameters dialog box and modify the script in the query editor
  3. Modify the query to add whatever business logic necessary
Launching the “Specify Values for Template Parameters” dialog Replacing Template Parameters
image image

Here’s the script with the parameters replaced. The SELECT statement in the body of the stored procedure has been replaced with business logic:

-- =============================================
-- Create basic stored procedure template
-- =============================================

-- Drop stored procedure if it already exists
IF EXISTS (
  SELECT * 
    FROM INFORMATION_SCHEMA.ROUTINES 
   WHERE SPECIFIC_SCHEMA = N'[Sales]'
     AND SPECIFIC_NAME = N'[proc_AddNumbers]' 
)
   DROP PROCEDURE [Sales].[proc_AddNumbers]
GO

CREATE PROCEDURE [Sales].[proc_AddNumbers]
	@p1 int = 0, 
	@p2 int = 0
AS
	--Template Default
	--SELECT @p1, @p2
	SELECT @p1+@p2 AS 'Result'
GO

-- =============================================
-- Example to execute the stored procedure
-- =============================================
EXECUTE [Sales].[proc_AddNumbers] 1, 2
GO

As you can see, our basic script is now ready for use in just 3 simple steps.

Interesting Reading…

Aaron Bertrand (blogs | twitter) believes that using the designer is a bad habit (http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/14/bad-habits-to-kick-using-the-visual-designers.aspx). I agree with Aaron, however, share the view that these designers are great for the developers who would want to study how to write production quality T-SQL code. Once a certain comfort level is achieved in writing T-SQL code, the reader would be motivated to explore options to improve the code and subsequently reduce the dependency on the designers.

Practice Exercises…

It’s time to practice! Today’s exercises may take some more time as it involves playing around with the various designers to your heart’s content:

  1. Create new database objects as mentioned here: http://msdn.microsoft.com/en-us/library/hh272695(v=VS.103).aspx
  2. Create a custom template to confirm to the coding standards of your organization
  3. Deploy the newly created custom template
  4. Create a test database as below:
    CREATE DATABASE foo
    GO
    
    USE foo
    GO
    CREATE TABLE MyTbl (MyName CHAR(4030))
    GO
    
    INSERT INTO MyTbl
    SELECT REPLICATE('a',4030)
    GO
      
  5. Increase the length of the column MyTbl.MyName to 4031 characters. Study the T-SQL script generated by table designer
    • Can you figure out why the T-SQL script was generated in this way?

Further reading

  1. SQL Server – SSMS – Table Designer v/s ALTER TABLE – Best Practices – Msg 1701 – Creating or altering table failed….This exceeds the maximum allowable table row size of 8060 bytes
  2. SSMS – Query Designer – Ad-hoc query writing/editing made simple
  3. Template Explorer – Underappreciated features of Microsoft SQL Server
  4. Template Explorer – Changes & Template updates in SQL 11 (Code Named: “Denali”) CTP01 – comparison with SQL Server 2008
  5. Template Explorer – Deploying custom templates in SSMS – VTD Webcast feedback question – Underappreciated Features of Microsoft SQL Server

Until we meet next time,

Be courteous. Drive responsibly.

Subscribe to my posts via E-mail: Subscribe here | Read my posts via your favourite RSS reader: Click Here! | Tweet to @nakulv_sql

#0129 – SQL Server – SSMS – Tutorial – Part 04 – Introduction to Database Diagramming (L100)


For those who have worked in Enterprise environments, documentation is of utmost importance. Documentation can be in the form of a text-based document, or a graphical document (in the form of a diagram).

A data dictionary is a centralized repository of information about data such as meaning, relationships to other data, origin, usage, and format. Data dictionaries are commonly used to circulate copies of the database schema to vendors and technology partners, and once a product is released, this may be made available to the end customers depending upon the need (e.g. to allow for customization or study).

Database diagrams, are a repository of the relationships between the various database objects. Database object relationships are typically described using a graphical representation of the tables, columns, keys, indexes, relationships, and constraints.

For any database, you can create as many database diagrams as you like; each database table can appear on any number of diagrams. Thus, you can create different diagrams to visualize different portions of the database, or to accentuate different aspects of the design. For example, you can create a large diagram showing all tables and columns, and you can create a smaller diagram showing all tables without showing the columns.

Diagram ownership

Database diagrams expose the entire relationship design of a database. This can potentially help someone to reverse engineer the diagrams. Therefore, all diagrams can only be seen by members of the db_owner role.

  1. A diagram can have one and only one owner – the creator of the diagram
  2. The creator of the diagram has to be a member of the db_owner role
  3. A diagram can only be seen by the diagram creator and all members of the db_owner role

Working with database diagrams

A database is not configured to generate and store database diagrams by default. Therefore, before a database diagram is generated, the first task is to prepare the database to enable database diagrams.

  1. Right-click the Database Diagrams node of your database in Object Explorer
  2. Select Yes when prompted if you want to set up database diagramming
  3. Clicking on Yes creates the following objects within the database:
    • Sysdiagrams table
    • sp_alterdiagam stored procedure
    • sp_creatediagram stored procedure
    • sp_dropdiagram stored procedure
    • sp_renamediagram stored procedure
    • sp_helpdiagrams stored procedure
    • sp_helpdiagramsdefinition stored procedure
    • sp_upgraddiagrams stored procedure
    • fn_diagramobjects function

Creating a diagram

Creating a database diagram is now a very easy process, and diagrams can be created in just 4 steps.

  1. Right-click the Database Diagrams node of your database in Object Explorer
  2. From the drop-down menu, click New Database Diagram
  3. In the Add Table dialog box, choose tables to work with in the diagram
  4. The Database Diagram menu will be added to the main menu and the designer pane will open

Here’s a graphical representation of these steps:

Creating a new database diagram Choosing the tables to display Tables added to the diagram

Parts of a diagram

As you can see in the diagram above, there are multiple parts to a relationship between the multiple objects on a database diagram:

  1. Endpoints   The endpoints of the line indicate whether the relationship is one-to-one or one-to-many. If a relationship has a key at one endpoint and a figure-eight at the other, it is a one-to-many relationship. If a relationship has a key at each endpoint, it is a one-to-one relationship
  2. Line Style   The line itself (not its endpoints) indicates whether the Database Management System (DBMS) enforces referential integrity for the relationship when new data is added to the foreign-key table. If the line appears solid, the DBMS enforces referential integrity for the relationship when rows are added or modified in the foreign-key table. If the line appears dotted, the DBMS does not enforce referential integrity for the relationship when rows are added or modified in the foreign-key table
  3. Related Tables   The relationship line indicates that a foreign-key relationship exists between one table and another. For a one-to-many relationship, the foreign-key table is the table near the line’s figure-eight symbol. If both endpoints of the line attach to the same table, the relationship is a reflexive relationship

Customizing the diagram

The diagram layout, by default, may not be in a consumable format. The database diagramming wizard allows use to customize the diagram to our convenience.

Zooming

One of the most commonly required features when working with database diagrams is the need to zoom in or out depending upon the number of tables and relationships involved. Simply right-click on the diagram and choose the zoom factor suitable to your needs.

Source view Choosing the zoom factor Post-zoom view
Source View Choosing the zoom factor Post-zoom view

Customizing the amount of information displayed on the diagram

The default view does not provide sufficient information to qualify as a concise, file-able document. To customize the information displayed on the diagram, one can follow the steps below:

  1. Select the tables for which the view needs to be modified
  2. On the “Database Diagrams Designer” toolbar, from the shortcut menu “Table View”, choose the required view
Choosing the required Table View
(The default “Column Names” view in the background)
The default Column Names view
Standard View Standard View
Key Names Key Name View
Table Name Table Name View
Custom View Custom View
Customizing the “Custom View” using the column selector window Customizing a custom database diagram view

Adding text annotation

Often, we may need to add custom notes to the diagram. This is achieved easily by adding a text annotation.

Right-click on any empty area of the screen and choose “New Text Annotation” Creating a new text annotation
A text box comes up and allows us to type in text of our choice. Text Annotated-diagram

Practice Exercises…

It’s time to practice! Very simple exercises today:

  1. Create a database diagram showing all tables of the HumanResources and the Sales schema and also show the relationship between them
  2. Customize the view to show only the keys on the tables
  3. Use the “auto-arrange” functionality to arrange the tables on the designer
  4. Show the relationship names on the diagram

Further reading

  1. Working with Database Diagrams
  2. Designing Database Diagrams

Until we meet next time,

Be courteous. Drive responsibly.

Subscribe to my posts via E-mail: Subscribe here | Read my posts via your favourite RSS reader: Click Here! | Tweet to @nakulv_sql

#0128 – SQL Server – SSMS – Tutorial – Part 03 – The T-SQL Debugger (L200)


More often than not, there is a myth in the developer community that Microsoft SQL Server does not provide the debugging abilities that other IDEs provide. Even SQL Server 2000 provided basic debugging ability. Starting Microsoft SQL Server 2005, the product now comes with it’s own Management Studio, which is based upon Microsoft’s renowned IDE – the Visual Studio. Therefore, the most common debugging abilities come out of the box for SQL Server – enough to give application developers a run for their money!

The upcoming, SQL Server 2012 takes debugging a step further – bringing conditional breakpoints, data-tips and what have you. Let’s have a look at some of the basic debugging options that are available to us in SSMS.

NOTE: For T-SQL Debugging, connecting the Transact-SQL editor to the server with a login having the sysadmin fixed server role is not sufficient; the Windows login of the Visual Studio user must also be a member of the sysadmin fixed server role on that instance of SQL Server.

Which objects can be debugged?

All commonly used objects within SQL Server can be debugged. These include, but are not limited to:

  • Ad-hoc queries
  • Stored procedures
  • Triggers

The way to debug any of these objects is same as Visual Studio.

  • Start debugging – F10
  • Step into an object – F11

We will keep things simple for this session, and raise the bar as we go along.

Debugging in SQL 2012 – Breakpoints

Test Script for this session

We will debug the following script in this session on SQL 11 (“Denali”) CTP03. It is a very simple script that loops through for 20 iterations.

DECLARE @iCounter INT = 0

WHILE (@iCounter <= 20)
BEGIN
    PRINT 'Hello World! The counter reads: ' + CAST(@iCounter AS VARCHAR(2))

    PRINT 'Hello Nakul! The counter reads: ' + CAST(@iCounter AS VARCHAR(2))

    SET @iCounter += 1
END
GO

Creating Conditional Breakpoints & Labeling them

One of the major features that was missing in the earlier versions of SSMS was the ability to have conditional breakpoints. In SSMS for Denali, conditional break-pointing is possible. To explore it’s features, let’s start debugging by pressing the F10 key as high-lighted in the Hands-On session. I would re-iterate that debugging in SSMS is not at all different than debugging in VS2010.

To demonstrate the fact, let’s place a breakpoint near the line for “Hello World!”. We will make this a conditional breakpoint, to break only if the value of the counter hits 10.

Hit F9 to setup the breakpoint on the desired line

Note that the information in the “Breakpoint” window is non-descriptive. Let’s correct that first

image
Right-click on the breakpoint, and choose “Edit Labels”

image
In the “Edit Labels” window, type in a descriptive detail and click “Add”

If pre-existing, you can choose one if you like

image
On clicking “OK”, notice that the breakpoint can now be identified easily amongst a pile of breakpoints image
Now, right-click on the breakpoint and go to “Condition” image
Add the required expression as a condition and click “OK” image
Notice that in both the “Breakpoints” window &  editor window, the breakpoint symbol now has a little "plus (+) sign in it image
Let’s create a “Hit Count” based breakpoint for the second line image
For the test, let’s set this breakpoint to hit at intervals in multiples of 4 – at 4, 8, 12,16 & 20.

Hit OK once done to set the breakpoint

image
The Breakpoints window would look like the one in the screenshot image

Hit “Alt + F5” to run through the sample code. The first breakpoint hit will be “Hello Nakul!” when the hit count is 4. To verify whether the hit is correct or not, you can either use the “Locals” window or the “Immediate” window (Go to Debug –> Windows –> Immediate or press Ctrl+Alt+I):

image

Hit Alt+F5 again. The next breakpoint to be hit will again be “Hello Nakul!”. Hit Alt + F5 again, and we will hit the “Hello World!” breakpoint and so on.

Searching for specific breakpoints – using Labels to your advantage

Go to Debug->Windows->Breakpoints or press Ctrl+Alt+B to launch the Breakpoints window.

While we only have 2 breakpoints in this session and it is quite easy to remember them, in production code, there might be tens of breakpoints and it might be difficult to remember each one. What’s more, out of all breakpoints, you might want to work with only the breakpoints that are related to a particular operation – an update to a given table, for example.

In the breakpoints window, take the time out to label each breakpoint carefully. You may want to use your labels such that each label identifies a particular group of operations in question – for example, a label can be – “Updating Production”, “Updating Sales Orders” and so on.

Notice the addition of a “Search” box in the Breakpoint window. The “Search” box allows us to search on a specific column or on all visible columns of the breakpoint window.

image

Choosing “All Visible” in the “In Column” drop-down, let’s type in “World” in the “Search” box and hit Enter. Notice that SSMS will take the other breakpoints off the list. Clearing the search results will bring them back.

image

Exporting Breakpoints

Now, let us see how to export breakpoints from one SSMS session to another.

Once the script file has been saved to any location of your choice, click on the “Export” button on the toolbar of the “Breakpoints” window image
In the File->Save dialog, select a location and file name of your choice to export the breakpoints image

Importing Breakpoints

Now that we have exported breakpoints to a file, let’s see how we can import them into another SSMS session.

Launch SSMS and open the query to debug.

Launch the breakpoints window (Debug –> Windows –> Breakpoints, or Ctrl + Alt +B) and click the Import button:

image
In the File->Open dialog box, choose the breakpoints file saved above image
Notice that the breakpoints are imported and applied successfully such that the IDE is now ready for debugging image

Data Tips

Per MSDN, “DataTips are one of the most convenient tools for viewing information about the variables and objects in your program during debugging. When the debugger is in break mode, you can view the value of a variable within the current scope by placing the mouse pointer over the variable in a source window.

I like to think of it as a very light-weight version of the Watch window. When debugging, almost any troubleshooter likes to be in full control – knowing exactly what is going on where. If a variable changes it’s value, it might be important because it may not be warranted and might produce incorrect results. Data Tips help us in being “aware” about our surroundings, and at times, in controlling the flow of execution.

Please note that to the best of my knowledge, Data Tips are available in all the flavours of Visual Studio 2010.

To Display A Data Tip

Start a debug session image_thumb2
However the mouse over the variable to be evaluated, a Data Tip appears image_thumb4

To Move, Pin and Unpin A Data Tip

Click the “pin” icon image_thumb6
The data-tip is now “pinned” image_thumb8
Drag the data tip to the desired location to move it image_thumb10
Hover over the data-pin and click the “pin” icon again to un-pin the data-tip image_thumb12

Adding Comments to a Data Tip

Click the “Expand” arrow on the data-tip image_thumb13
Add required comments in the edit box image_thumb15
Click anywhere on the “Canvas” image_thumb17

To Close all Data Tips

We have not one, but 3 distinct options to clear out the data-tips on a Microsoft SQL Server Query Editor window.

Option #1 – Debug Menu image_thumb19
Option #2 – The Data tip itself image_thumb21
Option #3 – Right-click the “indicator” column image_thumb23

Limitations

As with any enhancement, there are always things that can be improved upon after the fact. The only major limitation that I see with exporting & importing breakpoint is:

  • The name & location of the script file must be same as that when the breakpoints and data-tips are exported
    • Therefore, if when the breakpoints were exported, the script file was at “E:ScriptsBreakpoints.sql”, I cannot change it to be “E:DevelopmentBreakpoints.sql” for the import

Practice Exercises/How To…?

It’s time to practice! The practice exercises for the T-SQL debugger need some setup time, but are simple and easy.

Create the following stored procedure against the AdventureWorks2008 database:

--Step 01: Create the following Stored Procedure
USE AdventureWorks2008;
GO
IF OBJECT_ID ( 'Sales.proc_UpdateSalesOrderDetailUnitPrice', 'P' ) IS NOT NULL 
    DROP PROCEDURE [Sales].[proc_UpdateSalesOrderDetailUnitPrice];
GO

CREATE PROCEDURE [Sales].[proc_UpdateSalesOrderDetailUnitPrice]
    @tSalesOrderId       INT,
    @tSalesOrderDetailId INT,
    @tUnitPrice          MONEY
AS
BEGIN
    --Wrap the UPDATE in a transaction so that we do not make permanent changes to the DB
    BEGIN TRANSACTION MyDebuggingTest
        UPDATE [Sales].[SalesOrderDetail]
        SET UnitPrice = @tUnitPrice
        WHERE SalesOrderID = @tSalesOrderId AND
              SalesOrderDetailID = @tSalesOrderDetailId
    ROLLBACK TRANSACTION MyDebuggingTest
END
GO
  1. Debug the trigger – Sales.iduSalesOrderDetail by executing the following stored procedure:
        
    USE AdventureWorks2008
    GO
    
    DECLARE @tSalesOrderId INT = 43659,
            @tSalesOrderDetailId INT = 2,
            @tUnitPrice MONEY = 2010.255
    
    EXEC [Sales].[proc_UpdateSalesOrderDetailUnitPrice] @tSalesOrderId, @tSalesOrderDetailId, @tUnitPrice
    
  2. Define a breakpoint within the trigger. Notice that the breakpoint window displays a long number instead of the trigger/object/script name. What is this number?
    1. Hint: Read the article on the Debugger hands-on session in the “further reading” section below

Further Reading

Until we meet next time,

Be courteous. Drive responsibly.

Tweet to @sqltwins