• Save
9767401 - Creating Databases and Database Files
Upcoming SlideShare
Loading in...5
×
 

9767401 - Creating Databases and Database Files

on

  • 578 views

SQL - Creating Databases and

SQL - Creating Databases and
Database Files

Statistics

Views

Total Views
578
Views on SlideShare
577
Embed Views
1

Actions

Likes
0
Downloads
0
Comments
0

1 Embed 1

http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

9767401 - Creating Databases and Database Files 9767401 - Creating Databases and Database Files Document Transcript

  • Module 1Creating Databases andDatabase FilesContents:Lesson 1: Creating Databases 1-2Lesson 2: Creating Filegroups 1-15Lesson 3: Creating Schemas 1-22Lesson 4: Creating Database Snapshots 1-28Lab: Creating a Database 1-34
  • Information in this document, including URL and other Internet Web site references, is subject to changewithout notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with anyreal company, organization, product, domain name, e-mail address, logo, person, place or event is intended orshould be inferred. Complying with all applicable copyright laws is the responsibility of the user. Withoutlimiting the rights under copyright, no part of this document may be reproduced, stored in or introduced intoa retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying,recording, or otherwise), or for any purpose, without the express written permission of MicrosoftCorporation.The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoftmakes no representations and warranties, either expressed, implied, or statutory, regarding thesemanufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer orproduct does not imply endorsement of Microsoft of the manufacturer or product. Links are provided tothird party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for thecontents of any linked site or any link contained in a linked site, or any changes or updates to such sites.Microsoft is not responsible for webcasting or any other form of transmission received from any linked site.Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not implyendorsement of Microsoft of the site or the products contained therein.Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rightscovering subject matter in this document. Except as expressly provided in any written license agreementfrom Microsoft, the furnishing of this document does not give you any license to these patents, trademarks,copyrights, or other intellectual property.©2006 Microsoft Corporation. All rights reserved.Microsoft, JScript, MSDN, Outlook, PowerPoint, Visual Basic, Visual C#, Visual C++, Visual FoxPro, Windows,and Windows Server are either registered tradmarks or trademarks of Microsoft Corporation in the UnitedStates and/or other countries.The names of actual companies and products mentioned herein may be the trademarks of their respectiveowners.
  • Module 1: Creating Databases and Database Files 1–1**************************************** Illegal for non-trainer use ***************************************Module objectives After completing this module, students will be able to: ■ Create databases. ■ Create filegroups. ■ Create schemas. ■ Create database snapshots.Introduction One of the most fundamental tasks that a database developer must perform is the creation of a database and its major components, such as filegroups and schemas. In this module, you will learn how to create databases, filegroups, schemas, and database snapshots.
  • 1–2 Module 1: Creating Databases and Database FilesLesson 1: Creating Databases**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe the considerations for creating a database. ■ Describe the transaction logging process and considerations for log file location. ■ Describe database options. ■ Describe the sources of database information.Introduction As a database developer, you might be expected to plan, design, and implement databases. You might also be expected to work with existing databases that you or other developers have previously created. Because a database forms a critical part of many business applications, it is important to understand how databases are created and what the common database creation options are. This lesson describes the various considerations that you should take into account when designing a Microsoft® SQL Server™ 2005 database. You will also learn how the SQL Server 2005 transaction log works, how to set database options, and how to view metadata about a database and its objects.
  • Module 1: Creating Databases and Database Files 1–3Considerations for Creating a Database**************************************** Illegal for non-trainer use ***************************************Introduction You can use SQL Server to perform transaction processing, store and analyze data, and build new database applications. SQL Server is a family of products and technologies that meets the data storage requirements of online transaction processing (OLTP) and online analytical processing (OLAP) environments. SQL Server is a relational database management system (RDBMS) that: ■ Manages data storage for transactions and analysis. ■ Stores data in a wide range of data types, including text, numeric, Extensible Markup Language (XML), and large objects. ■ Responds to requests from client applications. ■ Uses Transact-SQL, XML, or other SQL Server commands to send requests between a client application and SQL Server. The RDBMS component of SQL Server is responsible for: ■ Maintaining the relationships among data in a database. ■ Ensuring that data is stored correctly and that the rules defining the relationships among data are not violated. ■ Recovering all data to a point of known consistency, in the event of a system failure.OLTP databases Relational tables organize data in an OLTP database to reduce redundant information and to increase the speed of updates. SQL Server enables a large number of users to perform transactions and simultaneously change real-time data in OLTP databases.OLAP databases OLAP technology is used to organize and summarize large amounts of data so that an analyst can evaluate data quickly and in real time. Microsoft SQL Server Analysis
  • 1–4 Module 1: Creating Databases and Database Files Services organizes this data to support a wide array of enterprise solutions, from corporate reporting and analysis to data modeling and decision support.Considerations when When planning a new database, you should take several aspects into consideration.planning a database These include, but are not limited to, the following: ■ Purpose of data storage OLTP and OLAP databases have different purposes and, therefore, different design requirements. ■ Transaction throughput. OLTP databases often have a high requirement for the number of transactions that can be processed per minute, hour, or day. An efficient design with an appropriate level of normalization, indexes, and data partitions can achieve a very high level of transaction throughput. ■ Potential growth of physical data storage. Large amounts of data require appropriate hardware for memory, hard disk space, and central processing unit (CPU) power. Estimating the amount of data that your database will store over subsequent months and years will help to ensure that your database continues to work efficiently. You can configure databases so that files grow automatically up to a maximum specified size. However, automatic file growth can affect performance. In most server-based database solutions, you should create the database with appropriately sized files, monitor space usage, and reallocate more space only when necessary. ■ File location. Where you place the database files can have an impact on performance. If you are able to use multiple disk drives, you can spread your database files across more than one disk. This enables SQL Server to take advantage of multiple connections and multiple disk heads for efficient reading and writing of data. For More Information For more information about estimating database sizes, see “Estimating the Size of a Database,” in SQL Server Books Online.Example of creating a You can create a database by using the visual tools in SQL Server Management Studio ordatabase the CREATE DATABASE Transact-SQL statement. The following example shows how to create a database by using Transact-SQL. CREATE DATABASE TestDB ON (NAME = TestDB_Data, FILENAME = D:DATATransactTestDB.mdf, SIZE = 20 MB, FILEGROWTH = 0) LOG ON (NAME = TestDB_Log, FILENAME = D:DATATestDB_Log.ldf, SIZE = 5 MB, FILEGROWTH = 0) For More Information For more information about creating databases using Transact-SQL, see “CREATE DATABASE (Transact-SQL),” in SQL Server Books Online.
  • Module 1: Creating Databases and Database Files 1–5Transaction Logging**************************************** Illegal for non-trainer use ***************************************Transaction A transaction is a single unit of work in a database. The acronym ACID is often used to describe the characteristics of a transaction. ACID stands for: ■ Atomicity. A transaction is an atomic unit; either all operations defined in the transaction are completed, or none of them are completed. ■ Consistency. A transaction always leaves the data in a consistent state. ■ Isolation. A transaction operates in isolation from other database activity; other concurrent database activity has no effect on the transaction. ■ Durability. When a transaction is committed, the results are stored in persistent storage and will survive system failure. SQL Server supports implicit transactions for individual statements that modify data and explicit transactions for multiple statements that must be executed as a unit.Transaction log SQL Server records every transaction in a write-ahead transaction log to maintain database consistency and to aid in recovery of a database failure. The log is a storage area that automatically tracks changes to a database. SQL Server records on disk modifications in the log as the modifications are executed and before they are written in the database.Logging process The logging process is as follows: 1. The application sends a data modification. 2. When a modification is executed, the affected data pages are loaded from disk into the buffer cache, provided that the pages are not already in the buffer cache from a previous query. 3. The log records each data modification statement as the modification is made. The change is always recorded in the log and written to disk before that change is made in the database. This type of log is called a write-ahead log.
  • 1–6 Module 1: Creating Databases and Database Files 4. On a recurring basis, the checkpoint process writes all completed transactions to the database on the disk. If the system fails, the automatic recovery process uses the transaction log to roll forward all committed transactions and roll back any incomplete transactions. The log uses transaction markers during automatic recovery to determine the starting and ending points of a transaction. A transaction is considered complete when the BEGIN TRANSACTION marker has an associated COMMIT TRANSACTION marker. Data pages are written to the disk when a checkpoint occurs. For More Information For more information about the checkpoint process and when it occurs, see “Checkpoints and the Active Portion of the Log,” in SQL Server Books Online.Log file location To improve performance, it is recommended that you place a transaction log file on aconsiderations separate physical disk from your data files. This reduces contention and enables one set of drive heads to record transactions in the transaction log while other heads read data from data files at the same time. Updating data is fast because the transactions can be written immediately to disk without waiting for the completion of data reads. Because log files are written sequentially, if the log is stored on a dedicated disk, the disk heads remain in the correct position for the next write operation.
  • Module 1: Creating Databases and Database Files 1–7Database Options**************************************** Illegal for non-trainer use ***************************************Introduction After you have created a database, you can set the database options by using the visual tools in SQL Server Management Studio or the ALTER DATABASE Transact-SQL statement. You can configure a number of database options, but you are able to set them for only one database at a time. To affect options in all new databases, you should modify the model database.Database option More than 25 database options are grouped into various option categories to makecategories management easier. The following table lists some of the more frequently used options. Database option category Database option Description Automatic AUTO_CREATE_STATISTICS Automatically creates any missing statistics needed by a query for optimization. The default is ON. AUTO_UPDATE_STATISTICS Automatically updates out-of-date statistics required by a query for optimization. The default is ON. AUTO_CLOSE Automatically closes a database when the last user exits if set to ON. The default is OFF for all versions of SQL Server 2005 except SQL Server 2005 Express. AUTO_SHRINK The database files are candidates for periodic shrinking if set to ON. The default is OFF.
  • 1–8 Module 1: Creating Databases and Database Files Database option category Database option Description Availability OFFLINE | ONLINE | Controls whether the database is EMERGENCY online or offline. EMERGENCY stops non-system administrators from connecting and makes the database read-only. The default is ONLINE. READ_ONLY | READ_WRITE Controls whether users can modify data. The default is READ_WRITE. SINGLE_USER | Controls which users are able to RESTRICTED_USER | connect to the database. MULTI_USER SINGLE_USER allows only one user to connect. RESTRICTED_USER allows members of the db_owner database role and dbcreator and sysadmin server roles to connect. MULTI_USER allows any user to connect that has appropriate security permissions. The default is MULTI_USER. Cursor CURSOR_CLOSE_ON_COMMI Automatically closes open cursors T when a transaction is committed. The default is OFF, and cursors remain open. CURSOR_DEFAULT CURSOR_DEFAULT_LOCAL limits the scope of the cursor. This option is local to the batch, stored procedure, or trigger in which the cursor was created. CURSOR_DEFAULT_GLOBAL is the default option setting; the scope of the cursor is global to the connection. Recovery RECOVERY FULL provides full recoverability from media failure and is the default. BULK_LOGGED uses less log space because logging is minimal, but it has a greater risk of exposure. SIMPLE recovers the database only to the last full database backup or last differential backup.
  • Module 1: Creating Databases and Database Files 1–9Databaseoptioncategory Database option Description PAGE_VERIFY Allows SQL Server to detect incomplete input/output (I/O) operations caused by power failures or other system outages. CHECKSUM stores a calculated value in the page header based on the contents of the page. This value is recalculated and compared to the stored version when data pages are read from the disk. This is the default value. TORN_PAGE_DETECTION stores a specific bit for each 512-byte sector in the 8-kilobyte (KB) data page as part of the page header. The bits stored in the page header are compared to the actual page sector information when data pages are read from the disk.SQL ANSI_NULL_DEFAULT Allows the user to control the database default nullability. SQL Server 2005 defaults to OFF and therefore NOT NULL. ANSI_NULLS When ON, all comparisons to a null value evaluate to NULL (unknown). When OFF, comparisons of non- Unicode values to a null value evaluate to TRUE if both values are NULL. By default, the ANSI_NULLS database option is OFF. RECURSIVE_TRIGGERS Controls whether recursive firing of AFTER triggers is allowed. The default is OFF, which prevents direct recursion.For More Information For more information about altering databases usingTransact-SQL, see “ALTER DATABASE (Transact-SQL),” in SQL Server Books Online.
  • 1–10 Module 1: Creating Databases and Database FilesSources of Database Information**************************************** Illegal for non-trainer use ***************************************Introduction You can view system metadata about your databases in two distinct ways. When you need to view information about a database object, the easiest way is to use SQL Server Management Studio. When you write applications that retrieve metadata about the database objects, you should use Transact-SQL to query the system-supplied catalog views, utilize the system functions, or execute the system stored procedures. Note SQL Server 2005 also supports information schema views that provide an internal, system table–independent view of the SQL Server metadata. These views conform to the American National Standards Institute (ANSI) structured query language (SQL) standard definition for the information schema. Although these views are supported for backward compatibility, catalog views are the recommended way to query database metadata.SQL Server Management SQL Server Management Studio provides visual tools to display database metadataStudio within the management environment. The following table lists the most commonly used tools. SQL Server Management Studio tool Description Object Explorer Object Explorer is a graphical tool for locating and managing servers, databases, and database objects. Properties window Each database object within Object Explorer has an associated Properties window that is accessible by right- clicking the object and then clicking Properties. The Properties window varies depending on the type of object selected.
  • Module 1: Creating Databases and Database Files 1–11 SQL Server Management Studio tool Description Reports SQL Server Management Studio includes a set of reports for various nodes provided within Object Explorer by the SQL Server Report Server engine. Commonly used nodes that can display reports include the following: ■ Server ■ Database ■ Service Broker, beneath a Database node ■ Logins, beneath the Security node ■ ManagementCatalog views Catalog views enable you to query metadata about SQL Server database objects, such as tables, stored procedures, and constraints. A few of the catalog views list server-wide information, but the majority are database-specific. Catalog views are listed in the ViewsSystem Views folder for each database in Object Explorer in SQL Server Management Studio. Although you can query them by using standard Transact-SQL syntax as for user-defined views, they are not actually implemented as traditional views on underlying tables but instead directly query the system metadata. There are more than 200 catalog views, and they are defined in the sys schema. Catalog views are categorized according to their function. The following table lists some of the key categories and a few of the commonly used catalog views within each category. Category Catalog view Description Databases sys.database_files Returns one row for each file of a and files database Objects sys.columns Returns one row for each column of an object that contains columns (for example, a table or a view) sys.events Returns one row for each event for which a trigger or notification fires sys.indexes Returns one row for each index or heap of a tabular object sys.tables Returns one row for each table in the database sys.views Returns one row for each view in the database Schemas sys.schemas Returns one row for each schema defined in the database Security sys.database_permissions Returns one row for each permission defined in the database sys.database_principals Returns one row for each security principal in the database sys.database_role_members Returns one row for each member of each database role
  • 1–12 Module 1: Creating Databases and Database Files For More Information For more information about catalog views, see “Catalog Views (Transact-SQL),” in SQL Server Books Online.Metadata functions SQL Server 2005 defines several categories of functions that return information about the database and database objects. Whereas catalog views return multiple rows of information, these functions return only a single value and are known as scalar functions. The following list describes some commonly used metadata functions: ■ DB_ID. Returns the database identification (ID) number for a specified database name, or the current database if no name is specified. ■ DB_NAME. Returns the database name for a specified database ID, or the current database if no ID is specified. ■ FILE_ID. Returns the file ID for the given logical file name in the current database. ■ FILE_NAME. Returns the logical file name for the given file ID. ■ FILEGROUP_ID. Returns the filegroup ID for a specified filegroup name. ■ FILEGROUP_NAME. Returns the filegroup name for the specified filegroup ID. For More Information For more information about metadata functions, see “Metadata Functions (Transact-SQL),” in SQL Server Books Online.System stored SQL Server 2005 provides numerous system stored procedures for retrieving databaseprocedures metadata. These procedures provide an alternative way to query information that the catalog views provide and some accept procedure arguments to allow customization of the result sets. The following list describes some commonly used system stored procedures of the hundreds available: ■ sp_databases. Lists databases that are available within an instance of SQL Server or are accessible through a database gateway. ■ sp_stored_procedures. Returns a list of stored procedures in the current database. ■ sp_help. Reports information about a database object, a user-defined data type, or a data type supplied by SQL Server 2005. For More Information For more information about system stored procedures, see “System Stored Procedures (Transact-SQL),” in SQL Server Books Online.
  • Module 1: Creating Databases and Database Files 1–13Practice: Creating Databases**************************************** Illegal for non-trainer use ***************************************Goals The goal of this practice is to enable you to create a database by using SQL Server Management Studio and by using Transact-SQL. In this practice, you will use both techniques to create a new database.Preparation Ensure that the virtual machine 2779A-MIA-SQL-01 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.To create a database by Perform the following steps to create a database by using SQL Server Managementusing SQL Server Studio:Management Studio 1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, specify the values in the following table, and then click Connect. Property Value Server type Database Engine Server name MIAMI Authentication Windows Authentication 3. If Object Explorer is not visible, click Object Explorer on the View menu. 4. In Object Explorer, right-click Databases, and then click New Database.
  • 1–14 Module 1: Creating Databases and Database Files 5. In the New Database dialog box, enter the details in the following table. Property Value Database name TestDB Initial Size for TestDB 20 6. In the Autogrowth column of the TestDB entry, click the ellipsis button (...). 7. In the Change Autogrowth for TestDB dialog box, clear the Enable Autogrowth check box, and then click OK. 8. Change the Initial Size setting for the TestDB_log entry to 5 MB. 9. In the Autogrowth column of the TestDB_log entry, click the ellipsis button (...). 10. In the Change Autogrowth for TestDB_log dialog box, clear the Enable Autogrowth check box and click OK. 11. In the New Database dialog box, click OK to create the database. 12. In Object Explorer, expand the Databases folder to verify that TestDB has been created; if TestDB is not listed, right-click the Databases folder and click Refresh. 13. Keep SQL Server Management Studio open. You will use it in the next procedure.To create a database by Perform the following steps to create a database by using Transact-SQL:using Transact-SQL 1. In SQL Server Management Studio, click the New Query button on the toolbar. 2. In the new, blank query window, type the following Transact-SQL code (each FILENAME parameter should be on a single line). CREATE DATABASE TransactTestDB ON (NAME = TransactTestDB, FILENAME = C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDATATransactTestDB.mdf, SIZE = 20 MB, FILEGROWTH = 0) LOG ON (NAME = TransactTestDB_Log, FILENAME = C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDATATransactTestDB_Log.ldf, SIZE = 5 MB, FILEGROWTH = 0) 3. Click the Execute button on the toolbar. 4. When the command has completed successfully, right-click the Databases folder in Object Explorer, and then click Refresh to verify that the TransactTestDB database has been created. 5. Close SQL Server Management Studio. Click No if prompted to save files.
  • Module 1: Creating Databases and Database Files 1–15Lesson 2: Creating Filegroups**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Explain what filegroups are. ■ Decide when to create filegroups.Introduction SQL Server 2005 stores data in data files that can then be grouped together into one or more filegroups. Although a database can run successfully with only one filegroup, there are times when it might be advantageous to create multiple filegroups. In this lesson, you will learn about filegroups and how they can improve database performance, maintenance, and design. You will also learn how to create filegroups.
  • 1–16 Module 1: Creating Databases and Database FilesWhat Are Filegroups?**************************************** Illegal for non-trainer use ***************************************Introduction A filegroup is a logical collection of data files that enables administrators to manage all files within the filegroup as a single item. The ability to control the physical placement of individual objects in the database can provide a number of manageability and performance benefits. For example, you can use multiple filegroups to control how the data in a database is stored physically on storage devices and to separate read/write data from read-only data.Types of filegroups SQL Server 2005 has a primary filegroup and can also have user-defined filegroups. ■ The primary filegroup contains the primary data file with the system tables. The primary data file typically uses the .mdf extension. ■ A user-defined filegroup consists of data files that are grouped together for allocation and administrative purposes. These other data files are known as secondary data files and typically use the .ndf extension.Example scenario for The illustration provides an example of how you might place database files on separatemultiple filegroups disks, as described in the following list: ■ You can create user-defined filegroups to separate files that are heavily queried from those that are heavily modified. In the illustration, the OrdHist1.ndf and OrdHist2.ndf files are placed on a separate disk from the Product, Customer, and SalesOrderHeader tables because they are queried for decision support rather than updated with current order information. ■ You could also place the OrdHist1.ndf and OrdHist2.ndf files on separate disks if they are both heavily queried. ■ You cannot place transaction log files in filegroups. Transaction log space is managed separately from data space. Transaction logs typically use the .ldf extension.
  • Module 1: Creating Databases and Database Files 1–17The following Transact-SQL code sample uses the CREATE DATABASE statement toimplement this scenario. CREATE DATABASE [AdventureWorks] ON PRIMARY ( NAME = NAdventureWorks_Data, FILENAME = NC:AdventureWorks_Data.mdf ), FILEGROUP [OrderHistoryGroup] ( NAME = NOrdHist1, FILENAME = ND:OrdHist1.ndf ), ( NAME = NOrdHist2, FILENAME = ND:OrdHist2.ndf ) LOG ON ( NAME = NAdventureWorks_log, FILENAME = NE:AdventureWorks_log.ldf)You can also use the ALTER DATABASE statement to add or delete files and filegroupson existing databases.For More Information For more information about filegroups, see “PhysicalDatabase Files and Filegroups,” in SQL Server Books Online.
  • 1–18 Module 1: Creating Databases and Database FilesWhen to Create Filegroups**************************************** Illegal for non-trainer use ***************************************Introduction You can create multiple data files on separate disks and create a user-defined filegroup to contain the files. The two main reasons for using filegroups are to improve performance and to control the physical placement of data.Using multiple files in a Although redundant array of independent disks (RAID) is a preferred way to improvesingle filegroup for the performance of a database, you can assign multiple files on separate disks to a singleperformance filegroup to improve performance by implementing a form of data striping within SQL Server. Because SQL Server uses a proportional fill strategy when writing data to a filegroup, the data is essentially striped across the files and, therefore, across the physical disk partitions. This approach enables finer-grained control over data striping than can be achieved when creating a volume stripe set in the Windows operating system or by using a RAID array controller. Note In most cases, using the striping capabilities of RAID provides much of the same performance gain that you might achieve by using user-defined filegroups, without the added administrative burden of defining and managing the filegroups.Using multiple filegroups To use filegroups to simplify maintenance or achieve design goals, you can:to control physical dataplacement ■ Store read/write data separately from read-only data to keep different kinds of disk I/O activity separate. ■ Store indexes on separate disks from tables, which can lead to improved performance. ■ Back up or restore individual files or filegroups instead of backing up or restoring an entire database. Backing up files or filegroups might be necessary for large databases to have an effective backup and restore strategy. ■ Group tables and indexes with similar maintenance requirements into the same filegroups. You might want to perform maintenance on some objects more frequently than on others. For example, by creating two filegroups and assigning
  • Module 1: Creating Databases and Database Files 1–19 tables to them, you can run daily maintenance tasks against the tables in a daily group and weekly maintenance tasks against the tables in a weekly group. This limits disk contention between the two filegroups.■ Separate user tables and other database objects from the system tables in the primary filegroup. You should also change the default filegroup to prevent unexpected table growth from constraining the system tables in the primary filegroup.■ Store the partitions of a partitioned table in multiple filegroups. This is a good way to physically separate data with different access needs within a single table and can also provide manageability and performance benefits.
  • 1–20 Module 1: Creating Databases and Database FilesPractice: Creating Filegroups**************************************** Illegal for non-trainer use ***************************************Goals The goal of this practice is to enable you to create filegroups by using SQL Server Management Studio and by using Transact-SQL. In this practice, you will use both techniques to create a new database filegroup.Preparation Note This practice requires that you have completed the preceding practice. Ensure that virtual machine 2779A-MIA-SQL-01 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.To create a filegroup by Perform the following steps to create a filegroup by using SQL Server Managementusing SQL Server Studio:Management Studio 1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, specify the values in the following table, and then click Connect. Property Value Server type Database Engine Server name MIAMI Authentication Windows Authentication 3. If Object Explorer is not visible, click Object Explorer on the View menu.
  • Module 1: Creating Databases and Database Files 1–21 4. In Object Explorer, expand Databases. 5. Right-click TestDB, and then click Properties. 6. In the Database Properties - TestDB dialog box, click Filegroups in the Select a page pane, and then click Add. 7. Enter the settings in the following table. Property Value Name SECONDARY Default Selected 8. Click Files in the Select a page pane, and then click Add. 9. Enter the settings in the following table. Property Value Logical Name TestDB2 File Type Data Filegroup SECONDARY 10. In the Database Properties - TestDB dialog box, click OK to create the new file and filegroup. 11. If the TestDB node is not selected, click TestDB. 12. In the Summary tab, click Report. When the report is displayed, expand Disk Space Used by Data Files. The report should show the two filegroups and the list of files for each group. 13. Keep SQL Server Management Studio open. You will use it in the next procedure.To create a filegroup by Perform the following steps to create a filegroup by using Transact-SQL:using Transact-SQL 1. In SQL Server Management Studio, click the New Query button on the toolbar. 2. In the new, blank query window, type the following Transact-SQL code. ALTER DATABASE [TransactTestDB] ADD FILEGROUP [SECONDARY] GO ALTER DATABASE [TransactTestDB] ADD FILE ( NAME = NTest2, FILENAME = NC:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDataTest2.ndf) TO FILEGROUP [SECONDARY] GO ALTER DATABASE [TransactTestDB] MODIFY FILEGROUP [SECONDARY] DEFAULT GO 3. Click the Execute button on the toolbar. 4. If the TransactTestDB node is not selected, click TransactTestDB. 5. Click the Summary tab, and then click Report. When the report is displayed, expand Disk Space Used by Data Files. The report should show the two filegroups and the list of files for each group. 6. Close SQL Server Management Studio. Click No if prompted to save files.
  • 1–22 Module 1: Creating Databases and Database FilesLesson 3: Creating Schemas**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Explain the purpose of schemas. ■ Explain how object name resolution works.Introduction Developers who have worked with the Microsoft .NET Framework or XML will be familiar with the concept of namespaces. A namespace helps group together related objects, making complex object lists more manageable. SQL Server 2005 uses schemas to implement a similar concept for database objects. In this lesson, you will learn how schemas work and how they help you to develop database structures that are easy to manage. You will also learn how to create database schemas of your own.
  • Module 1: Creating Databases and Database Files 1–23What Are Schemas?**************************************** Illegal for non-trainer use ***************************************Introduction Objects in a database (such as tables, views, and stored procedures) are created within a schema. It is essential that you understand what a schema is before planning and implementing a SQL Server 2005 database.Schemas as namespaces A schema is a namespace for database objects. In other words, a schema defines a boundary within which all names are unique. Because schema names themselves must be unique within the database, every object in a database has a unique fully qualified name in the form server.database.schema.object. Within a database, you can shorten this to schema.object. The preceding illustration shows three schemas in the AdventureWorks database in a SQL Server instance named Server1. The schemas are named Person, Sales, and dbo. Each of these schemas contains a table, and the fully qualified name of the table includes the server, database, and schema name. For example, the fully qualified name of the ErrorLog table in the dbo schema is Server1.AdventureWorks.dbo.ErrorLog. In earlier releases of SQL Server, an object’s namespace was determined by the user name of its owner. In SQL Server 2005, schemas are separated from object ownership, providing the following benefits: ■ Greater flexibility when organizing database objects into namespaces, because the grouping of objects into schemas does not depend on object ownership. ■ Simpler permission management, because permission can be granted at the schema scope as well as on the individual objects. ■ Improved manageability, because dropping a user does not necessitate the renaming of all objects that the user owns.
  • 1–24 Module 1: Creating Databases and Database FilesExample schemas The AdventureWorks database uses the following schemas to organize its database objects into namespaces: ■ HumanResources ■ Person ■ Production ■ Purchasing ■ Sales For example, you refer to the Employee table in the HumanResources schema as HumanResources.Employee.The dbo schema Every database contains a schema named dbo. The dbo schema is the default schema for all users who do not have any other explicitly defined default schema.Creating a schema To create a schema, use Object Explorer in SQL Server Management Studio or use the CREATE SCHEMA statement, as shown in the following example. Use AdventureWorks GO CREATE SCHEMA Sales GO
  • Module 1: Creating Databases and Database Files 1–25How Object Name Resolution Works**************************************** Illegal for non-trainer use ***************************************Introduction When a database contains multiple schemas, object name resolution can become confusing. For example, a database might contain two tables named Order in two different schemas, Sales and dbo. The qualified names of the objects within the database are unambiguous: Sales.Order and dbo.Order, respectively. However, the use of the unqualified name Order can produce unexpected results. You can assign users a default schema to control how unqualified object names are resolved.How name resolution SQL Server 2005 uses the following process to resolve an unqualified object name:works 1. If the user has a default schema, SQL Server attempts to find the object in the default schema. 2. If the object is not found in the user’s default schema, or if the user has no default schema, SQL Server attempts to find the object in the dbo schema. For example, a user with the default schema Person executes the following Transact- SQL statement: SELECT * FROM Contact SQL Server 2005 will first attempt to resolve the object name to Person.Contact. If the Person schema does not contain an object named Contact, SQL Server will attempt to resolve the object name to dbo.Contact. If a user with no defined default schema executes the same statement, SQL Server will immediately resolve the object name to dbo.Contact.Assigning a default You can assign a default schema to a user by using the Database User Properties dialogschema box or by specifying the schema name in the DEFAULT_SCHEMA clause of the CREATE USER or ALTER USER statement. For example, the following Transact-SQL code assigns Sales as the default schema for the user Anders: ALTER USER Anders WITH DEFAULT_SCHEMA = Sales
  • 1–26 Module 1: Creating Databases and Database FilesPractice: Creating a Schema**************************************** Illegal for non-trainer use ***************************************Goals The goal of this practice is to enable you to create schemas by using SQL Server Management Studio and by using Transact-SQL. In this practice, you will use both techniques to create a new schema.Preparation Note This practice requires that you have completed the preceding practice. Ensure that virtual machine 2779A-MIA-SQL-01 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.To create a schema by Perform the following steps to create a schema by using SQL Server Managementusing SQL Server Studio:Management Studio 1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, specify the values in the following table, and then click Connect. Property Value Server type Database Engine Server name MIAMI Authentication Windows Authentication 3. If Object Explorer is not visible, click Object Explorer on the View menu.
  • Module 1: Creating Databases and Database Files 1–27 4. In Object Explorer, expand Databases, TestDB, and Security. 5. Right-click Schemas, and then click New Schema. 6. In the Schema - New dialog box, enter Sales for Schema name, and then click OK. 7. In Object Explorer, expand Schemas, and then confirm that the Sales schema exists. 8. Keep SQL Server Management Studio open. You will use it in the next procedure.To create a schema by Perform the following steps to create a schema by using the CREATE SCHEMAusing Transact-SQL Transact-SQL statement: 1. In SQL Server Management Studio, click the New Query button on the toolbar. 2. In the new, blank query window, type the following Transact-SQL code. Use TransactTestDB GO CREATE SCHEMA [Marketing] GO 3. Click the Execute button on the toolbar. 4. In Object Explorer, expand Databases, TransactTestDB, Security, and Schemas, and then confirm that the Marketing schema exists. 5. Close SQL Server Management Studio. Click No if prompted to save files.
  • 1–28 Module 1: Creating Databases and Database FilesLesson 4: Creating Database Snapshots**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe database snapshots, and identify suitable scenarios for a database snapshot. ■ Explain how database snapshot files are populated.Introduction As a database developer in your organization, you might need to create a static view of a SQL Server 2005 database. This kind of static view of the data enables you to work with data as it appeared at a specific point in time, rather than reflecting the current status of the data. Such a point-in-time view might be useful for reporting, development, or testing purposes. This lesson introduces the concept of database snapshots and how they work. You will also learn how to configure database snapshots.
  • Module 1: Creating Databases and Database Files 1–29What Are Database Snapshots?**************************************** Illegal for non-trainer use ***************************************Introduction There are many scenarios in which a simple copy of the database, known as a snapshot, is useful as a “warm to cold” standby database, as a test and development database, or simply as a reporting database. You use the AS SNAPSHOT OF clause of the CREATE DATABASE statement to create a database snapshot.Definition A database snapshot is a read-only, static view of a database from a specified point in time that does not change after the creation of the snapshot. The database from which the snapshot is created is referred to as the source database. Database snapshots can be useful as a quick restore point in case of accidental or malicious damage to the data in the database. However, they cannot be used as a substitute for backups because a database snapshot does not contain all records in the database.Restrictions for creating One limitation of a database snapshot is that the snapshot must be located on the samesnapshots server as the source database. The following restrictions also apply to database snapshots: ■ Database snapshots cannot be created for the model, master, or tempdb databases. ■ Database snapshots cannot be backed up or restored. ■ Database snapshots cannot be attached or detached. ■ Database snapshots cannot be created on FAT32 or raw partitions. ■ All database snapshots created over a database must be dropped before the database itself is dropped. ■ SQL Server Management Studio does not support snapshot creation. Therefore, database snapshots can be created only by using Transact-SQL.
  • 1–30 Module 1: Creating Databases and Database Files For More Information For more information about creating database snapshots by using the CREATE DATABASE statement, see “CREATE DATABASE (Transact-SQL),” in SQL Server Books Online.
  • Module 1: Creating Databases and Database Files 1–31How Database Snapshots Work**************************************** Illegal for non-trainer use ***************************************Introduction Database snapshots maintain their static view of a source database by storing copies of premodification data when updates occur on the source database. This copied information is then returned as part of a normal query.Data modification SQL Server 2005 uses copy-on-write technology to implement database snapshots without incurring the overhead of creating a complete copy of the database. A database snapshot is initially empty and is physically implemented as NTFS sparse files, which are files for which physical disk space is allocated only when required. When a page in the source database is first updated, the original image of that page is copied to the database snapshot. If a page is never modified, it is never copied. SQL Server actually makes copies of entire data pages, even if only one row has been updated. Using pages instead of rows is more efficient. The read and write performance for an entire page versus an entire row is very similar. A page can contain many rows, so even if multiple rows in a data page are updated, SQL Server needs to perform only one copy operation. This efficient copy mechanism facilitates effective database snapshot creation even on a frequently updated database.Data retrieval A user accessing a database snapshot will see the copy of a page in the snapshot only if that page has changed since the snapshot was created. Otherwise, the user is redirected to the corresponding page in the source database. This redirection is transparent to the user.
  • 1–32 Module 1: Creating Databases and Database FilesPractice: Creating Database Snapshots**************************************** Illegal for non-trainer use ***************************************Goals The goal of this practice is to enable you to create database snapshots by using Transact- SQL. In this practice, you will create a database snapshot from the AdventureWorks database.Preparation Ensure that virtual machine 2779A-MIA-SQL-01 is running and that you are logged on as Student. If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.To create a database Perform the following steps to create a database snapshot by using Transact-SQL:snapshot by using 1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and thenTransact-SQL click SQL Server Management Studio. 2. In the Connect to Server dialog box, specify the values in the following table and then click Connect. Property Value Server type Database Engine Server name MIAMI Authentication Windows Authentication 3. In SQL Server Management Studio, click the New Query button on the toolbar. 4. In the new, blank query window, type the following Transact-SQL code. CREATE DATABASE AdventureWorks_Snapshot1200 ON ( NAME = NAdventureWorks_Data, FILENAME =
  • Module 1: Creating Databases and Database Files 1–33 NC:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDataAW_1200.ss) AS SNAPSHOT OF AdventureWorks 5. Click the Execute button on the toolbar. 6. In Object Explorer, expand Databases, Database Snapshots, and then confirm that the AdventureWorks_Snapshot1200 database snapshot exists. You might need to refresh the list of database snapshots before the AdventureWorks_Snapshot1200 snapshot becomes visible. 7. Click the New Query button on the toolbar. 8. In the new, blank query window, type the following Transact-SQL code. SELECT AddressID, AddressLine1, ModifiedDate FROM AdventureWorks.Person.Address WHERE AddressID = 1 SELECT AddressID, AddressLine1, ModifiedDate FROM AdventureWorks_Snapshot1200.Person.Address WHERE AddressID = 1 9. Click the Execute button on the toolbar, and then view the results. Both statements return exactly the same information.10. Click the New Query button on the toolbar.11. In the new, blank query window, type the following Transact-SQL code. UPDATE AdventureWorks.Person.Address SET AddressLine1 = 1000 Napa Ct. WHERE AddressID = 112. Click the Execute button on the toolbar.13. Return to the previous query window that contains the SELECT statements, and then click the Execute button. This time, the results should be different because the snapshot still contains the original value.14. Close SQL Server Management Studio. Click No if prompted to save files.
  • 1–34 Module 1: Creating Databases and Database FilesLab: Creating a Database**************************************** Illegal for non-trainer use ***************************************Scenario The senior database developer at Adventure Works has created a specification for a new database in which details of the information technology (IT) assets used by the company will be stored. You must use the specification to create the appropriate filegroups, create the database with the necessary options, create the required schemas, and create a database snapshot. The senior database developer has provided you with the following requirements for the new database: ■ The new database name is AW_ITAssets. ■ The database should consist of two data files and one log file with the names AW_IT_Assets_Data1, AW_IT_Assets_Data2, and AW_IT_Assets_Log. These files should be created in the C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLData folder. ■ The database should use two filegroups, the primary filegroup and a filegroup named Secondary, which should be the default filegroup. The AW_IT_Data2 file should be placed in the Secondary filegroup. ■ Both data files should have an initial size of 20 megabytes (MB) each and should not grow automatically. The log file should have an initial size of 5 MB and should not grow automatically. ■ The database should automatically close when no users are connected and should automatically shrink when appropriate. ■ The database should have one user-defined schema named TechSupport. ■ A script for creating and populating a table has been generated and must be executed in the database.
  • Module 1: Creating Databases and Database Files 1–35 ■ The user MIAMIKatie should use the TechSupport schema as her default schema. ■ A database snapshot named AW_IT_Snapshot must be created for reporting purposes. The files for the database snapshot must be created in the C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLData folder. ■ Use SQL Server Management Studio to create scripts for each action, and then save these scripts in a SQL Server Scripts project in the D:LabfilesStarter folder. This project can be used to document the database configuration and to re-create the database if necessary. ■ Scripts to create tables and users have been provided in the D:LabfilesStarter folder.Additional information When performing database development tasks, it can be helpful to use SQL Server Management Studio to create a SQL Server Scripts project, and use it to document the Transact-SQL code necessary to re-create the solution if necessary. Use the following procedure to create a SQL Server Scripts project: 1. Open SQL Server Management Studio, connecting to the server you want to manage. 2. On the File menu, point to New, and then click Project. 3. Select the SQL Server Scripts template and enter a suitable name and location for the project. Note that you can create a solution that contains multiple projects, but in many cases a single project per solution is appropriate. To add a query file to a project: 1. Click New Query on the Project menu, or right-click the Queries folder in Solution Explorer and click New Query. If Solution Explorer is not visible, you can display it by clicking Solution Explorer on the View menu. 2. When prompted, connect to the server on which you want to execute the query. This will add a connection object to the project. 3. Change the name of the query file from the default name (SQLQuery1.sql) by right-clicking it in Solution Explorer and clicking Rename. Although you can perform all database development tasks by executing Transact-SQL statements, it is often easier to use the graphical user interface in SQL Server Management Studio. However, you should generate the corresponding Transact-SQL scripts and save them in the project for future reference. Often, you can generate the Transact-SQL script for an action before clicking OK in the Properties dialog box used to perform the action. Many Properties dialog boxes include a Script drop-down list with which you can script the action to a new query window, a file, the Clipboard, or a SQL Server Agent job. A common technique is to add a blank query file to a project, script each action to the Clipboard as it is performed, and then paste the generated script into the query file. You can also generate scripts for many existing objects, such as databases and tables. To generate a script, right-click the object in Object Explorer and script the CREATE action. If Object Explorer is not visible, you can display it by clicking Object Explorer on the View menu.Preparation Ensure that virtual machine 2779A-MIA-SQL-01 is running and that you are logged on as Student.
  • 1–36 Module 1: Creating Databases and Database Files If a virtual machine has not been started, perform the following steps: 1. Close any other running virtual machines. 2. Start the virtual machine. 3. In the Log On to Windows dialog box, complete the logon procedure by using the user name Student and the password Pa$$w0rd.
  • Module 1: Creating Databases and Database Files 1–37Exercise 1: Creating a DatabaseCreating a new databasewith options and Task Supporting informationfilegroups Create a SQL Server 1. Create a new SQL Server Scripts project named Management Studio Scripts AW_IT_Database in the appropriate folder. project. 2. Add a new query to the project, connecting to MIAMI by using Windows authentication when prompted. Change the query file name to CreateAW_IT_Assets.sql. Create the new database 1. Use Object Explorer to create a new database. with appropriate options 2. Enter the appropriate details for the AW_IT_Assets and filegroups. database and script the action to the Clipboard before clicking OK. 3. Paste the contents of the Clipboard into the CreateAW_IT_Assets.sql script file, and then save the file.
  • 1–38 Module 1: Creating Databases and Database FilesExercise 2: Creating SchemasCreating schemas for theAW_IT_Assets database Task Supporting information Create the TechSupport 1. On the Project menu, click New Query to create a schema. new query file. When prompted, connect to MIAMI. 2. In Solution Explorer, rename SQLQuery1.sql to CreateAW_IT_Schemas.sql. 3. Use Object Explorer to create the TechSupport schema, scripting the action to the Clipboard. 4. Paste the contents of the Clipboard into the CreateAW_IT_Schemas.sql script file, and then save the file. Create a new table and login 1. On the Project menu, click Add Existing Item. by using the provided script. 2. Add the D:LabfilesStarterCreate_AW_IT_Table_and_ User.sql file. When prompted, connect to MIAMI. 3. Execute the script to create the table, login, and user. Verify that the user can 1. Click Start, click Run, and run the command select information from the runas /noprofile /user:MIAMIKatie cmd. When Asset table only by prompted for the user password, enter Pa$$w0rd. qualifying the table name 2. In the new command prompt window, type with the schema. sqlcmd -S MIAMI -E. 3. Select all of the data from the Asset table by using the following Transact-SQL code: USE AW_IT_Assets SELECT * FROM Asset GO An error message is displayed. 4. Select all of the data from the Asset table using the TechSupport schema by using the following Transact-SQL code: USE AW_IT_Assets SELECT * FROM TechSupport.Asset GO The table is displayed correctly. 5. Do not close the command prompt window.
  • Module 1: Creating Databases and Database Files 1–39Task Supporting informationChange the default schemas 1. Using Object Explorer in SQL Server Managementfor the users, and retest Studio, expand Databases, AW_IT_Assets,access to the table within Security, Users, right-click MIAMIKatie, andthe default schema. then click Properties. 2. Change the default schema for MIAMIKatie to TechSupport, scripting the action to the Clipboard. 3. Paste the contents of the Clipboard into the CreateAW_IT_Schemas.sql file, appending the existing script. Then save all files in the project. 4. Return to the command prompt window running sqlcmd, and then select all of the data from the Asset table by using the default schema, as shown in the following Transact-SQL code: USE AW_IT_Assets SELECT * FROM Asset GO The table is displayed correctly. 5. Exit sqlcmd and close the command prompt window.
  • 1–40 Module 1: Creating Databases and Database FilesExercise 3: Creating a Database SnapshotCreating a databasesnapshot for the Task Supporting informationAW_IT_Assets database Create a database snapshot, 1. Add a new query file to the project, connecting to and then compare the MIAMI when prompted. snapshot data file sizes 2. Rename the new query file to before and after data CreateAW_IT_Snapshot.sql. modification. 3. Add Transact-SQL code to create a new database snapshot named AW_IT_Assets_Snapshot1 based on the AW_IT_Assets database by using the CREATE DATABASE Transact-SQL statement. You must create two snapshot files to match the two data files in the source database. Place the two snapshot data files in C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLData. 4. View the size of the snapshot files by using Windows Explorer, and notice the current Size on disk value. 5. Modify the data in the source database by inserting a new record into the Asset table, and then verify that the new record exists in the source database but not in the database snapshot. 6. View the new Size on disk value for the snapshot’s second data file by using Windows Explorer. This value has increased because of the data modification.Results checklist Use the following checklist of results to verify whether you have successfully performed this lab: ■ Created a database named AW_IT_Assets. ■ Configured a filegroup named Secondary that contains a secondary data file. ■ Created a TechSupport schema. ■ Assigned TechSupport as the default schema of the MIAMIKatie user account. ■ Created a database snapshot named AW_IT_Assets_Snapshot1.