Tag Archives: #SQLServer

All about Microsoft SQL Server

#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

#0127 – SQL Server – SSMS – Tutorial – Part 02 – Introduction to the Object Explorer and Object Explorer Details window (L100)


As you know, we are exploring the world of graphical tools & utilities that are available to us out of the box in a Microsoft SQL Server installation. In the previous part of the tutorial, I provided an introduction to the SQL Server Management Studio (SSMS) and the Query Editor window. I hope that you have started exploring these most important tools.

In this part, I will help you explore the two most important windows after the Query Editor. These are the Object Explorer & the Object Explorer Details. Both are related, and therefore, easier to understand.

The base functionality offered by these windows was around at least since the days of SQL Server 7.0. We lost most of this functionality when SQL Server underwent massive re-engineering in SQL Server 2005, but they were reintroduced starting SQL Server 2008.

Object Explorer window

The Object Explorer window is perhaps the 2nd most used part of the SQL Server Management studio. The Object explorer has the ability to connect to following services of SQL Server:

  1. Database Engine instances
  2. Analysis Services
  3. Integration Services
  4. Reporting Services
  5. SQL Server Compact editions

The primary functions of the Object Explorer are:

  • Provides a view of the objects available in the SQL Server
  • Provides a user interface, or invokes wizards to manage these objects

The Object Explorer UI

The object explorer is so powerful, that it comes with it’s own UI elements – a toolbar and a working area. Here’s the screenshot.

Object Explorer - Base View

To connect to the object explorer, click on the “connect” button in the Object Explorer toolbar, which pulls up the “Connect to Server…” dialog box. Once logged in, the user immediately notices that all database objects are neatly arranged in the logical groups. When connected to a database engine, the groups are:

  1. SQL Server instance – allows you to:
    1. Manage SQL Server configuration
    2. Manage part of the SQL Server surface configuration
  2. Databases – allows you to:
    • View a list of accessible databases, their states
    • View information about database objects
    • Create & modify database objects
    • Manage databases
    • Manage database security
  3. Security – allows you to:
    • Manage SQL Server instance security, including logins
  4. Server Objects – allows you to:
    • Manage endpoints
    • Manage devices
    • Manage linked servers
  5. Replication – allows you to:
    • Manage & configure replication
  6. Management
    • View activity log information
    • Run basic
  7. Integration Services
  8. SQL Server Agent
    • Setup, configure and manage agent jobs
    • Manage SQL Server automation

Not only does the object explorer allow an administrator to manage the SQL Server instance, it also allows a developer to:

  1. Filter & identify database objects from all objects of a database
  2. Once filtered, the developer can script these objects out

Filtering objects within the object explorer

We can summarize filtering within the object explorer in 3 simple steps!

Step 01:
A. In the Object explorer, right click on the “Tables”
B. Go to Filter –> Filter Settings
Filter objects view
Step 02:
Enter the object information as necessary. For our case, enter:
Name = Person
(If you only want to work within a schema, enter only the schema name)
Filter Settings
Step 03:
Simply click “OK” to apply the filters in the Object Explorer
Filtered objects in the Object Explorer
Step 04:
To remove filtering, all one needs to do is:
A. In the Object explorer, right click on the “Tables”
B. Go to Filter –> Remove Filter
Removing filters

Filtering is applicable to all object types within the Object Explorer. If one is to only work on a particular schema or a set of objects, it is very productive to have only those required objects filtered out. For SQL Server 2005 users, there are no bad news because this feature is available in Microsoft SQL Server 2005 as well.

Scripting a database object

Once you have filtered for the required object, you can script out the object for saving a copy or deploying the object on another database/SQL Server instance. Again, we have a very concise sequence of steps:

Step 01:
Right click on any object.
 
Step 02:
Go to Script Table As –> Create To –> New Query Editor window
Scripting objects from the Object Explorer
Step 03:
A script that can be used to recreate a database object is now generated.
Scripted object

Adjusting scripting options

You can adjust the scripting options to suit your standards and needs. For example, many prefer that the script check for pre-existing versions of the objects before going ahead with the deployment. To adjust the scripting options, you need to follow the following steps:

Step 01: Go to Tools –> Options Options window
Step 02: Under SQL Server Object Explorer, go to “Scripting” Scripting options
Step 03: Configure scripting options of your choice depending upon your project/organization best practices Scripting Options

Once these options are set, the SSMS will follow these settings for all scripting capabilities available.

Object Explorer Details window

In addition to providing object listing functionality same as the Object explorer, the Object Explorer details also provides certain additional information:

  1. Database information
    • Information about database owner, space available, recovery model and other database properties
  2. Table & index usage
    • Information about # of rows in a table/index, size of table/rows, etc
  3. Space utilization
    • Log and data file space utilization

The object explorer details is not launched by default. To launch the Object explorer details window, simply hit F7 after launching SSMS or go to View->Object explorer details.

IMPORTANT: On 32-bit operating systems, Object Explorer can only display 64,000 objects. An icon must be selected to access additional objects.

The following screenshots demonstrate how you can move about the object explorer details window via a drill-down mechanism.

Object explorer base state image
Drill down to the “Databases” node, and select a database to view database properties
(Also, you can use the column chooser)
image
Double click on the database, browse out to the “Tables” node and double-click on any table to get the table Details image
Index Details image

Object Search

One of the best features I like is the object search. It’s power-packed, fast and is absolutely geared towards reducing developer and administrator efforts.

Here are the brief steps:

  1. Navigate to the Object Explorer Details window by using the View menu or pressing the (F7) key when in the SQL Server Management Studio
  2. Drill down to the database against which the search needs to be carried out
  3. In the Search bar, enter the object name that you would like to search for (you can use wild-card characters)
  4. Simply hit “Enter” to execute the search!

Object Explorer Details search

If no specific database is chosen, the search is executed across all databases in the entire SQL Server instance. This is very useful feature, however, can be very slow. If you happen to use this accidentally, there’s always the panic button labeled – “Stop”!

Progress bar on the object explorer window

Once an object is found, one might want to look for it in the Object Explorer. To do so, simply right-click and choose “Synchronize”.

Step 01: Right-click and choose “Synchronize” Object Synchronization
Step 02: Notice that both the object explorer and object explorer details now points to the selected object Object Synchronization

In addition, the object explorer details window allows the administrator or the developer to script out the object.

Practice Exercises/How To…?

It’s time to practice! The practice exercises for Object Explorer and the Object Explorer details are fast, simple and easy.

Object Explorer

  1. Explore how to start and stop the SQL Server and the SQL Server Agent services via the Object Explorer window
  2. From the AdventureWorks2008R2 database, attempt to script at least 2 similar objects (stored procedures, triggers, etc) to a single script together

Object Explorer Details

  1. Create the following stored procedure within the AdventureWorks2008R2 database
    CREATE PROCEDURE proc_tmpOESearch
    AS
    BEGIN
        PRINT 'BeyondRelational.com'
    END
    GO
      
    • Search for the text – “BeyondRelational” within the AdventureWorks2008R2 database. Are any results returned?
    • Now, search on the object name – “OESearch” within the AdventureWorks2008R2 database. Are any results returned?
  2. Search for the object names using wild cards  – “dm_os%counters” within the AdventureWorks2008R2 database
  3. Can you search for objects using the .NET regular expressions?
  4. From the AdventureWorks2008R2 database, attempt to script at least 2 similar objects (stored procedures, triggers, etc) to a single script together. Are the results different from the Object Explorer 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!