Home > SQL Server Tips > > Working with schemas in SQL Server 2005
SQL Server Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 


Working with schemas in SQL Server 2005


Adam Machanic, Contributor
04.25.2006
Rating: -4.49- (out of 5)


Expert advice on database administration
Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


If you were to ask a group of database administrators which key personality trait they have that helps them do their jobs well, the most important and popular answer would be an excellent sense of organization. Great DBAs organize everything in the database -- from the data itself to the backup schedule -- with a level of precision that has given them a reputation as a slightly anal-retentive group in the IT world.

DBAs use their sense of organization to keep the database working properly, but many things can get in the way -- not the least of which is "object bloat," the sense that there are just too many objects in a given database. Managing databases that have become overfilled with tables, stored procedures and views can be utterly confusing on the best of days, and they quickly become tiresome. A tired DBA can't do a good job of ensuring data quality.

Unfortunately, previous versions of SQL Server didn't help much in this regard. The only way to easily manage a huge number of objects was to split them up and create one database for each logical subset -- one database for the sales department, another for marketing, still another for human resources, etc.

Creating all of these databases helped address the table management problem; now there was no question about where to look for a specific type of data. But, alas, the multi-database solution created other problems. DBAs soon discovered the joys of backing up all of those databases and then worrying about creating a separate maintenance plan for each. This is in addition to cross-database foreign keys, which don't exist in SQL Server. And need I bring up permissions? If the mere mention of the term "cross-database ownership chaining" makes you shudder, you know what I'm talking about.

If you're still stuck in this multiple-database nightmare, it might be time to wake up and start thinking about consolidation. SQL Server 2005, thanks to its implementation of an ANSI SQL feature called schemas, fixes many issues that drove many DBAs to split things up -- and it brings a few nice bonus features as well.

Creating and using schemas

A schema is nothing more than a named, logical container in which you can create database objects. A new schema is created using the CREATE SCHEMA DDL statement. For instance, you might create a schema for sales-related data by using the following T-SQL:

CREATE SCHEMA Sales
GO

Once created, you can add objects, such as tables or stored procedures, to the schema. To do so, you must prefix them with the schema name:

Just as you might expect, you can access an object by referencing it by schema name:

In SQL Server 2005, every object participates in a schema, even if you don't explicitly specify one. Creating an object without specifying the schema will cause it to be created in your default schema. A default schema can be assigned to a user when the user is created, but if it is not specified, the dbo schema will be used. Since any ...


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google



RELATED CONTENT
SQL Server Security
Password cracking tools for SQL Server
Meet compliance requirements with improved database security practices
Hardening the network and OS for SQL Server security
Securing the server and database in SQL Server
SQL Server security made simple and sensible
Blog: Protect your databases from the internal threat
Setting up SQL Server Service Broker for secure communication
The keys to database backup protection for SQL Server
Understanding transparent data encryption in SQL Server 2008
The fine line between not encrypting your databases and breach notification

SQL Server Database Modeling and Design
Optimizing SQL Server indexes –- even when they're not your indexes
Top tips and tricks for SQL Server database development
Managing the development lifecycle with Visual Studio Team System 2008
A first look at Visual Studio Team System 2008 Database Edition
Testing transaction log autogrowth behavior in SQL Server
Top 10 SQL Server Tips of 2008
Tutorial: SQL Server indexing tips to improve performance
Tutorial: Learn SQL Server basics from A-Z
SQL Server database design disasters: How it all starts
Can you shrink your SQL Server database to death?

