#0133 – SQL Server – SSMS – Tutorial – 08 – How SSMS helps in reviewing and configuring your SQL Server Instance (L200)


One of the most important aspects of SQL Server administration and maintenance is the ability to review and changing the existing configuration of the server. In Part 01 of this tutorial series, I had mentioned that one of the key responsibilities of SSMS was to replace the erstwhile SQL Server Enterprise Manager – the interface that is used to manage & maintain the SQL Server instance configuration. Today, we will look at some of the windows and wizards that can be used to configure your SQL Server instance.

Reviewing & Changing Instance-level configuration

Using the Object Explorer, you can review the instance-level configuration (provided you have sufficient privileges, of course) for all servers that you are connected to. Simply right-click on the instance name and select “Properties” from the pop-up menu to launch the SQL Server instance properties window.

image image

The base or “general” view of the window is a read-only view that provides details on the SQL Server build, hose operating system version, number of processors and memory, SQL Server collation and high-availability configuration values.

Navigating out to any of the child nodes (“Database settings” node visible in the screenshot below), allows us to view two sets of values – the “configured” values, and the “running” values.

  • Configured values: These are editable values, and display the configured values for the options on this pane. If you change these values, click Running Values to see whether the changes have taken effect. If they have not, the instance of SQL Server must be restarted first.
  • Running values: View the currently running values for the options on this pane. These values are read-only

image

Below is a summary of the various child nodes in the Server Properties window:

Page Brief description Further help from BOL
Memory Adjust the memory allocated to the given SQL Server instance, index creation and query execution operations http://msdn.microsoft.com/en-us/library/ms181453.aspx
Processors Adjust processor/IO affinity, NUMA configuration, lightweight pooling, max. worker threads and sql server process priority http://msdn.microsoft.com/en-us/library/ms189435.aspx
Security Choose the authentication mechanism, audit logging, cross-database chaining, C2 auditing and other security configurations. http://msdn.microsoft.com/en-us/library/ms188470.aspx
Connections Adjust default connection options, query governor, remote connections, distributed transactions and max. concurrent connections http://msdn.microsoft.com/en-us/library/ms180124.aspx
Database Settings Adjust database options – index fill factor, backup set options, compress backups, recovery intervals and default data & log file paths http://msdn.microsoft.com/en-us/library/ms178521.aspx
Advanced Enable Containment & FILESTREAM, allow cascading triggers, adjust 2-digit year cutoff, full-text settings, parallelism and network options http://msdn.microsoft.com/en-us/library/ms189357.aspx
Permissions Assign permissions to instance level logins and roles. (Not found on BOL)

Reviewing & Configuring database-level configuration

Similar to the instance-level properties page, simply right-click on the database name and select “Properties” from the pop-up menu to launch the database properties window. Please note that this window does not have the concept of “configured” and “running” values. Any changes you make are in effect for ever new connection to the database going forward.

The screenshot below shows the “General” page, which displays the following information:

  • Last backup information
  • Database creation date, status
  • Database owner
  • Space available in the database
  • Current Number of concurrent users connected to the database
  • Database collation

image

Below is a summary of the various child nodes in the Database Properties window:

Page Brief Description Further help in BOL
Files Database file paths, change database owner, enable use of full-text indexes
(NOTE: Once enabled, full-text indexing cannot be turned off)
http://msdn.microsoft.com/en-us/library/ms180254.aspx
Filegroups Adjust row filegroups and FILESTREAM data filegroups http://msdn.microsoft.com/en-us/library/ms187567.aspx
Options Manage collation, recovery model, compatibility level, containment, database state, AUTO options, Cursor behaviour, FILESTREAM, Service Broker, recovery, ANSI and other miscellaneous options http://msdn.microsoft.com/en-us/library/ms188124.aspx
Change Tracking Manage change tracking for the database http://msdn.microsoft.com/en-us/library/bb895205.aspx
Permissions Manage database permissions to users or roles (Not found on BOL)
Extended Properties Manage database extended properties, typically used for documentation purposes (Not found on BOL)
Mirroring Configure database mirroring and associated security options http://msdn.microsoft.com/en-us/library/ms183684.aspx
Transaction Log Shipping Configure log shipping – define secondary instances and databases, enable current database a primary database in the log shipping configuration, establish a monitor instance and finally, script all changes for future reference! http://msdn.microsoft.com/en-us/library/ms186910.aspx

Scripting changes for future reference

Whenever a SQL Server configuration change is required, it needs to be planned and scheduled for execution during an outage. There too, the team implementing the change may or may not be the same as those recommending the change. In such cases, it becomes essential to script the changes made so that the change can be supplied to the implementation team for:

  1. Record keeping – for future reference
  2. Scheduled deployment – the required change has been scripted, so it can be applied whenever the outage window permits
  • Login to your SQL Server instance using SSMS
  • From the object explorer, right-click on the SQL server instance name to bring up the instance properties window
  • Go to the “Security” tab
  • Assume that we want to switch from “Windows Authentication mode” to "mixed” mode. Do NOT apply the change
  • image
  • Click on the little arrow near the “script” button at the top
  • image
  • Choose “Script Action to New Query Window” or press Ctrl+Shift+N
  • Notice that a new query window opens up with the underlying change scripted and ready for execution
  • image
  • USE [master]
    GO
    EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'SoftwareMicrosoftMSSQLServerMSSQLServer', N'LoginMode', REG_DWORD, 2
    GO
  • The change can now be executed during the regular maintenance window for an instance
  • Practice Exercises…

    The properties page is available for every distinct object visible within the Object Explorer.

    • Explore the properties for your SQL login
    • Define an idle CPU condition for the SQL Server agent using the using the SQL Server Agent properties 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

    #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