9767402 - Creating Data Types and Tables

398
-1

Published on

Creating Data Types and Tables

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
398
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

9767402 - Creating Data Types and Tables

  1. 1. Module 2Creating Data Types and TablesContents:Lesson 1: Creating Data Types 2-2Lesson 2: Creating Tables 2-10Lesson 3: Creating Partitioned Tables 2-18Lab: Creating Data Types and Tables 2-27
  2. 2. 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.
  3. 3. Module 2: Creating Data Types and Tables 2–1**************************************** Illegal for non-trainer use ***************************************Module objectives After completing this module, students will be able to: ■ Create data types. ■ Create tables. ■ Create partitioned tables.Introduction Data in a database is stored in tables. Each item of data is defined as a specific data type. This module describes the system-supplied data types in Microsoft® SQL Server™ 2005 and how to define custom Transact-SQL data types. It also describes how to create tables and how to use partitioned tables to organize data into multiple partitions.
  4. 4. 2–2 Module 2: Creating Data Types and TablesLesson 1: Creating Data Types**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe the system-supplied data types. ■ Describe suitable scenarios for creating alias data types.Introduction Before you can create a table, you must define the data types for the table. Data types specify the type of information (characters, numbers, or dates) that a column can hold, as well as how the data is stored. SQL Server 2005 supplies more than 30 specific system data types. SQL Server 2005 also supports alias data types, which are user- defined data types based on system data types.
  5. 5. Module 2: Creating Data Types and Tables 2–3What Are System-Supplied Data Types?**************************************** Illegal for non-trainer use ***************************************Introduction Data types define the data values allowed for each column in a database table. SQL Server provides a number of data types. Certain categories of data types that are commonly used in programming languages have several associated SQL Server data types. You should use the smallest data type that meets your needs. This will conserve disk space and allow the most rows on a data page, which provides the best performance.System-supplied data The following table describes the system-supplied database in SQL Server 2005 andtypes indicates the American National Standards Institute (ANSI) synonyms for standard data types used across ANSI-compliant database systems. When referencing data types in Transact-SQL code, you can use the SQL Server–specific data type name or the ANSI synonym. SQL Server system-supplied Data type category data types ANSI synonym Number of bytes Integer int integer 4 8 2, 1 bigint — smallint, tinyint — Exact numeric decimal[(p[, s])] dec 2–17 numeric[(p[, s])] — Approximate float[(n)] double precision, 8 4 numeric real float[(n)] for n=8–15 float[(n)] for n=1–7 Monetary money, — 8, 4 smallmoney Date and time datetime, — 8, 4 smalldatetime
  6. 6. 2–4 Module 2: Creating Data Types and Tables SQL Server system-supplied Data type category data types ANSI synonym Number of bytes Non-Unicode char[(n)] character[(n)] 0–8,000 0–8,000 character varchar[(n)] char VARYING[(n)] 0–2 gigabytes (GB) varchar(max) character (in row or 16-byte text VARYING[(n)] pointer) 0–2 GB char VARYING(max) (16-byte pointer) character VARYING(max) — Unicode character nchar[(n)] national char[(n)] 0–8,000 (4,000 nvarchar[(n)] national character[(n)] characters) nvarchar(max) national char 0–8,000 (4,000 ntext VARYING([n]) characters) 0–2 national character GB (in row or 16- VARYING([n]) byte pointer) national char 0–2 GB (16-byte VARYING(max) pointer) national character VARYING(max) — Binary binary[(n)] — 0–8,000 0–8,000 varbinary[(n)] binary VARYING[(n)] 0–2 GB (in row or varbinary(max) binary 16-byte pointer) VARYING(max) Image image — 0–2 GB (16-byte pointer) Global identifier uniqueidentifier — 16 XML xml — 0–2 GB Special bit, cursor — 1, 0–8 8 256 timestamp rowversion 0–8,016 sysname — table — sql_variant — For More Information For more information about system-supplied data types, see “Data Types (Database Engine)” in SQL Server Books Online.Exact and approximate How you plan to use a data type should determine whether you choose an exactnumeric data types numeric or an approximate numeric data type. ■ Exact numeric data types let you specify exactly the scale and precision to use. For example, you can specify three digits to the right of the decimal and four to the left. A query always returns exactly what you entered. SQL Server supports two exact numeric data types for ANSI compatibility: decimal and numeric. In general, you use exact numeric data types for financial applications in which you want to portray the data consistently (always two decimal places) and to query on that column (for example, to find all loans with an interest rate of 8.75 percent). ■ Approximate numeric data types store data as accurately as possible.
  7. 7. Module 2: Creating Data Types and Tables 2–5 For example, the fraction one-third is represented in a decimal system as 0.33333 (repeating). The number cannot be stored accurately, so an approximation is stored. SQL Server supports two approximate numeric data types: float and real. If you are rounding numbers or performing quality checks between values, you should avoid using approximate numeric data types. Tip It is best to avoid referencing columns with the float or real data types in WHERE clauses.Fixed and variable data When you know that all values for a given data entity will be exactly the same size, youtypes can use a fixed length data type such as nchar and indicate the number of bytes that should be reserved for each value. When the value length can vary, it might be more efficient to use a variable-length data type such as nvarchar and specify the maximum length of the value. When a variable-length data type is specified, SQL Server reserves 2 bytes for each variable-length value as a marker and uses only the additional space required for each value.Large data values Columns that will be used to store medium to large data values (typically larger than 8,000 bytes) can be stored by using a large object (LOB) type such as text or image, or as a varchar, nvarchar, or varbinary column declared with the max specifier. LOB data types are provided primarily for backward compatibility. You should generally use the max specifier to store large data values.
  8. 8. 2–6 Module 2: Creating Data Types and TablesWhat Are Alias Data Types?**************************************** Illegal for non-trainer use ***************************************Alias data types An alias data type is a custom data type based on a system-supplied data type. An alias data type: ■ Allows you to further refine data types to ensure consistency when working with common data elements in various tables or databases. ■ Is defined in a specific database. ■ Must have a unique name within the database. (But alias data types with different names can have the same definition.)When to create alias data You should create an alias data type when you need to define a commonly used datatypes element with a specific format. For example, a column in which you will store a country code based on the International Organization for Standardization (ISO) alpha-2 standard for international country name abbreviations (such as JP for Japan and CH for Switzerland) could be defined as char(2). However, if the country code will be used regularly throughout the database, you could define a CountryCode data type and use that instead. This makes it easier to understand the object definitions and code in your database. Tip Alias data types that you create in the model database are automatically included in all databases that are subsequently created.Example of creating an You can create alias data types by using Object Explorer in SQL Server Managementalias data type Studio or by using the CREATE TYPE Transact-SQL statement. The following code sample shows how to create an alias data type named CountryCode. CREATE TYPE dbo.CountryCode FROM char(2) NULL
  9. 9. Module 2: Creating Data Types and Tables 2–7Note that when you create an alias data type, you can specify its nullability. An alias datatype created with the NOT NULL option can never be used to store a NULL value. It isimportant to specify the appropriate nullability when you create a data type. To changea data type, you must use the DROP TYPE statement to drop the data type and then re-create a new data type to replace it. And because you cannot drop a data type that is usedby tables in the database, you would also need to ALTER every table that uses the datatype first.For More Information For more information about managing alias data types inTransact-SQL, see “CREATE TYPE (Transact-SQL)” and “DROP TYPE (Transact-SQL)”in SQL Server Books Online.
  10. 10. 2–8 Module 2: Creating Data Types and TablesPractice: Creating Data Types**************************************** Illegal for non-trainer use ***************************************Goals The goal of this practice is to enable you to create alias types based on system-supplied types. You create alias types by using Object Explorer in SQL Server Management Studio or the CREATE TYPE Transact-SQL statement. In this practice, you will use both techniques to create alias types in the AdventureWorks database.Preparation Ensure that virtual machine 2779A-MIA-SQL-02 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 an alias type by Perform the following steps to create an alias data type by using SQL Serverusing SQL Server Management 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, expand Databases, AdventureWorks, Programmability, and Types.
  11. 11. Module 2: Creating Data Types and Tables 2–9 5. Right-click User-defined Data Types, and then click New User-defined Data Type. 6. In the New User-defined Data Type dialog box, enter the details in the following table, and click OK. Property Value Schema dbo Name CountryCode Data type char Length 2 Allow NULLs Selected 7. Verify that the CountryCode data type is displayed in the User-defined Data Types list. 8. Keep SQL Server Management Studio open. You will use it in the next procedure.To create an alias type by Perform the following steps to create a user-defined data type by using Transact-using Transact-SQL 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. USE AdventureWorks CREATE TYPE dbo.EmailAddress FROM nvarchar(50) NULL 3. Click the Execute button on the toolbar. 4. When the command has completed successfully, right-click the User-defined Data Types folder in Object Explorer, and then click Refresh to verify that the dbo.EmailAddress data type has been added to the database. 5. Close SQL Server Management Studio. Click No if prompted to save any files.
  12. 12. 2–10 Module 2: Creating Data Types and TablesLesson 2: Creating Tables**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Describe how SQL Server organizes data in rows. ■ Describe how SQL Server organizes large data values. ■ Describe the considerations for defining columns in a table.Introduction After you define all the data types for your database that you will require, you can create the tables needed to store your data. When you create a table, you need to understand how SQL Server physically organizes the data and how to define columns for optimal storage and performance.
  13. 13. Module 2: Creating Data Types and Tables 2–11How SQL Server Organizes Data in Rows**************************************** Illegal for non-trainer use ***************************************Introduction A data row consists of a row header and a data portion. It is important to understand the elements of the data portion of each row to accurately estimate the size of a table.The row header The 4-byte row header contains information about the columns in the data row, such as a pointer to the location of the end of the fixed-data portion of the row and whether variable-length columns exist in the row.The data portion The data portion of a row can contain the following elements: Fixed-length data. Fixed-length data is entered into the page before variable-length data. An empty fixed-length data row takes up as much space as a populated fixed-length data row. A table with only fixed-length columns always stores the same number of rows on a page. Null block. A null block is a variable-length set of bytes. It consists of 2 bytes storing the number of columns followed by a null bitmap indicating whether each individual column is null. The size of a null bitmap is equal to 1 bit per column, rounded up to the nearest byte. One to eight columns require a 1-byte bitmap. Nine to 16 columns require a 2-byte bitmap. Variable block. A variable block consists of 2 bytes that describe how many variable- length columns are present. An additional 2 bytes per column point to the end of each variable-length column. The variable block is omitted if there are no variable-length columns. Variable-length data. Variable-length data is entered into the page after the variable block. An empty variable-length data row takes up no space. A table with variable-length columns can have a few long rows or many short rows.
  14. 14. 2–12 Module 2: Creating Data Types and TablesHow SQL Server Organizes Large Data Values**************************************** Illegal for non-trainer use ***************************************Introduction A row cannot be larger than a page, so when a column can contain a value larger than 8,000 bytes, SQL Server must store the data separately and store in the actual row only a pointer to the data.Large object (LOB) data Large object (LOB) data types can be stored as one collection of pages or in data rows. LOB data types include: text. The text data type can hold 2,147,483,647 characters. The non-Unicode text data type cannot be used for variables in stored procedures. ntext. The ntext data type can hold a maximum of 2 º – 1 (1,073,741,823) characters or 231 – 1 bytes, which is 2,147,483,647 bytes of variable-length Unicode data. image. The image data type can hold 0 through 2,147,483,647 bytes of binary data. Because text, ntext, and image data types are usually large, SQL Server stores them outside of rows. A 16-byte pointer in the data row points to a root structure that holds the data. The text root structure forms the root node of the B-Tree, which points to the data blocks. If there are more than 32 kilobytes (KB) of data, intermediate nodes in the B-Tree are added between the root node and the blocks of data. This permits quick B- Tree navigation starting in the middle of a string. With small to medium-size text, ntext, and image content, SQL Server provides the option to store values in the data row rather than in a separate B-Tree structure. You can specify this text in row option. You can also set the option limit; the range is 24 through 7,000 bytes. You can enable the text in row option for a table by using the sp_tableoption system stored procedure. Caution The text in row setting will be removed in a future version of SQL Server. You should use the max specifier instead of LOB data types when you need to store large values.
  15. 15. Module 2: Creating Data Types and Tables 2–13The max specifier The max specifier can be used with the varchar, nvarchar, and varbinary data types. This makes it possible to use these data types to store data values larger than 8,000 bytes in the same way that LOB data types are stored, without some of the limitations that apply to LOB data types. As with the LOB data types, you can control how columns defined by using the max specifier are stored. You can set the large value types out of row option with the sp_tableoption system stored procedure. When this option is on, a pointer to the root node of the B-Tree for the data is stored in the row; when the option is off, values that are small enough are stored directly in the row, and a pointer is used only for values that are too large to fit in the row. For More Information For details about the differences between LOB data types and the max specifier, see “Using Large-Value Data Types” in SQL Server Books Online.
  16. 16. 2–14 Module 2: Creating Data Types and TablesConsiderations for Creating Tables**************************************** Illegal for non-trainer use ***************************************Introduction When you create a table, you must specify the table name, column names, and column data types. Column names must be unique to a specific table. However, you can use the same column name in different tables within the same database. You must specify a data type for each column. You can have: ■ More than 2 billion objects per database, including tables. ■ Up to 1,024 columns per table. ■ Up to 8,060 bytes per row. (This approximate maximum length does not apply to image, text, and ntext data types or to columns defined by using the max specifier.)Column collation A collation is a sort order for data that determines the order in which values are listed when the data is sorted sequentially. Different collations sort data into different orders depending on whether the collation is case-sensitive or case-insensitive, the ordering rules for accented letters and special characters, and other considerations. SQL Server supports storing data entities with different collations in the same database. Separate SQL Server collations can be specified at the column level so that each column in a table can be assigned a different collation.Nullability You can specify in the table definition whether to allow null values in each column. If you do not specify NULL or NOT NULL, SQL Server provides the NULL or NOT NULL characteristic, based on the session-level or database-level default. However, these defaults can change, so do not rely on them. Note When the nullability of a column is unspecified, it is determined by the ANSI_NULL_DEFAULT database or session option. When this option is ON, columns allow NULL values by default. When the option is OFF, column nullability is set to NOT NULL by default. In SQL Server 2005, the ANSI_NULL_DEFAULT option is initially OFF.
  17. 17. Module 2: Creating Data Types and Tables 2–15Special column types Special types of columns include the following: Computed columns. A computed column is a virtual column that is not physically stored in the table. SQL Server uses a formula that you create to calculate this column value by using other columns in the same table. Using a computed column name in a query can simplify the query syntax. Identity columns. You can use the Identity property to create columns (referred to as identity columns) that contain system-generated sequential values identifying each row inserted into a table. An identity column is often used for primary key values. Having SQL Server automatically provide key values can reduce costs and improve performance. It simplifies programming, keeps primary key values short, and reduces user-transaction bottlenecks. timestamp columns. Columns defined with the timestamp data type have a default value that consists of an automatically generated time stamp that is guaranteed to be unique within the database. uniqueidentifier columns. Columns defined with the uniqueidentifier data type can be used to store globally unique identifiers (GUIDs), which are guaranteed to be universally unique. You can generate a value for a uniqueidentifier column by using the NEWID Transact-SQL function.Example of creating a You can create tables by using Object Explorer in SQL Server Management Studio or bytable using the CREATE TABLE Transact-SQL statement. The following Transact-SQL code sample can be used to create a table named CustomerOrders in a schema named Sales. The table includes an identity column. CREATE TABLE Sales.CustomerOrders (OrderID int identity NOT NULL, OrderDate datetime NOT NULL, CustomerID int NOT NULL, Notes nvarchar(200) NULL) For More Information For more information about the syntax of the CREATE TABLE statement, see “CREATE TABLE (Transact-SQL)” in SQL Server Books Online. You can also create a table by using Object Explorer tools in SQL Server Management Studio.Modifying and removing You can modify a table definition in Object Explorer or by using the ALTER TABLEtables Transact-SQL statement. For example, the following Transact-SQL statements show how to add a column and change the nullability of a column in the Sales.CustomerOrders table defined previously. ALTER TABLE Sales.CustomerOrders ADD SalesPersonID int NOT NULL GO ALTER TABLE Sales.CustomerOrders ALTER COLUMN Notes nvarchar(200) NOT NULL GO To remove a table from the database, you can delete it in Object Explorer or use the DROP TABLE Transact-SQL statement. For More Information For more information about altering and dropping tables, see “ALTER TABLE (Transact-SQL)” and “DROP TABLE (Transact-SQL)” in SQL Server Books Online.
  18. 18. 2–16 Module 2: Creating Data Types and TablesPractice: Creating Tables**************************************** Illegal for non-trainer use ***************************************Goals The goal of this practice is to enable you to create tables. You create tables by using Object Explorer in SQL Server Management Studio or by using the CREATE TABLE Transact-SQL statement. In this practice, you will use both techniques to create tables in the AdventureWorks database.Preparation Ensure that virtual machine 2779A-MIA-SQL-02 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 table by using Perform the following steps to create a table by using SQL Server ManagementSQL Server Management Studio: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, expand Databases, AdventureWorks, and Tables.
  19. 19. Module 2: Creating Data Types and Tables 2–17 5. Right-click Tables, and then click New Table. 6. In the Table – dbo.Table_1 window, enter the following details. Column Name Data Type Allow Nulls DiscountID int Unselected Amount decimal (18, 0) Unselected DiscountName nvarchar (50) Unselected Description nvarchar (MAX) Selected 7. Click the DiscountID row, and then examine the Column Properties pane below the column list. 8. Expand Identity Specification, and then set the (Is Identity) property to Yes. 9. On the Table Designer menu, click Set Primary Key. Note A primary key specifies a column (or combination of columns) that uniquely identifies each record in the table. 10. Click the DiscountName row, and then examine the Column Properties pane. 11. Set the Length property to 25. 12. On the View menu, click Properties Window, and set the Schema property to Sales. 13. Click anywhere in the table design surface, and then on the File menu, click Save Table_1. 14. In the Choose Name dialog box, type Discount, and then click OK. 15. Close the Table-Sales.Discount window, and then right-click the Tables folder and click Refresh to verify that the new table has been created. 16. Keep SQL Server Management Studio open. You will use it in the next procedure.To create a table by using Perform the following steps to create a table by using Transact-SQL: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. USE AdventureWorks CREATE TABLE Sales.SpecialOffers (SpecialOfferID int IDENTITY PRIMARY KEY NOT NULL, OfferName nvarchar(25) NOT NULL, Description nvarchar(max) NULL) 3. Click the Execute button on the toolbar. 4. When the command has completed successfully, right-click the Tables folder in Object Explorer, and then click Refresh to verify that the Sales.SpecialOffers table has been added to the database. 5. Close SQL Server Management Studio. Click No if prompted to save any files.
  20. 20. 2–18 Module 2: Creating Data Types and TablesLesson 3: Creating Partitioned Tables**************************************** Illegal for non-trainer use ***************************************Lesson objectives After completing this lesson, students will be able to: ■ Define partitioned tables. ■ Define partition functions. ■ Define a partition scheme. ■ Create a partitioned table. ■ Describe the operations that can be performed on partitioned data.Introduction A useful strategy in large databases is to partition a single logical set of data into multiple physical storage locations for manageability or performance reasons. SQL Server 2005 supports partitioned tables and indexes. Partitioned tables and indexes are single objects stored in multiple physical partitions, each partition holding a specific subset of the data. In this lesson, you will learn how to implement partitioned tables. You will also learn about the partition functions and partition schemes on which partitioned tables are based.
  21. 21. Module 2: Creating Data Types and Tables 2–19What Are Partitioned Tables?**************************************** Illegal for non-trainer use ***************************************What is a partitioned A partitioned table is a table in which the data is separated horizontally into multipletable? physical locations based on a range of values for a specific column. The physical locations for partitions are filegroups. For example, you could use a partitioned table to store sales orders and then separate the order records into different filegroups based on the order date so that orders placed in the current financial year are stored in one partition, orders placed in the previous financial year are stored in a second partition, and all orders older than two years are stored in a third partition. This technique makes it possible to control the physical storage of different kinds of orders while still maintaining them in a single table.Manageability benefits The main reason for implementing a partitioned table is to make it easier to manageof partitioned tables different sets of data within the same table. Manageability benefits of partitioned tables include: The ability to implement separate backup strategies. Different sets of data might have different backup requirements. For example, recent orders data might be updated frequently and require regular backups, while older orders might change rarely and require only infrequent backups. Control over storage media. Partitioning a table lets you choose appropriate storage for data, based on its access requirements. For example, you can store historical, unchanging data on an NTFS compressed filegroup while keeping the current data on a high-performance redundant array of independent disks (RAID) 10 filegroup. Index management benefits. In addition to partitioning a table, you can partition its indexes. This allows you to reorganize, optimize, and rebuild indexes by partition, which is faster and less intrusive than managing an entire index. Additionally, partitioning an index can minimize fragmentation. For example, older order data is unlikely to change, so the index pages that relate to historical orders are stable.
  22. 22. 2–20 Module 2: Creating Data Types and TablesPerformance benefits of In addition to the manageability benefits of partitioned tables, you can also realize apartitioned tables number of performance benefits. These performance benefits include: Faster index searches. Partitioning results in smaller index trees for each partition, making partition access fast, especially when you limit rows by specifying the partition key in a WHERE clause. Enhanced JOIN performance. JOIN operations can be faster when joining aligned tables (that is, tables that are partitioned in the same manner). Reduced locking. Lock escalation stops at the partition level, significantly minimizing the risk of blocking and deadlock.
  23. 23. Module 2: Creating Data Types and Tables 2–21What Are Partition Functions?**************************************** Illegal for non-trainer use ***************************************What is a partition A partition function specifies the data type of the key used to partition the data and thefunction? boundary values for each partition. The number of partitions defined by a partition function is always one more than the number of boundary values that the function defines. For example, a partition function that defines a datetime partitioning key with the boundary values ‘01/01/2003’, ‘01/01/2004’, and ‘01/01/2005’ will result in four partitions: one for everything up to the first boundary value (in other words, values before January 1, 2003), one for values between the first and second boundaries (in other words, values between January 1, 2003, and January 1, 2004), one for values between the second and third boundaries (in other words, values between January 1, 2004, and January 1, 2005), and one for everything beyond the final boundary (in other words, values after January 1, 2005).Boundary value Partition functions are configured as LEFT or RIGHT, depending on where you wantplacement data that matches the boundary value to go. In a LEFT partition function, exact matches with the boundary value go to the partition to the left, whereas in RIGHT partition functions, exact matches go to the right.Example of a partition You create a partition function by using the CREATE PARTITION FUNCTION Transact-function SQL statement, as shown in the following code sample. CREATE PARTITION FUNCTION pf_OrderDate (datetime) AS RANGE RIGHT FOR VALUES (01/01/2003, 01/01/2004, 01/01/2005) This code sample creates a partition function named pf_OrderDate with four partitions: one for dates before January 2003, one for dates between January and the end of December 2003, one for dates between January and the end of December 2004, and one for dates after January 2005. For More Information For a full explanation of the CREATE PARTITION FUNCTION syntax, see “CREATE PARTITION FUNCTION (Transact-SQL)” in SQL Server Books Online.
  24. 24. 2–22 Module 2: Creating Data Types and TablesWhat Is a Partition Scheme?**************************************** Illegal for non-trainer use ***************************************What is a partition A partition scheme maps the partitions defined in a partition function to the filegroupsscheme? on which the partitions will be physically stored. You can map all partitions to the same filegroup, or you can map some or all of the partitions to different filegroups, depending on your specific needs.Specifying the next When you create a partition scheme, you can optionally specify the filegroup to be used iffilegroup another partition is added to the partition function. This is known as the next filegroup.Example of a partition You create a partition scheme by using the CREATE PARTITION SCHEME Transact-scheme SQL statement, as shown in the following code sample. CREATE PARTITION SCHEME ps_OrderDate AS PARTITION pf_OrderDate TO (fg1, fg2, fg3, fg4, fg5) This code sample creates a partition scheme named ps_OrderDate for the pf_OrderDate partition function in the previous example. The four partitions defined by the partition function are assigned to the fg1, fg2, fg3, and fg4 filegroups. The TO clause in this example specifies one more filegroup than there are partitions, which is how you specify the “next” partition. In this example, fg5 is specified as the next filegroup to be used. If you want to map all partitions to the same filegroup, you can use the ALL keyword, as shown in the following example. CREATE PARTITION SCHEME ps_OrderDate AS PARTITION pf_OrderDate ALL TO ([PRIMARY]) In this example, all partitions are mapped to the primary filegroup, which is also designated as the next filegroup to be used. For More Information For a full explanation of the CREATE PARTITION SCHEME syntax, see “CREATE PARTITION SCHEME (Transact-SQL)” in SQL Server Books Online.
  25. 25. Module 2: Creating Data Types and Tables 2–23Demonstration: Creating a Partitioned Table**************************************** Illegal for non-trainer use ***************************************Introduction In this demonstration, you will see how to create a partition function, a partition scheme, and a partitioned table.Preparation Ensure that virtual machine 2779A-MIA-SQL-02 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 partition To create a partition function, perform the following steps:function 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. On the File menu, point to Open, click File, and then open the Partitions.sql file in the D:Democode folder. Connect to MIAMI by using Windows authentication when prompted. 4. Select the code under the comment Create partition function, and then click the Execute button. This code creates a partition function named pf_OrderDate with three partitions: one for dates prior to 2004, one for dates between January and the end of December 2004, and one for dates after January 2005.
  26. 26. 2–24 Module 2: Creating Data Types and TablesTo create a partition To create a partition scheme, perform the following steps:scheme 1. Select the code under the comment Add filegroups and create partition scheme. This code: ● Adds filegroups to the AdventureWorks database. ● Adds files to the new filegroups in the AdventureWorks database. ● Creates a partition scheme named ps_OrderDate that maps partitions in the pf_OrderDate partition function to the new filegroups. 2. Click the Execute button. Notice that the partition scheme is created and that fg4 is marked as the next filegroup to be used.To create a partitioned To create a partitioned table, perform the following steps:table 1. Select the code under the comment Create partitioned table. This code creates a table and then uses the ON clause to place the table on the ps_OrderDate partition scheme. 2. Click the Execute button.To view partitioned table To view partitioned table behavior, perform the following steps:behavior 1. Select the code under the comment Insert data, and then click the Execute button. This code copies data from an existing table and then inserts an additional row containing an order placed on January 1, 2005. 2. Select the code under the comment View partition metadata, and then click the Execute button. This code retrieves information about the partitions used by the dbo.PartitionedTransactions table from the sys.Partitions catalog view. 3. Select the code under the comment View data with partition number, and then click the Execute button. This code uses the $Partition function to identify in which partition each row is stored. 4. Select the code under the comment Verify lowest value in each partition, and then click the Execute button. This code retrieves the lowest value stored in each partition. Notice that the order placed on January 1, 2005, is stored in the third partition. This is because the pf_OrderDate partition function is configured to store boundary values in the RIGHT partition. 5. Highlight the code under the comment Reset database, and then click the Execute button. This code removes the objects created in this demonstration.
  27. 27. Module 2: Creating Data Types and Tables 2–25What Operations Can Be Performed on Partitioned Data?**************************************** Illegal for non-trainer use ***************************************Introduction In addition to the features already mentioned, partitions provide some very powerful capabilities. You can perform three main operations on a partitioned table: ■ Switching partitions ■ Merging partitions ■ Splitting partitionsSwitching partitions You can swap a populated table or partition with an empty table or partition by using the SWITCH clause of the ALTER TABLE statement. This technique is commonly used to archive data from a partitioned table or to bulk-insert new data from a staging table. The following code sample shows how to switch a partition. ALTER TABLE dbo.PartitionedTransactions SWITCH PARTITION 1 TO dbo.TransactionArchive For More Information For more information about switching partitions, see “Transferring Data Efficiently by Using Partition Switching” in SQL Server Books Online.Merging partitions You can use the ALTER PARTITION FUNCTION statement to merge a partition. When performing a merge operation, the partition for the boundary value specified in the ALTER PARTITION FUNCTION statement is removed, and the data is merged into the adjacent partition.
  28. 28. 2–26 Module 2: Creating Data Types and Tables The following code sample shows how to merge a partition. ALTER PARTITION FUNCTION pf_OrderDate() MERGE RANGE (01/01/2003) For More Information For more information about merging partitions, see “ALTER PARTITION FUNCTION (Transact-SQL)” in SQL Server Books Online.Splitting partitions Like a merge, a split operation is performed by using the ALTER PARTITION FUNCTION statement. This creates a new partition and reassigns the data accordingly. The new partition is created on the filegroup designated as the next filegroup in each partition scheme based on the partition function. If a partition scheme has no next filegroup defined when the partition is split, an error occurs. The following code sample shows how to split a partition. ALTER PARTITION FUNCTION pf_OrderDate() SPLIT RANGE (01/01/2006) For More Information For more information about splitting partitions, see “ALTER PARTITION FUNCTION (Transact-SQL)” in SQL Server Books Online.
  29. 29. Module 2: Creating Data Types and Tables 2–27Lab: Creating Data Types and Tables**************************************** Illegal for non-trainer use ***************************************Scenario The sales manager at Adventure Works has requested that the company’s database be modified to include data about goods that have been returned and sales that have been refunded. The senior database developer has designed some new data types and tables for the returns and refunds data and has assigned you the task of creating them in the database. The design specification for the database modification includes the following requirements: ■ You must use SQL Server Management Studio to create a SQL Server Scripts project for the solution in the D:LabfilesStarter folder. ■ You must create a new data type named ShortDescription in the dbo schema. This data type should be based on the nvarchar system-supplied data type and should have a maximum length of 100 characters. ■ You must create a new data type named CashValue in the dbo schema. This data type should be based on the decimal system-supplied data type and should have a precision of 8 and a scale of 2. ■ You must create a table named ReturnedGoods in the Sales schema. The ReturnedGoods table should contain the following columns: ● ReturnID. An int identity column that cannot contain NULL values ● ProductID. An int column that cannot contain NULL values ● CustomerID. An int column that cannot contain NULL values ● ReturnDate. A datetime column that cannot contain NULL values ● ReturnReason. A ShortDescription column that can contain NULL values ■ You must create a table named Refunds in the Sales schema. The Refunds table should contain the following columns: ● RefundID. An int identity column that cannot contain NULL values ● ReturnID. An int column that cannot contain NULL values
  30. 30. 2–28 Module 2: Creating Data Types and Tables ● Amount. A CashValue column that cannot contain NULL values ■ In the Sales schema You you must create a partitioned table named ReturnsArchive that contains archived returns data in the same structure as the ReturnedGoods table but that stores data in three partitions: one for returns prior to 2005, one for returns in 2005, and one for returns in 2006. ■ A script to populate the ReturnsArchive table is 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, and then script each action to the Clipboard as it is performed and 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-02 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.
  31. 31. Module 2: Creating Data Types and Tables 2–29Exercise 1: Creating Data TypesCreating theShortDescription and Task Supporting informationCashValue data types Create a SQL Server Scripts 1. Start SQL Server Management Studio. project. 2. Create a new SQL Server Scripts project named AW_Tables. Create the ShortDescription 1. Add a new query file to the project, connecting to and CashValue data types. MIAMI when prompted. Rename the query file to CreateDataTypes.sql. 2. In the query window, type the appropriate Transact-SQL statement to create the ShortDescription data type in the AdventureWorks database. 3. Add a second Transact-SQL statement to create the CashValue data type in the AdventureWorks database. 4. Execute the query, and then save the query file. 5. Use Object Explorer to verify that the data types have been created. 6. Keep SQL Server Management Studio open; you will use it in the next exercise.
  32. 32. 2–30 Module 2: Creating Data Types and TablesExercise 2: Creating TablesCreating theReturnedGoods and Task Supporting informationRefunds tables Create a new query file. 1. Add a new query file to the project, connecting to MIAMI when prompted. 2. Rename the query file to CreateTables.sql. Create the ReturnedGoods 1. In the query window, type the appropriate and Refunds tables. Transact-SQL statement to create the ReturnedGoods table in the AdventureWorks database. 2. Add a second Transact-SQL statement to create the Refunds table. 3. Execute the query, and then save the query file. 4. Use Object Explorer to verify that the tables have been created. 5. Keep SQL Server Management Studio open; you will use it in the next exercise.
  33. 33. Module 2: Creating Data Types and Tables 2–31Exercise 3: Creating Partitioned TablesCreating theReturnsArchive Task Supporting informationpartitioned table Create a partition function. 1. Add a new query file to the project, connecting to MIAMI when prompted. 2. Rename the query file to CreatePartitionedTable.sql. 3. In the query window, type the appropriate Transact-SQL statement to create a partition function named pf_ReturnDate that defines two partition boundaries: 01/01/2005 and 01/01/ 2006. Data that matches the boundary value should be stored in the partition to the right. 4. Execute the query to create the partition function. Create a partition scheme. 1. Under the existing code in the CreatePartitionedTable.sql script file, add code to create a partition scheme named ps_ReturnDate that maps all partitions defined in the pf_ReturnDate partition function to the primary filegroup. 2. Select the code that creates the ps_ReturnDate partition scheme, and then execute it. Create a partitioned table. 1. Under the existing code in the CreatePartitionedTable.sql script file, add code to create the ReturnsArchive table. This table should be partitioned on the ps_ReturnDate partition scheme using the ReturnDate column as the partitioning key. 2. Select the code that creates the ReturnsArchive table, and then execute it. Insert data into the 1. On the Project menu, click Add Existing Item, partitioned table. and then add the InsertReturnsArchive.sql query file in D:LabfilesStarter to the project. When prompted, connect to MIAMI. 2. Click the Execute button to insert data into the partitioned table. View partition usage. 1. Under the existing code in the InsertReturnsArchive.sql query file, add a Transact-SQL statement to retrieve the ReturnID and ReturnDate columns, and use the $Partition.pf_ReturnDate function to retrieve the partition number for each record from the Sales.ReturnsArchive table. 2. Select the code that queries the ReturnsArchive table, and then execute it. 3. View the results and verify that the data is spread across the partitions defined in the pf_ReturnDate partition function.
  34. 34. 2–32 Module 2: Creating Data Types and TablesResults checklist Use the following checklist of results to verify whether you have successfully performed this lab: ■ Created data types named ShortDescription and CashValue in the AdventureWorks database ■ Created tables named ReturnedGoods and Refunds in the Sales schema of the AdventureWorks database ■ Created a partition function named pf_ReturnDate in the AdventureWorks database ■ Created a partition scheme named ps_ReturnDate in the AdventureWorks database ■ Created a partitioned table named ReturnsArchive in the Sales schema of the AdventureWorks database

×