Microsoft SQL Server 2005
End of life comes for SQL Server 2005 SP2, 2008
SQL Server Reporting Services Fast Guide
SQL Server Service Broker Tutorial and Reference Guide
Tips for tuning SQL Server 2005 to improve reporting performance
SQL Server consolidation: Why it's an optimization technique
Parent-child dimensions in SQL Server 2005 with Analysis Services MDX
Enforcing data integrity in a SQL Server database
SSIS error message due to installation problem on SQL Server 2005
Should you upgrade to SQL Server 2005 or SQL Server 2008?
Basics for working with DATETIME and SMALLDATETIME in SQL Server 2005
Microsoft SQL Server 2005 Research

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
data corruption  (SearchSQLServer.com)
data hiding  (SearchSQLServer.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary


given database user might belong to a different default schema, it's a good idea to always scope tables by schema name. Even if your table is in the dbo schema, you should use two-part naming, such as the following:

You can also transfer objects between schemas. That's done by using the TRANSFER option of ALTER SCHEMA. To transfer the SalesPeople table from the Sales schema into the dbo schema, the following T-SQL would be used:

Database organization

Schemas are truly great from an organizational point of view. The following screenshot is an image of some tables from the AdventureWorks sample database, as viewed in SQL Server Management Studio:

[IMAGE]

This cross-section of tables includes human resources-related data, data about people, and production information -- all logically separated by virtue of participating in separate schemas. These tables are all in the same database, so they can share references, filegroups, backup and maintenance schemas, or anything else that tables in the same database can do together. In other words, you get all of the benefits of splitting up the database and none of the problems that might have driven you to want to split it up in the first place.

Assigning schema permissions

Another great benefit of schemas is that you no longer need to worry about assigning users' rights to objects on a granular basis. Rather than create roles for every combination of users, or having to maintain permissions for groups of objects on a per-user basis, schemas allow you to assign rights in blocks. Once assigned schema-level permission, a user will have that right for any object in the schema.

Keep in mind that granting permissions on a schema is a bit different than granting permissions for many other objects. The following does not work:

GRANT SELECT ON SchemaName TO UserName

Instead, you need to scope the grant and specify that it's for a schema:

GRANT SELECT ON SCHEMA::SchemaName TO UserName

Database build scripts

Finally, I'd like to touch upon a little-known feature that's actually been around in SQL Server for quite a while. You might be surprised to learn that the CREATE SCHEMA statement is not actually new to SQL Server; it was added to the product in SQL Server 2000, but it didn't have much functionality until now.

What it did have then and still has today is the ability to allow a user to create objects that reference each other, out of order. That can be tremendously useful for development teams that keep database objects scripted in a source-control system, broken up into one file per object. The problem occurs when building a database out of the objects, which begs the question: How do you know the order in which to concatenate the files? For example, assume you have the DDL (data description language) for a table of Web site users and a table of logins for those users. If you concatenate the files in alphabetical order, you'll end up with the following T-SQL, which fails when run:

Reversing the order doesn't help either. How will you deal with the Products table, which contains products that are sold, and the Sales table, which details which products were sold to which customers?

Luckily, schemas solve this problem nicely. When creating a schema, you can specify additional DDLs to define the objects that will go in the schema -- and SQL Server takes care of the ordering. To create the Logins and Users' tables shown above, just put them into a schema together:

Summary

Support for schemas can help solve a surprisingly large number of issues that have faced DBAs in past versions of SQL Server. Database consolidation and security management are easier, organization is better defined and even build scripts are easier to create. Schemas may not fix all of your problems as a DBA, but they will make things a lot more straightforward in many cases.

More information from SearchSQLServer.com

  • Tip: Granting permissions in SQL Server 2005
  • E-book: When, why and how to consolidate SQL Servers
  • Book Excerpt: Get up to speed on new security features in SQL Server 2005

  • Rate this Tip
    To rate tips, you must be a member of SearchSQLServer.com.
    Register now to start rating these tips. Log in if you are already a member.




    DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.



    SQL Server Development - .NET, C#, T-SQL, Visual Basic
    HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
    About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
    SEARCH 
    TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

    TechTarget Corporate Web Site  |  Media Kits  |  Site Map




    All Rights Reserved, Copyright 2005 - 2009, TechTarget | Read our Privacy Policy
      TechTarget - The IT Media ROI Experts