text:
This action might not be possible to undo. Are you sure you want to continue?
Version: SQLSERVER2005/Handout/0408/1.0 Date: 30-04-08
Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com
Handout - SQL Server 2005
Introduction ...................................................................................................................................7 About this Module .........................................................................................................................7 Target Audience ...........................................................................................................................7 Module Objectives ........................................................................................................................7 Pre-requisite .................................................................................................................................7 Session 02: SQL Server 2005 Overview .......................................................................................8 Learning Objectives ......................................................................................................................8 SQL Server Overview ...................................................................................................................8 SQL Server 2005 Architecture and Components .........................................................................8 SQL Server 2005 Tools ..............................................................................................................10 SQL Server Security ...................................................................................................................12 Database ....................................................................................................................................12 Transact SQL..............................................................................................................................13 Data types...................................................................................................................................14 Summary ....................................................................................................................................16 Test Your Understanding............................................................................................................16 Exercises ....................................................................................................................................17 Session 07: Implementing Data Integrity ...................................................................................18 Learning Objectives ....................................................................................................................18 Data Integrity Overview ..............................................................................................................18 Enforcing Data Integrity ..............................................................................................................19 Computed Columns and Persisted Columns .............................................................................23 Summary ....................................................................................................................................24 Test your Understanding ............................................................................................................24 Session 09 and 12: Subqueries, Joins and T-SQL Enhancements .........................................25 Learning Objectives ....................................................................................................................25 TSQL Fundamentals ..................................................................................................................25 The SELECT Statement .............................................................................................................26 SELECT Clause..........................................................................................................................27 FROM Clause .............................................................................................................................28 WHERE clause ...........................................................................................................................38 GROUP BY clause .....................................................................................................................42
Page 2 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
HAVING clause...........................................................................................................................43 ORDER BY clause......................................................................................................................44 Subqueries..................................................................................................................................45 INSERT Statement .....................................................................................................................46 UPDATE statement ....................................................................................................................50 DELETE statement .....................................................................................................................55 TRUNCATE TABLE statement ...................................................................................................59 CREATE TABLE statement ........................................................................................................60 Functions ....................................................................................................................................63 Deterministic and Nondeterministic Functions ...........................................................................63 Aggregate Functions ..................................................................................................................64 Date and Time Functions ...........................................................................................................65 String Functions ..........................................................................................................................67 Ranking Functions ......................................................................................................................68 Common Table Expressions ......................................................................................................68 Summary ....................................................................................................................................69 Session 15: Database and Data files ..........................................................................................70 Learning Objectives ....................................................................................................................70 Overview .....................................................................................................................................70 Database Files ............................................................................................................................70 Database Filegroups ..................................................................................................................72 CREATE DATABASE (T-SQL Statement) .................................................................................74 Creating Database (Using using SQL Server Management Studio) ..........................................84 Summary ....................................................................................................................................84 Session 17: Views and Partition Tables .....................................................................................85 Learning Objectives ....................................................................................................................85 Database Console Commands...................................................................................................85 Views ..........................................................................................................................................85 Types of Views ...........................................................................................................................86 Advantages of Views ..................................................................................................................87 CREATE VIEW ...........................................................................................................................87 Derived Tables............................................................................................................................92 Partitioned Tables .......................................................................................................................92 Summary ....................................................................................................................................93 Session 19: Control Flow Constructs ........................................................................................94 Learning Objectives ....................................................................................................................94
Page 3 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
Overview .....................................................................................................................................94 END (BEGIN...END) ...................................................................................................................94 IF...ELSE ....................................................................................................................................95 CASE ..........................................................................................................................................96 GOTO .........................................................................................................................................98 BREAK........................................................................................................................................99 CONTINUE .................................................................................................................................99 WHILE ........................................................................................................................................99 WAITFOR .................................................................................................................................100 TRY...CATCH ...........................................................................................................................101 DECLARE @local_variable ......................................................................................................104 Summary ..................................................................................................................................109 Session 21: Cursors ...................................................................................................................110 Learning Objectives ..................................................................................................................110 Cursors .....................................................................................................................................110 Server Cursor Advantage .........................................................................................................111 Cursor Process .........................................................................................................................111 TSQL Cursors ...........................................................................................................................112 SQL Cursor Variables ...............................................................................................................112 DECLARE CURSOR ................................................................................................................113 Opening cursor .........................................................................................................................118 Fetching cursor .........................................................................................................................119 Closing Cursor ..........................................................................................................................122 Deallocating Cursors ................................................................................................................123 Cursor: Disadvantages .............................................................................................................123 Summary ..................................................................................................................................124 Session 23: Stored Procedures ...............................................................................................125 Learning Objectives ..................................................................................................................125 Stored Procedure .....................................................................................................................125 Types of Stored Procedures .....................................................................................................126 Creating Stored Procedures .....................................................................................................127 Creating Stored Procedures WITH RECOMPILE option .........................................................131 Creating Stored Procedures WITH ENCRYPTION option .......................................................131 System Stored Procedures.......................................................................................................132 Error Handling...........................................................................................................................132 CLR Integration.........................................................................................................................134 CLR Procedures .......................................................................................................................134
Page 4 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
................................................................................................................................................................................................................144 Inline Table-Valued Functions .............................................................................................................................................. Cognizant Technology Solutions................................................................Usage ...........................................................................................................137 Summary ....................149 AFTER Triggers ...........................................................163 Clustered Indexes .....................................................164 Clustered Indexes ..............183 Learning Objectives ......................................................165 Non Clustered Indexes .......................................................................................................................................................163 Learning Objectives ..148 Triggers .................................135 ALTER PROCEDURE .............SQL Server 2005 EXECUTE AS clause ......................................139 Scalar functions ..........................................................138 Session 26: Functions ....................................................................................................................................................................................................................................................................................................................................183 Explicit Transactions .....................................................................182 Summary ................................................................................145 Multi-Valued Table Functions ............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................139 User-defined Functions .......................................................................................................183 Transactions ..........................................................162 Session 31: Indexes ........................................................................................................................................................................161 Summary ..................................139 Learning Objectives ...........................................184 Page 5 ©Copyright 2007......................................................................................................................................................145 Summary .............................................182 Session 33: Transactions and Locking .................................147 Session 29: Triggers .............153 INSTEAD OF Triggers .............................................................161 OUTPUT Clause ....................................................................................................................166 CREATE INDEX ............................................................................................154 DDL Triggers .......167 Database Engine Tuning Advisor ..................................................................................................................................................... All Rights Reserved C3: Protected .......................................Handout ...............................................................................................................................................................................................................................................................................................................................................................148 Learning Objectives ......................................................................................................................................................................................................148 Types of DML Triggers .....................................149 CREATE TRIGGER ............................................163 Index ..................................................................................................................................................................................................................................................................139 CREATE FUNCTION ....................................153 Creating CLR Trigger ..................
....................................................................186 Locks ..................................186 Isolation Levels ...........................................................................................................Handout ...............................224 Books ............192 Summary .............................................................................................................................212 Selection Logic: FLWOR Expressions ...............................................................................187 Query Processing ....................................205 OPENXML Enhancements in SQL Server 2005 ........................................................224 Websites ........................................................................................................195 FOR XML Commands ................................................................195 The XML Data Type ..........................................................................................................................................................................................................................................................................................................................................................SQL Server 2005 Nesting Transactions .................................213 XQuery......................................................................................194 Session 36: XML Support in SQL Server ........................................................................................ All Rights Reserved C3: Protected ...................................................................................................................................198 FOR XML Enhancements in SQL Server 2005 ...................191 Distributed Queries ........................................................................................................................195 Learning Objectives ..................................................................................................................................................................................................................................................225 Page 6 ©Copyright 2007................................................224 STUDENT NOTES: .............................................................................185 Distributed Transactions .........................................................................................................................222 References ....................................................................................................................................................................................................................................................................215 Summary ..........................................................................195 XML in SQL Server ........ Cognizant Technology Solutions............
you will be able to understand: Create data types and tables Implement data integrity Perform programming SQL Server Create databases Manage databases Implement Cursors. Indexes. Cognizant Technology Solutions. Module Objectives After completing this module.SQL Server 2005 Introduction About this Module This module provides the developer with the SQL Server 2005 fundamentals and skills to code using TSQL.Handout . Functions. and Triggers Managing Transactions and Locks XML Support in SQL Server Pre-requisite Basic knowledge of general RDBMS concepts Page 7 ©Copyright 2007. Target Audience This module is designed for entry level developer using SQL Server 2005. All Rights Reserved C3: Protected . Stored Procedures.
Cognizant Technology Solutions. All Rights Reserved C3: Protected . SQL Server 2005 is made up of the following components: Relational database engine Analysis Services SQL Server Integration Services (SSIS) Notification Services Reporting Services Page 8 ©Copyright 2007. The Database Engine also provides rich support for sustaining high availability. SQL Server is a RDBMS (Relational Database Management System) that: Manages data storage for transactions and analysis Stores data in a wide range of data types. in the event of a system failure SQL Server 2005 Architecture and Components SQL Server 2005 is more than just a database management system. and e-commerce applications. The Database Engine provides controlled access and rapid transaction processing to meet the requirements of the most demanding data consuming applications within your enterprise.SQL Server 2005 Session 02: SQL Server 2005 Overview Learning Objectives After completing this session. XML (eXtensible Markup Language) 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. and securing data. processing. numeric. data warehousing. including text. The Database Engine is the core service for storing. XML and large objects Responds to request form client applications Applies T-SQL (Transact-SQL). you will be able to: Describe the architecture of SQL Server 2005 Implement various SQL Server 2005 tools Apply SQL Server 2005 security mechanisms SQL Server Overview Microsoft SQL Server 2005 is a database and data analysis platform for large-scale online transaction processing (OLTP).Handout . It includes multiple components and services that make it a comprehensive platform for enterprise applications.
secure environment for storing.NET.NET Common Language Run time (CLR): Hosted in SQL Server. making it possible to implement database solutions applying managed code written in a .SQL Server 2005 Service Broker Replication Full-text search Relational database engine: The SQL Server relational database engine is at the heart of SQL Server 2005 and provides a high-performance.NET language such as Microsoft Visual C#® . retrieving. scalable. All Rights Reserved C3: Protected .NET or Microsoft Visual Basic® . Native HTTP Support: Enables client applications to connect to HTTP endpoints within SQL Server without requiring Internet Information Services (IIS). Replication: A set of technologies for copying and distributing data and database objects from one database or server to another and then synchronizing between databases to ensure consistency Page 9 ©Copyright 2007. Cognizant Technology Solutions.Handout . and modifying data in relational or eXtensible Markup Language (XML) format Analysis Services: Provides the basis of a powerful business intelligence solution that supports Online Analytical Processing (OLAP) applications and data mining SQL Server Integration Services (SSIS): An engine for building data import and export solutions and performing transformations on data as it is transferred Notification Services: A framework for solutions in which subscribers are sent notifications when specific events occur and notifications can be generated efficiently and sent to multiple device types Reporting Services: Applied to extract data from SQL Server and generate reports Service Broker: A queuing mechanism for reliable. transactional message based communication between software services .
and administering all components of SQL Server. All Rights Reserved C3: Protected . The Code Editor replaces the Query Analyzer included in previous releases of SQL Server. replication topologies. Cognizant Technology Solutions. and notification servers. data transformation packages. configuring. scripting or running objects belonging to instances of SQL Server and also to browse different servers and for viewing logs. Analysis Services cubes. SQL Server Management Studio is a suite of administrative tools for managing the components belonging to SQL Server. Object Explorer for locating. SQL Server 2005 tools are as follows: SQL Server Management Studio SQL Server Business Intelligence Development Studio SQL Server Profiler SQL Server Configuration Manager SQL Server Surface Area Configuration Database Engine Tuning Advisor Command Prompt Utilities SQL Server Management Studio SQL Server Management Studio is an integrated environment for accessing. Microsoft SQL Server 2005 provides the SQL Server Management Studio for administering and designing SQL Server databases within the context of a script project. and administer relational databases. guides and wizards to assist users in developing. and SQL Mobile Query Editor. Management studio replaces Enterprise Manager and Query Analyzer of previous SQL Server releases. Page 10 ©Copyright 2007. editors. This integrated environment allows users to perform a variety of tasks. namely the SQL Query Editor. Tools that are now incorporated into the SQL Server Management Studio include: Code Editor is a rich script editor for writing and editing scripts. modifying. deploying and maintaining databases. Template explorer is applied to locate an existing template to be implemented in the code editor or to add a custom template. deploy. develop. such as backing up data. reporting servers. SQL Server Management Studio includes designers.Handout . SQL Server 2005 Tools Microsoft SQL Server 2005 provides the tools to design. managing. XML Query Editor. MDX (Multidimensional Expressions )Query Editor.SQL Server 2005 Full-text search: Enables fast and flexible indexing for queries based on keyword of text data stored in a SQL Server database. and automating common functions within a single interface. editing queries. SQL Server Management Studio provides four versions of the Code Editor.
and script files at the command prompt. SQL Server Configuration Manager SQL Server Configuration Manager is a tool: To manage the services associated with SQL Server To configure the network protocols applied by SQL Server To manage the network connectivity configuration from SQL Server client computers Command Prompt Utilities tools Command Prompt Utilities are tools for moving bulk data. system procedures. Some of Command Prompt Utilities tools as follows: bcp Utility: Applied to copy data between an instance of Microsoft SQL Server and a data file in a user-specified format. and Reporting Services projects. running scripts. The events are saved in a trace file that can later be analyzed or applied to replay a specific series of steps when trying to diagnose a problem. Page 11 ©Copyright 2007. managing Notification Services.Handout . SQL Server Profiler SQL Server Profiler is a tool that captures SQL Server 2005 events from a server. osql Utility: Allows you to enter Transact-SQL statements. Integration Services. and so on. Business Intelligence Development Studio is the primary environment that you will apply to develop business solutions that include Analysis Services.SQL Server 2005 Business Intelligence Development Studio Business Intelligence Development Studio is Microsoft Visual Studio 2005 with additional project types that are specific to SQL Server 2005 business intelligence. Cognizant Technology Solutions. and script files at the command prompt. sqlcmd Utility: Allows you to enter Transact-SQL statements. dta Utility: Applied to analyze a workload and recommend physical design structures to optimize server performance for that workload. All Rights Reserved C3: Protected . system procedures.
A database can span multiple files across multiple disks. SQL Server Authentication SQL Server Authentication is used when SQL Server authenticates the client by comparing the client-supplied user name and password to the list of valid user names and passwords maintained within SQL Server. Microsoft Windows is completely responsible for authenticating the client. Multiple instances can run on the same machine and each instance manages multiple databases to store data. All Rights Reserved C3: Protected . System Databases System database always stores information about SQL Server as a whole. SQL Server system databases are as follows: Master Model MSDB Tempdb Resource Page 12 ©Copyright 2007. In this case. Cognizant Technology Solutions. the client is identified by its Windows user account.Handout .SQL Server 2005 SQL Server Security SQL Server supports two forms of authentication: Windows Authentication SQL Server Authentication Windows Authentication Windows Authentication is used to connect to SQL Server. SQL Server applies system database to operate and manage the system. Database SQL Server service running on a machine is called an "Instance".
and other database options. Therefore.SQL Server 2005 Master: Records all the system-level information for an instance of SQL Server. master records the initialization information for SQL Server. master is the database that records the existence of all other databases and the location of those database files. MSDB: Applied by SQL Server Agent for scheduling alerts and jobs Tempdb: Workspace for holding temporary objects or intermediate result sets. linked servers. Cognizant Technology Solutions. are applied to any databases created afterward. Modifications made to the model database. company varchar(40). phone char(12) ) GO DCL statements: applied to control access to data in a database Page 13 ©Copyright 2007.92 specification Specific to SQL Server databases only The Transact SQL statements classified as: Data Definition Language Statements (DDL) Data Control Language Statements (DCL) Data Manipulation Language Statements (DML) DDL statements: applied to build and modify the structure of your tables and other objects in the database Define the database objects with the following statements: o CREATE object_name o ALTER object_name o DROP object_name User Must have the appropriate permissions to execute DDL Statements CREATE TABLE MyCustomer ( cust_id int. All Rights Reserved C3: Protected . and system configuration settings. SQL Server cannot start if the master database is unavailable. collation. Resource: A read-only database that contains copies of all system objects that ship with Microsoft SQL Server 2005 Transact SQL The features of Transact SQL are: Powerful and unique superset of the SQL standard Follows ANSI SQL. Model: Applied as the template for all databases created on the instance of SQL Server. endpoints. Additionally. Also.Handout . This includes instance-wide metadata such as logon accounts. such as database size. recovery model. contact varchar(30).
local variable. each column. System Data Types Data types in SQL Server 2005 are organized into the following categories: Exact numerics Approximate numerics Date and time Character strings Unicode character strings Binary strings Other data types Page 14 ©Copyright 2007. All Rights Reserved C3: Protected . and parameter has a related data type. Cognizant Technology Solutions. SQL Server supplies a set of system data types that define all the types of data that can be used with SQL Server. unitprice FROM products GO Data types In SQL Server 2005. character data. data and time data. expression. monetary data.SQL Server 2005 Set or change permissions with following statements: o o o GRANT DENY REVOKE User Must have the appropriate permissions to execute DCL Statements GRANT SELECT ON Mycustomer TO public GO DML statements: Applied to change data or retrieve information Manipulate the data using following statements: o o o o SELECT INSERT UPDATE DELETE User Must have the appropriate permissions to execute DML Statements SELECT categoryid. A data type is an attribute that specifies the type of data that the object can hold: integer data. You can also define your own data types in Transact-SQL. binary strings. productname. productid. and so on.Handout .
nvarchar(max).000 bytes Page 15 ©Copyright 2007. some data types are designated as belonging to the following groups: Large value data types: varchar(max). based on their storage characteristics.SQL Server 2005 Exact Numerics bigint int smallint tinyint bit Approximate Numerics float Date and Time datetime Character Strings char varchar Unicode Character Strings nchar nvarchar Binary Strings binary varbinary Other Data Types cursor sql_variant table timestamp uniqueidentifier xml image ntext text smalldatetime real decimal numeric money smallmoney In SQL Server 2005. All Rights Reserved C3: Protected .Handout . and varbinary(max) varchar (max): o Character data types of variable length o Applied when the sizes of the column data entries vary considerably and the size might exceed 8. Cognizant Technology Solutions.
EmailAddress FROM nvarchar(50) NULL GO Summary SQL Server is a RDBMS product from Microsoft. and xml xml: o Used to store XML data. varchar(max). osql Test Your Understanding 1. SQL Server uses Command Line Utility tools such as bcp.000 bytes Large object data types: text. system procedures. SQL Server supports Windows and SQL authentication mechanisms. and script files a) sqlcmd b) bcp c) dta d) Management Studio Page 16 ©Copyright 2007. ntext. varbinary(max). The Enterprise Manager and Query Analyzer are the most important SQL Server tools replaced with Management Studio in SQL Server 2005. All Rights Reserved C3: Protected . Cognizant Technology Solutions. image. Command Prompt Utilities Allows you to execute Transact-SQL statements. Multiple SQL Server Instances can be deployed on the same machine. User Defined Data Types User defined or alias data type is a custom data type based on a data type supplied by system applied for common data elements with a specific format Created by applying the CREATE TYPE statement: Use AdventureWorks CREATE TYPE dbo.000 bytes varbinary (max): o Binary data types of variable length o Applied when the column data entries exceed 8.Handout .SQL Server 2005 nvarchar (max): o o Unicode character data types of variable length Applied when the sizes of the column data entries vary considerably and the size might exceed 8. nvarchar(max). sqlcmd. dta.
2. Login to SQL Server using sqlcmd utility command and try to execute SQL Queries on Sample AdventureWorks database. Login to SQL Server Management Studio either using SQL Authentication or Windows Authentication and try to execute SQL Queries on Sample Adventureworks database. All Rights Reserved C3: Protected . Which tool replaces Enterprise Manager and Query Analyzer of previous SQL Server releases? a) SQL Server Profiler b) SQL Server Configuration Manager c) SQL Server Surface Area Configuration d) SQL Server Management Studio Exercises 1. Page 17 ©Copyright 2007.SQL Server 2005 2. Cognizant Technology Solutions.Handout .
The various types of data integrity as follows: Entity integrity Domain integrity Referential integrity User-defined integrity Entity Integrity: Entity integrity defines a row as a unique entity for a particular table. Deleting records from a primary table if there are matching related records. All Rights Reserved C3: Protected . restrict the format by using CHECK constraints and rules. PRIMARY KEY constraints. Data integrity refers to the consistency and accuracy of data that is stored in a database. Entity integrity enforces the integrity of the identifier columns or the primary key of a table. In SQL Server 2005. Domain Integrity: Domain integrity is the validity of entries for a specific column. through FOREIGN KEY and CHECK constraints. CHECK constraints. Cognizant Technology Solutions. Changing values in a primary table that causes orphaned records in a related table. or restrict the range of possible values by using FOREIGN KEY constraints. You can enforce domain integrity to restrict the type by using data types. Enforcing data integrity guarantees the quality of the data in the database.Handout . In this chapter you will learn about the different types of data integrity in a relational database and the options provide by SQL Server 2005 to enforce data integrity. and rules. Referential Integrity: Referential integrity preserves the defined relationships between tables when records are entered or deleted. Page 18 ©Copyright 2007. you will be able to: Explain the Data Integrity Overview Implement Constraints Compute columns and persisted columns Data Integrity Overview An Important step in database planning is deciding the best way to enforce the integrity of the data. all references to it change consistently throughout the database. DEFAULT definitions. referential integrity is based on relationships between foreign keys and primary keys or between foreign keys and unique keys. SQL Server prevents users from doing the following: Adding or changing records to a related table if there is no associated record in the primary table. This kind of consistency requires that there are no references to nonexistent values and that if a key value changes. NOT NULL definitions.SQL Server 2005 Session 07: Implementing Data Integrity Learning Objectives After completing this session. UNIQUE constraints. through indexes. Referential integrity makes sure that key values are consistent across tables. or IDENTITY properties. When you enforce referential integrity.
Column that participates in the PRIMARY KEY constraint cannot accept null values. Syntax: CONSTRAINT {constraint_name} { PRIMARY KEY | UNIQUE } { ( column_name [ ASC | DESC ] [ . This includes all column-level and table-level constraints in CREATE TABLE. All Rights Reserved C3: Protected .SQL Server 2005 User-Defined Integrity: User-defined integrity lets you define specific business rules that do not fall into one of the other integrity categories. Consider the following facts before you implement a PRIMARY KEY constraint: A table can have only one PRIMARY KEY constraint.. Enforcing Data Integrity Planning and creating tables requires identifying valid values for the columns and deciding how to enforce the integrity of the data in the columns.Handout . Cognizant Technology Solutions.. stored procedures. Because PRIMARY KEY constraints guarantee unique data. cust_name varchar(30) NOT NULL. and triggers. All the integrity categories support user-defined integrity. The Primary key uniquely identifies a row in a table and enforces entity integrity of the table. One of the columns in the table is identity column. A PRIMARY KEY constraint creates a unique index for the primary key columns.n ] ) } Example: CREATE TABLE customer ( cust_id int NOT NULL.. Consider using a PRIMARY KEY constraint when: One or more columns in a table should uniquely identify each row (entity) in the table. CONSTRAINT PK_Customer_CustID PRIMARY KEY (cust_id) ) Page 19 ©Copyright 2007. they are frequently defined on an identity column. You can create a primary key by defining a PRIMARY KEY constraint when you create or modify a table. SQL Server 2005 provides the following mechanisms to enforce the integrity of the data in a column: PRIMARY KEY Constraints FOREIGN KEY Constraints UNIQUE Constraints CHECK Constraints DEFAULT Definitions Allowing Null Values PRIMARY KEY Constraints A PRIMARY KEY constraint defines one or more columns in a table that constitute a primary key.
Cognizant Technology Solutions. The rows in a table should not be deleted while rows in another table depend on them. For example. Consider using a FOREIGN KEY constraint when: The data in one or more columns can hold only values contained in certain columns in the same or another table.SQL Server 2005 FOREIGN KEY Constraints A FOREIGN KEY (FK) is a column or combination of columns that is used to establish and enforce a link between the data in two tables. they cannot be changed or deleted. A FOREIGN KEY constraint enforces referential integrity.Product table. table. The number of columns and data types that are specified in the FOREIGN KEY statement must match the number of columns and data types in the REFERENCES clause. referential integrity is based on the relationship between the foreign key (ProductID) in the Sales. while references exist to the primary key values.Handout .Product tables in the AdventureWorks database. The values in the foreign key column must appear in the primary key column. This relationship makes sure that a sales order can never reference a product that does not exist in the Production. with the Sales.SalesOrderDetail table and the primary key (ProductID) in the Production. All Rights Reserved C3: Protected .SalesOrderDetail and Production. or another. FOREIGN KEY constraints do not create indexes automatically. Example: CONSTRAINT (FK_SaleOrderDetails_Product_ProductID) FOREIGN KEY (ProductID) REFERENCES Production. Consider the following facts before you implement a FOREIGN KEY constraint: A FOREIGN KEY constraint provides single-column or multicolumn referential integrity.Product table. The FOREIGN KEY constraint defines a reference to a column with a PRIMARY KEY or UNIQUE constraint in the same. Unlike PRIMARY KEY or UNIQUE constraints.Product (ProductID) Page 20 ©Copyright 2007.
Consider the following facts before you implement a UNIQUE constraint: Only one null value can appear in a column with a UNIQUE constraint. Consider using a UNIQUE constraint when: The table contains columns that are not part of the primary key but that. A CHECK constraint cannot be placed on columns with the rowversion. such as an employee's tax number. but you want to guarantee that other identifiers. A single column can have multiple CHECK constraints. Check constraint can be applied at column and table level. must contain unique values. such as an employee number. Column-level CHECK constraints restrict the values that can be stored in that column. A UNIQUE constraint is enforced through the creation of unique index on the specified column or columns. This index cannot allow the table to exceed the 249 limit on nonclustered indexes. text. Consider the following facts before you implement a CHECK constraint: A CHECK constraint verifies data every time you execute an INSERT and UPDATE statement. Page 21 ©Copyright 2007.Handout . individually or as a unit. A table can have multiple UNIQUE constraints. The Database Consistency Checker (DBCC) CHECKCONSTRAINTS statement will return any rows containing data that violates a CHECK constraint. A CHECK constraint cannot contain subqueries. Table-level CHECK constraints can reference multiple columns in the same table to allow for crossreferencing and comparison of column values. A UNIQUE constraint is helpful when you already have a primary key. A CHECK constraint can be any logical (Boolean) expression that returns TRUE OR FALSE. whereas it can have only a single primary key. such as tax numbers or passport numbers. ntext. Example: TaxNumber nvarchar(30) NOT NULL UNIQUE NONCLUSTERED CHECK Constraints A CHECK constraint restricts the data values that users can enter into a particular column during INSERT and UPDATE statements. are also unique. The database engine will return an error if you create a UNIQUE constraint on the column that contains data in which duplicate values are found. Business logic dictates that the data stored in a column must be unique. The data stored in a column has natural uniqueness on the values it can contain. Cognizant Technology Solutions. All Rights Reserved C3: Protected .SQL Server 2005 UNIQUE Constraints A UNIQUE constraint specifies that two rows in a column cannot have the same value. or image data types.
Considerations for using the IDENTITY property: A table can have only one column defined with the IDENTITY property. job_desc VARCHAR (50) DEFAULT 'N/A'. Relationships exist between the columns of a table that restrict that values a column can contain. Syntax: CONSTRAINT {constraint_name} CHECK {Check_expression} Example: CONSTRAINT DepartmentConstraint CHECK (department_no < 0 AND department_no > 100) DEFAULT Constraints A DEFAULT constraint enters a value in a column when one is not specified in an INSERT statement. identifies a row uniquely. or tinyint data type. Page 22 ©Copyright 2007. Identity. int. smallint. job_desc VARCHAR (50) CONSTRAINT DF_job_desc DEFAULT 'N/A'.Handout . All Rights Reserved C3: Protected . As rows are inserted. Consider the following facts before you implement a DEFAULT constraint: A DEFAULT constraint applies only to insert statements. numeric. like a primary key. SQL Server generates the row value for an identity column by adding an increment to the existing maximum value. and that column must be defined using the decimal. The data stored in a column has natural limits on the values it can contain. Each column can have only one DEFAULT constraint. …) CREATE TABLE job(… . Consider using a DEFAULT constraint when: The data stored in a column has an obvious default value. The column does not accept null values The column done not enforce unique values. bigint. …) Identity property Identity is a column property that auto generates unique ids for newly inserted rows. Columns with the IDENTITY property or the rowversion data type cannot have a DEFAULT constraint placed on them.SQL Server 2005 Consider using a CHECK constraint when: Business logic dictates that the data stored in a column must be a member of a specific set or range of values. SQL Server implements row identification using a numeric value. Example: CREATE TABLE job(… . Cognizant Technology Solutions. DEFAULT constraints enforce domain integrity.
and any combination of these connected by one or more operators. The OBJECTPROPERTY function can be used to determine if a table has an IDENTITY column. SQL Server automatically uses the new inserted value as the current identity value Syntax: IDENTITY [(seed. Their values are recalculated every time they are referenced in a query. variable. Unitprice int.Handout . cust_name varchar(30) NOT NULL. @@IDENTITY returns the last-inserted identity value. Computed columns are virtual columns that are not physically stored in the table. Page 23 ©Copyright 2007. It allows explicit values to be inserted into the identity column of a table. constant. The column can be referenced in a select list by using the IDENTITYCOL keyword after the IDENTITY property has been set. If the value inserted is larger than the current identity value for the table. and the COLUMNPROPERTY function can be used to determine the name of the IDENTITY column. increment)] Arguments Seed: Is the value that is used for the very first row loaded into the table. Cognizant Technology Solutions. The identifier column must not allow null values and must not contain a DEFAULT definition or object. Example: CREATE TABLE Price (Qty int.SQL Server 2005 The seed and increment can be specified. SET IDENTITY_INSERT { table } ON is used to temporarily disallow autogeneration. The default value for both is 1. All Rights Reserved C3: Protected . function. Example: CREATE TABLE customer ( cust_id int IDENTITY NOT NULL. The expression cannot be a subquery. Increment: Is the incremental value that is added to the identity value of the previous row that was loaded. The SQL Server 2005 Database Engine applies the PERSISTED keyword in the CREATE TABLE and ALTER TABLE statements to physically store computed columns in the table. Total as Qty+Unitprice PERSISTED ) . The expression can be a noncomputed column name. CONSTRAINT PK_Customer_CustID PRIMARY KEY (cust_id) ) Computed Columns and Persisted Columns A computed column is computed from an expression that can apply other columns in the same table.
What are the different types of integrity? What are the two ways of enforcing domain integrity? Which one of them is preferable? Can Primary and Foreign keys have null values? How would you auto generate primary keys? Page 24 ©Copyright 2007. 2.SQL Server 2005 Summary Enforcing data integrity guarantees the quality of the data in the database. 4. All Rights Reserved C3: Protected . Entity integrity defines a row as a unique entity for a particular table. 3.Handout . Domain integrity is the validity of entries for a specific column Referential integrity preserves the defined relationships between tables SQL Server 2005 provides the following mechanisms to enforce the integrity of the data in a column: o o o o o o PRIMARY KEY Constraints FOREIGN KEY Constraints UNIQUE Constraints CHECK Constraints DEFAULT Definitions Allowing Null Values Test your Understanding 1. Cognizant Technology Solutions.
and concatenating strings. and Joins Execute DDL Statements like Create table Describe TSQL Enhancements (CTE. SubQueries. Transact-SQL provides a number of capabilities that extend beyond typical implementations of SQL. In addition. Update and Delete Write Queries. conditional operations (IFTHEN-ELSE). APPLY). All Rights Reserved C3: Protected . The Transact-SQL language is compliant with the American National Standards Institute (ANSI) SQL-92 standard at the entry level. It is the core of the decision-support capabilities of the SQL server engine. For example. and drill into a result set by further selecting data directly from a SELECT statement. finding substrings and so on). Cognizant Technology Solutions. These capabilities allow easily and efficiently writing queries that are difficult to write in standard SQL. It is specific to SQL Server databases only. Transact-SQL also provides mathematical operations such as returning the square root of a number. Transact SQL (T-SQL) is a powerful and unique superset of the SQL standard. and error checking—that can simplify application development by allowing the user to use a simple SQL script rather than a third-generation programming language (3GL). Joins and T-SQL Enhancements Learning Objectives After completing this session. and looping. where the analysis can be optimized as part of the execution plan of a query. The CASE expression can be used to easily make complex conditional substitutions in the SELECT statement. and for manipulating and formatting date information. Page 25 ©Copyright 2007.SQL Server 2005 Session 09 and 12: Subqueries. cursors. for converting datatypes. comparing values. It offers considerably more power because of its unique extensions to the standard. it is possible to embed additional SELECT statements in the SELECT list. special operators such as CUBE and ROLLUP can be used to efficiently perform multidimensional analysis at the database server. It provides a large collection of operators for doing arithmetic. Transact-SQL provides many system functions for dealing with strings (for concatenating strings. doing bit operations. a feature known as a derived table. UNPIVOT. you will be able to: Explain TSQL Fundamentals Execute DML Statements like Select. TSQL Fundamentals Transact-SQL is Microsoft's version of the Structured Query Language (SQL). PIVOT.Handout . Transact-SQL provides programming constructs—such as variables. Insert.
The T-SQL Select is similar to the SQL statement. Processing Order of WHERE.SQL Server 2005 Stored procedures and functions are collections of SQL statements stored in a SQL Server database. 3. Example: SELECT GetDate() Page 26 ©Copyright 2007. For example. and HAVING Clauses The following steps show the processing order for a SELECT statement with a WHERE clause.Handout . 5. The GROUP BY clause collects the selected rows into one group for each unique value in the GROUP BY clause. a GROUP BY clause. on the other hand. a stored procedure might be written to insert a new order into a table. GROUP BY. Triggers are a special class of stored procedure defined to execute automatically when an UPDATE. assign local variables. or DELETE statement is issued against a table or view. returns a value and that value can be used anywhere that any SQL statement can use a single value. The Select can be used to retrieve data. The full syntax of the SELECT statement is complex. and a HAVING clause: 1. INSERT. and the data must be checked for validity before the actual insert occurs. 4. The SELECT Statement The SELECT statement is the most frequently used SQL command and is the fundamental way to query data. All Rights Reserved C3: Protected . A function. The WHERE clause excludes rows not meeting its search condition. Stored procedures perform actions and usually contain all the error checking associated with that action. EXCEPT and INTERSECT operators can be used between queries to combine or compare their results into one result set. The FROM clause returns an initial result set. Stored procedures and functions differ from each other in how they're used in the code. Complex queries and transactions can be written as stored procedures and then invoked directly from the front-end application. but more powerful. Stored procedures are basic building blocks in database application development. join tables. The HAVING clause additionally excludes rows not meeting its search condition. 2. but the main clauses can be summarized as: WITH <common_table_expression>] SELECT select_list [ INTO new_table ] [ FROM table_source ] [ WHERE search_condition ] [ GROUP BY group_by_expression ] [ HAVING search_condition ] [ ORDER BY order_expression [ ASC | DESC ] ] The UNION. It retrieves rows from the database and allows the selection of one or many rows or columns from one or many tables. and even create other tables. Aggregate functions specified in the select list calculate summary values for each group. Cognizant Technology Solutions.
UPDATE. and DELETE statements. Qualify column_name to prevent an ambiguous reference. and DELETE statements. Null values are considered equal for the purposes of the DISTINCT keyword. < select_list > The columns to be selected for the result set. ALL is the default. TOP expression [ PERCENT ] [ WITH TIES ] Indicates that only a specified first set or percent of rows will be returned from the query result set. such as occurs when two tables in the FROM clause have columns with duplicate names.* | { column_name | [ ] expression | $IDENTITY | $ROWGUID } | udt_column_name [ { . the SalesOrderHeader and SalesOrderDetail tables in the AdventureWorks database both have a column named ModifiedDate.n] ) } ] [ [ AS ] column_alias ] | column_alias = expression } [ . DISTINCT Specifies that only unique rows can appear in the result set. * Specifies that all columns from all tables and views in the FROM clause should be returned. If the two Page 27 ©Copyright 2007... The columns are returned by table or view. expression can be either a number or a percent of the rows. | :: } { { property_name | field_name } | method_name(argument [. and in the order in which they exist in the table or view.. table_ name | view_ name | table_ alias. The maximum number of expressions that can be specified in the select list is 4096. UPDATE.n ] Arguments: ALL Specifies that duplicate rows can appear in the result set. as specified in the FROM clause. The select list is a series of expressions separated by commas. For example. column_ name Is the name of a column to return...SQL Server 2005 SELECT Clause Syntax SELECT [ ALL | DISTINCT ] [ TOP expression [ PERCENT ] [ WITH TIES ] ] <select_list> <select_list> ::= { * | { table_name | view_name | table_alias }. The TOP clause can be used in SELECT. Cognizant Technology Solutions. Parentheses delimiting expression in TOP is required in INSERT..Handout . INSERT.* Limits the scope of the * to the specified table or view. All Rights Reserved C3: Protected .
for example: USE AdventureWorks. or HAVING clause.. Aliases are used also to specify names for the results of expressions.. GO SELECT AVG(UnitPrice) AS 'Average Price' FROM Sales. $IDENTITY Returns the identity column. derived tables. Cognizant Technology Solutions.n ] ) ] | user_defined_function [ [ AS ] table_alias ] | OPENXML <openxml_clause> | derived_table [ AS ] table_alias [ ( column_alias [ . an alias such as Quantity. column_ alias Is an alternative name to replace the column name in the query result set.Handout .. views. FROM Clause Specifies the tables.SQL Server 2005 tables are joined in a query. All Rights Reserved C3: Protected .. and joined tables used in DELETE. or Quantity to Date.SalesOrderDetail. variables. column_alias cannot be used in the FOR UPDATE clause. $ROWGUID Returns the row GUID column. expression Is a column name. However.. constant. ]. In the SELECT statement. it cannot be used in a WHERE. and UPDATE statements. Syntax [ FROM { <table_source> } [ .. SELECT. If the query expression is part of a DECLARE CURSOR statement...n ] ) ] | rowset_function [ [ AS ] table_alias ] [ ( bulk_column_alias [ .n ] ) ] | <joined_table> | <pivoted_table> | <unpivoted_table> } <tablesample_clause> ::= TABLESAMPLE [SYSTEM] ( sample_number [ PERCENT | ROWS ] ) Page 28 ©Copyright 2007. any combination of column names. and arithmetic expressions (no column names). the modified date of the SalesOrderDetail entries can be specified in the select list as SalesOrderDetail. function. and functions connected by an operator or operators.n ] ] <table_source> ::= { table_or_view_name [ [ AS ] table_alias ] [ <tablesample_clause> ] [ WITH ( < table_hint > [ [ . the FROM clause is required except when the select list contains only constants.ModifiedDate. constants. For example.. column_alias can be used in an ORDER BY clause. GROUP BY. or Qty can be specified for a column named quantity.. or a subquery..
. A table variable can be specified as a table source. or derived table source. to use in the Transact-SQL statement.SQL Server 2005 [ REPEATABLE ( repeat_seed ) ] <joined_table> ::= { <table_source> <join_type> <table_source> ON <search_condition> | <table_source> CROSS JOIN <table_source> | left_table_source { CROSS | OUTER } APPLY right_table_source | [ ( ] <joined_table> [ ) ] } <join_type> ::= [ { INNER | { { LEFT | RIGHT | FULL } [ OUTER ] } } [ <join_hint> ] ] JOIN <pivoted_table> ::= table_source PIVOT <pivot_clause> table_alias <pivot_clause> ::= ( aggregate_function ( value_column ) FOR pivot_column IN ( <column_list> ) ) <unpivoted_table> ::= table_source UNPIVOT <unpivot_clause> table_alias <unpivot_clause> ::= ( value_column FOR pivot_column IN ( <column_list> ) ) <column_list> ::= column_name [ . ] Arguments <table_source> Specifies a table. table_or_view_name Is the name of a table or view. Cognizant Technology Solutions. although the limit varies depending on available memory and the complexity of other expressions in the query.. The order of table sources after the FROM keyword does not affect the result set that is returned. Up to 256 table sources can be used in a statement. with or without an alias. All Rights Reserved C3: Protected . . Page 29 ©Copyright 2007. SQL Server 2005 returns errors when duplicate names appear in the FROM clause.Handout . Individual queries may not support up to 256 table sources. view.
When you use bulk_column_alias. When specified with the same repeat_seed value. column_alias Is an optional alias to replace a column name in the result set of the derived table. or alias. and enclose the complete list of column aliases in parentheses.object_name. such as OPENROWSET. the sample_number expression must evaluate to an integer value greater than zero. SQL Server will likely return some different sample of the rows in the table. use a four-part name in the form linked_server.schema. view name. that returns an object that can be used instead of a table reference. user_defined_function Specifies a table-valued function. [AS] table_alias Is an alias for table_source that can be used either for convenience or to distinguish a table or view in a self-join or subquery. WITH (<table_hint> ) Specifies that the query optimizer use an optimization or locking strategy with this table and for this statement. The table name cannot be used if an alias is defined. rowset_function Specifies one of the rowset functions. If the same column name exists in more than one table in the join. If the table or view exists outside the local server on a linked server. rowset or table-valued function. bulk_column_alias Is an optional alias to replace a column name in the result set. When specified with a different repeat_seed value. The Page 30 ©Copyright 2007. Include one column alias for each column in the select list. When ROWS is specified. or operator clause (such as PIVOT or UNPIVOT) is used. ROWS Specifies that approximately sample_number of rows will be retrieved. When ROWS is specified. All Rights Reserved C3: Protected .schema. REPEATABLE Indicates that the selected sample can be returned again. the required table_alias at the end of the clause is the associated table name for all columns. use a fully qualified name in the form database. derived_table Is a subquery that retrieves rows from the database. including grouping columns.catalog. Cognizant Technology Solutions.object. A four-part table or view name that is constructed by using the OPENDATASOURCE function as the server part of the name can also be used to specify the table source. Column aliases are allowed only in SELECT statements that use the OPENROWSET function with the BULK option. returned. derived_table is used as input to the outer query. SQL Server will return the same subset of rows as long as no changes have been made to any rows in the table. An alias is frequently a shortened table name used to refer to specific columns of the tables in a join. OPENXML <openxml_clause> Provides a rowset view over an XML document.Handout . When a derived table. specify an alias for every table column in the same order as the columns in the file. SQL Server requires that the column name be qualified by a table name. SQL Server returns an approximation of the number of rows specified.SQL Server 2005 If the table or view exists in another database on the same computer that is running an instance of SQL Server.
per join specified in the query FROM clause. although columns and comparison operators are frequently used. Page 31 ©Copyright 2007. use parentheses to change the natural order of the joins.ProductID) When the condition specifies columns. INNER Specifies all matching pairs of rows are returned. Discards unmatched rows from both tables. index rebuild or defragmentation. or execution algorithm. When no join type is specified. however. The condition can specify any predicate. v. and database restore or attach. the columns do not have to have the same name or same data type. if the data types are not the same.VendorID FROM Production. RIGHT [OUTER] Specifies all rows from the right table not meeting the join condition are included in the result set. and output columns from the other table are set to NULL in addition to all rows returned by the inner join. For multiple joins. <joined_table> Is a result set that is the product of two or more tables. Cognizant Technology Solutions. for example: SELECT p.Handout . The repeat_seed expression must evaluate to an integer greater than zero. FULL [ OUTER ] Specifies that a row from either the left or right table that does not meet the join condition is included in the result set. the sampling result is always the same if no changes have been applied to the table. If the data types cannot be implicitly converted. and output columns that correspond to the other table are set to NULL. repeat_seed Is a constant integer expression used by SQL Server to generate a random number. delete. repeat_seed is bigint. SQL Server assigns a value at random. and output columns that correspond to the other table are set to NULL. this is the default. For a specific repeat_seed value. <join_hint> Specifies that the SQL Server query optimizer use one join hint. JOIN Indicates that the specified join operation should occur between the specified table sources or views.SQL Server 2005 following actions to the table are considered changes: insert. the condition must explicitly convert the data type by using the CONVERT function. All Rights Reserved C3: Protected . in addition to all rows returned by the inner join. If repeat_seed is not specified. ON <search_condition> Specifies the condition on which the join is based. This is in addition to all rows typically returned by the INNER JOIN. <join_type> Specifies the type of join operation.Product p JOIN Purchasing. they must be either compatible or types that SQL Server 2005 can implicitly convert. LEFT [ OUTER ] Specifies that all rows from the left table not meeting the join condition are included in the result set. update.ProductID = v.ProductID.ProductVendor v ON (p.
Returns the same rows as if no WHERE clause was specified in an old-style. The output is a table that contains all columns of the table_source except the pivot_column and value_column. For more information. left_table_source Is a table source as defined in the previous argument. The aggregate function should be invariant to null values. Additionally. This functionality is useful when the right_table_source contains a table-valued function that takes column values from the left_table_source as one of its arguments. pivot_column must be of a type implicitly or explicitly convertible to nvarchar(). see the Remarks section. All Rights Reserved C3: Protected . FOR pivot_column Is the pivot column of the PIVOT operator. This column cannot be image or rowversion. PIVOT performs a grouping operation on the input table with regard to the grouping columns and returns one row for each group. When CROSS is specified. except the pivot_column and value_column. When used with UNPIVOT. the output contains one column for each value specified in the column_list that appears in the pivot_column of the input_table. Page 32 ©Copyright 2007. value_column cannot be the name of an existing column in the input table_source.SQL Server 2005 There can be predicates that involve only one of the joined tables in the ON clause. Such predicates also can be in the WHERE clause in the query. Cognizant Technology Solutions. non-SQL-92-style join. The columns of the table_source.Handout . one row is produced for each row of the left_table_source even when the right_table_source evaluates against that row and returns an empty result set. The COUNT(*) system aggregate function is not allowed. left_table_source { CROSS | OUTER } APPLY right_table_source Specifies that the right_table_source of the APPLY operator is evaluated against every row of the left_table_source. value_column Is the value column of the PIVOT operator. Either CROSS or OUTER must be specified with APPLY. This is because the predicates in the ON clause are applied to the table before the join. whereas the WHERE clause is semantically applied to the result of the join. When OUTER is specified. right_table_source Is a table source as defined in the previous argument. aggregate_function Is a system or user-defined aggregate function. see the Remarks section and Using APPLY. An aggregate function invariant to null values does not consider null values in the group while it is evaluating the aggregate value. Although the placement of such predicates does not make a difference for INNER joins. CROSS JOIN Specifies the cross-product of two tables. they might cause a different result when OUTER joins are involved. table_source is a table or table expression. table_source PIVOT <pivot_clause> Specifies that the table_source is pivoted based on the pivot_column. see the Remarks section. For more information. no rows are produced when the right_table_source is evaluated against a specified row of the left_table_source and returns an empty result set. are called the grouping columns of the pivot operator. For more information.
pivot_table_alias must be specified.row). lists the values in the pivot_column that will become the column names of the output table. but it cannot contain arguments that are columns from the right_table_source. pivot_column is the name of the output column that becomes narrowed from the table_source. Using PIVOT and UNPIVOT The pivot_column and value_column are grouping columns that are used by the PIVOT operator. UNPIVOT < unpivot_clause > Specifies that the input table is narrowed from multiple columns in column_list into a single column called pivot_column. Generates values for the columns in the column list for each output row by performing the following: a) Grouping additionally the rows generated in the GROUP BY in the previous step against the pivot_column.Handout . table_alias Is the alias name of the output table. Combines the result sets that are produced for each row in the evaluation of right_table_source with the left_table_source by performing a UNION ALL operation. The list cannot specify any column names that already exist in the input table_source that is being pivoted. All Rights Reserved C3: Protected . IN ( column_list ) In the PIVOT clause. The values in the right_table_source depend on left_table_source. Cognizant Technology Solutions. Performs a GROUP BY on its input_table against the grouping columns and produces one output row for each group. Page 33 ©Copyright 2007. 2.SQL Server 2005 When UNPIVOT is used. The main difference between these operands is that the right_table_source can use a table-valued function that takes a column from the left_table_source as one of the arguments of the function. Evaluates right_table_source against each row of the left_table_source to produce rowsets. The list of columns produced by the result of the APPLY operator is the set of columns from the left_table_source that is combined with the list of columns from the right_table_source. The grouping columns in the output row obtain the corresponding column values for that group in the input_table. right_table_source can be represented approximately this way: TVF(left_table_source. In the UNPIVOT clause. Using APPLY Both the left and right operands of the APPLY operator are table expressions. The APPLY operator works in the following way to produce the table source for the FROM clause: 1. where TVF is a tablevalued function. There cannot be an existing column in table_source with that name. PIVOT follows the following process to obtain the output result set: 1. 2. lists the columns in table_source that will be narrowed into a single pivot_column. The left_table_source can include table-valued functions.
GO -. USE AdventureWorks . Page 34 ©Copyright 2007. SQL Server generates a null value for that output_column. Using the TABLOCK and HOLDLOCK optimizer hints The following partial transaction shows how to place an explicit shared table lock on Employee and how to read the index. Using the SQL-92 FULL OUTER JOIN syntax The following example returns the product name and any corresponding sales orders in the SalesOrderDetail table. USE AdventureWorks . If the subgroup is empty.Name . If the aggregate function is COUNT and the subgroup is empty.SQL Server 2005 b) For each output column in the column_list. Examples Using a simple FROM clause The following example retrieves the TerritoryID and Name columns from the SalesTerritory table in the AdventureWorks sample database.EmployeeID.Handout . d. d.The OUTER keyword following the FULL keyword is optional. GO SELECT e. GO SELECT TerritoryID. It also returns any sales orders that have no product listed in the Product table. The lock is held throughout the whole transaction.SalesTerritory ORDER BY TerritoryID . USE AdventureWorks . HOLDLOCK) .Employee e CROSS JOIN HumanResources. and any products with a sales order other than the one listed in the Product table.Name AS Department FROM HumanResources. Name FROM Sales.Employee WITH (TABLOCK. A list of all possible combinations of EmployeeID rows and all Department name rows are returned. Using the SQL-92 CROSS JOIN syntax The following example returns the cross product of the two tables Employee and Department.EmployeeID. zero (0) is returned.Department d ORDER BY e. selecting a subgroup that satisfies the condition: pivot_column = CONVERT(<data type of pivot_column>. Cognizant Technology Solutions. 'output_column') c) aggregate_function is evaluated against the value_column on this subgroup and its result is returned as the value of the corresponding output_column. All Rights Reserved C3: Protected . GO BEGIN TRAN SELECT COUNT(*) FROM HumanResources. USE AdventureWorks .
SQL Server 2005 SELECT p.Name.SalesTerritory st RIGHT OUTER JOIN Sales.ProductID = sod. The Product table is matched with the SalesOrderDetail table on the ProductID columns in each table.Product p INNER JOIN Sales. Cognizant Technology Solutions.SalesOrderID FROM Production. GO SELECT st.SalesPerson sp ON st.Name . All products. SELECT p. SQL Server performs an INNER JOIN if only the JOIN -. whether or not they are assigned a territory.SalesOrderID FROM Production.ProductID IS NULL ORDER BY p. The query optimizer joins Product and Page 35 ©Copyright 2007.ProductID = sod.Name.SalesOrderDetail sod ON p.SalesOrderID FROM Production. ProductVendor.TerritoryID . sod.keyword is specified.Product p FULL OUTER JOIN Sales.Name AS Territory. USE AdventureWorks . Using the SQL-92 RIGHT OUTER JOIN syntax The following example joins two tables on TerritoryID and preserves the unmatched rows from the right table.ProductID = sod.By default. GO SELECT p.SalesOrderDetail sod ON p.SalesPersonID FROM Sales. The SalesTerritory table is matched with the SalesPerson table on the TerritoryID column in each table.ProductID ORDER BY p.ProductID WHERE p. USE AdventureWorks . USE AdventureWorks . sod.Name .Name.SalesOrderDetail sod ON p. The following example returns all product names and sales order IDs. sp. sod. All salespersons appear in the result set. appear in the result set. All Rights Reserved C3: Protected . ordered and not ordered. and Vendor tables to produce a list of products and their vendors. Using HASH and MERGE join hints The following example performs a three-table join among the Product.Name . GO -.ProductID IS NULL OR sod.ProductID ORDER BY p.TerritoryID = sp.Product p LEFT OUTER JOIN Sales.Handout . Using the SQL-92 LEFT OUTER JOIN syntax The following example joins two tables on ProductID and preserves the unmatched rows from the left table.
City FROM Person.Name .Handout .FirstName) + ' ' + LTRIM(c.ProductID = pv.ContactID = e.AddressID ORDER BY c.Employee e ON c.FirstName . EmpSalary) that report directly or indirectly to the specified MgrID.ProductVendor pv ON p. Using a derived table The following example uses a derived table. EmpFirstName. EmpID Employees: EmpID.VendorID ORDER BY p. d.ProductID INNER HASH JOIN Purchasing. v. a SELECT statement after the FROM clause.Product p INNER MERGE JOIN Purchasing.Name AS ProductName.SQL Server 2005 ProductVendor (p and pv) by using a MERGE join. v.Customer TABLESAMPLE SYSTEM (10 PERCENT) . the results of the Product and ProductVendor MERGE join (p and pv) are HASH joined to the Vendor table to produce (p and pv) and v. USE AdventureWorks . All Rights Reserved C3: Protected . GO SELECT RTRIM(c. DeptMgrID EmpMgr: MgrID.ContactID INNER JOIN (SELECT AddressID.LastName.VendorID = v.LastName) AS Name.AddressID = d.Address) AS d ON e. Next. USE AdventureWorks . Using APPLY The following example assumes that the following tables with the following schema exist in the database: Departments: DeptID. EmpLastName. Page 36 ©Copyright 2007.Contact c INNER JOIN HumanResources. c. DeptName. EmpSalary There is also a table-valued function. USE AdventureWorks . GO SELECT * FROM Sales. GO SELECT p. DivisionID.Name. to return the first and last names of all employees and the cities in which they live.Name AS VendorName FROM Production. Cognizant Technology Solutions. City FROM Person. GetReports(MgrID) that returns the list of all employees (EmpID.Vendor v ON pv. EmpLastName. Using TABLESAMPLE to read data from a sample of rows in a table The following example uses TABLESAMPLE in the FROM clause to return approximately 10 percent of all the rows in the Customer table in the AdventureWorks database.
Handout - SQL Server 2005
The example uses APPLY to return all departments and all employees in that department. If a particular department does not have any employees, there will not be any rows returned for that department. SELECT DeptID, DeptName, DeptMgrID, EmpID, EmpLastName, EmpSalary FROM Departments d CROSS APPLY dbo.GetReports(d.DeptMgrID) ; If you want the query to produce rows for those departments without employees, which will produce null values for the EmpID, EmpLastName and EmpSalary columns, use OUTER APPLY instead. SELECT DeptID, DeptName, DeptMgrID, EmpID, EmpLastName, EmpSalary FROM Departments d OUTER APPLY dbo.GetReports(d.DeptMgrID) ; Using PIVOT and UNPIVOT The following example returns the number of purchase orders placed by employee IDs 164, 198, 223, 231, and 233, categorized by vendor ID. USE AdventureWorks GO SELECT VendorID, [164] AS Emp1, [198] AS Emp2, [223] AS Emp3, [231] AS Emp4, [233] AS Emp5 FROM (SELECT PurchaseOrderID, EmployeeID, VendorID FROM Purchasing.PurchaseOrderHeader) p PIVOT ( COUNT (PurchaseOrderID) FOR EmployeeID IN ( [164], [198], [223], [231], [233] ) ) AS pvt ORDER BY VendorID; Here is a partial result set: VendorID 1 2 3 4 5 Emp1 4 4 4 4 5 Emp2 3 1 3 2 1 Emp3 5 5 5 5 5 Emp4 4 5 4 5 5 Emp5 4 5 4 4 5
To unpivot the table, assume the result set produced in the previous example is stored as pvt. The query looks like the following. --Create the table and insert values as portrayed in the previous example. CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int, Emp3 int, Emp4 int, Emp5 int) GO
Page 37 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
INSERT INTO pvt VALUES (1,4,3,5,4,4) INSERT INTO pvt VALUES (2,4,1,5,5,5) INSERT INTO pvt VALUES (3,4,3,5,4,4) INSERT INTO pvt VALUES (4,4,2,5,5,4) INSERT INTO pvt VALUES (5,5,1,5,5,5) GO --Unpivot the table. SELECT VendorID, Employee, Orders FROM (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5 FROM pvt) p UNPIVOT (Orders FOR Employee IN (Emp1, Emp2, Emp3, Emp4, Emp5) )AS unpvt GO Here is a partial result set: VendorID 1 1 1 1 1 2 2 2 2 2 Employee Emp1 Emp2 Emp3 Emp4 Emp5 Emp1 Emp2 Emp3 Emp4 Emp5 Orders 4 3 5 4 4 4 1 5 5 5
WHERE clause
Specifies the search condition for the rows returned by the query. Syntax [ WHERE <search_condition> ] Arguments < search_condition > Defines the condition to be met for the rows to be returned. There is no limit to the number of predicates that can be included in a search condition. For more Is a combination of one or more predicates that use the logical operators AND, OR, and NOT.
Page 38 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
Syntax < search_condition > ::= { [ NOT ] <predicate> | ( <search_condition> ) } [ { AND | OR } [ NOT ] { <predicate> | ( <search_condition> ) } ] [ ,...n ] <predicate> ::= { expression { = | < > | ! = | > | > = | ! > | < | < = | ! < } expression | string_expression [ NOT ] LIKE string_expression [ ESCAPE 'escape_character' ] | | | ( | | expression expression CONTAINS { column | FREETEXT ( expression [ NOT ] BETWEEN expression AND expression IS [ NOT ] NULL * } , '< contains_search_condition >' ) { column | * } , 'freetext_string' ) [ NOT ] IN ( subquery | expression [ ,...n ] )
| expression { = | < > | ! = | > | > = | ! > | < | < = | ! < } { ALL | SOME | ANY} ( subquery ) | EXISTS ( subquery ) }
Arguments <search_condition> Specifies the conditions for the rows returned in the result set for a SELECT statement, query expression, or subquery. For an UPDATE statement, specifies the rows to be updated. For a DELETE statement, specifies the rows to be deleted. There is no limit to the number of predicates that can be included in a Transact-SQL statement search condition. NOT Negates the Boolean expression specified by the predicate. AND Combines two conditions and evaluates to TRUE when both of the conditions are TRUE. OR Combines two conditions and evaluates to TRUE when either condition is TRUE. < predicate > Is an expression that returns TRUE, FALSE, or UNKNOWN. expression Is a column name, a constant, a function, a variable, a scalar subquery, or any combination of column names, constants, and functions connected by an operator or operators, or a subquery. The expression can also contain the CASE function. = Is the operator used to test the equality between two expressions. <> Is the operator used to test the condition of two expressions not being equal to each other. != Is the operator used to test the condition of two expressions not being equal to each other.
Page 39 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
> Is the operator used to test the condition of one expression being greater than the other. >= Is the operator used to test the condition of one expression being greater than or equal to the other expression. !> Is the operator used to test the condition of one expression not being greater than the other expression. < Is the operator used to test the condition of one expression being less than the other. <= Is the operator used to test the condition of one expression being less than or equal to the other expression. !< Is the operator used to test the condition of one expression not being less than the other expression. string_expression Is a string of characters and wildcard characters. [ NOT ] LIKE Indicates that the subsequent character string is to be used with pattern matching pattern Is the specific string of characters to search for in match_expression, and can include the following valid wildcard characters. pattern can be a maximum of 8,000 bytes. Wildcard character % Description Any string of zero or more characters. Example WHERE title LIKE '%computer%' finds all book titles with the word 'computer' anywhere in the book title. WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on).
_ (underscore)
Any single character.
WHERE au_lname LIKE '[C-P]arsen' finds author last Any single character within names ending with arsen and starting with any single the specified range ([a-f]) character between C and P, for example Carsen, or set ([abcdef]). Larsen, Karsen, and so on. Any single character not within the specified range ([^a-f]) or set ([^abcdef]). WHERE au_lname LIKE 'de[^l]%' all author last names starting with de and where the following letter is not l.
ESCAPE 'escape_ character' Allows for a wildcard character to be searched for in a character string instead of functioning as a wildcard. escape_character is the character that is put in front of the wildcard character to indicate this special use.
Page 40 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
the query would search for any description values that contain the word green followed by any single character other than the _ character. a subquery. An expression with a bitwise or arithmetic operator evaluates to NULL if any one of the operands is NULL. the proximity of words within a certain distance of one another. Without specifying the ESCAPE option. or FALSE when no values in the subquery satisfy the comparison or when the subquery returns no rows to the outer statement.Handout . and the INTO keyword are not allowed ALL Used with a comparison operator and a subquery. based on whether the expression is included in or excluded from a list. All Rights Reserved C3: Protected . This option can only be used with SELECT statements. GO SELECT * FROM Production. more typically.SQL Server 2005 [ NOT ] BETWEEN Specifies an inclusive range of values. depending on the keywords used. and weighted matches. or FALSE when not all values satisfy the comparison or when the subquery returns no rows to the outer statement { SOME | ANY } Used with a comparison operator and a subquery. USE AdventureWorks .ProductPhoto Page 41 ©Copyright 2007. the expression is UNKNOWN. FREETEXT Provides a simple form of natural language query by searching columns that contain character-based data for values that match the meaning instead of the exact words in the predicate. This option can only be used with SELECT statements. the COMPUTE clause. IS [ NOT ] NULL Specifies a search for null values. Returns TRUE for <predicate> when all values retrieved for the subquery satisfy the comparison operation. The search expression can be a constant or a column name. Otherwise. Examples Using WHERE with LIKE and ESCAPE syntax The following example searches for the rows in which the LargePhotoFileName column has the characters green_. Cognizant Technology Solutions. Returns TRUE for <predicate> when any value retrieved for the subquery satisfies the comparison operation. or for values that are not null. Use AND to separate the starting and ending values. [ NOT ] IN Specifies the search for an expression. Enclose the list of values in parentheses subquery Can be considered a restricted SELECT statement and is similar to <query_expresssion> in the SELECT statement. CONTAINS Searches columns that contain character-based data for precise or less precise (fuzzy) matches to single words and phrases. EXISTS Used with a subquery to test for the existence of rows returned by the subquery. and uses the ESCAPE option because _ is a wildcard character. The ORDER BY clause. and the list can be a set of constants or.
USE AdventureWorks . either each column in any nonaggregate expression in the select list should be included in the GROUP BY list. GROUP BY ALL is not supported in queries that access remote tables if there is also a WHERE clause in the query. City. Syntax [ GROUP BY [ ALL ] group_by_expression [ . or the GROUP BY expression must exactly match the select list expression.Address AS a JOIN Person. CountryRegionCode FROM Person. Using WHERE and LIKE syntax with Unicode data The following example uses the WHERE clause to retrieve the mailing address for any company that is outside the United States (US) and in a city whose name starts with Mn. GO Page 42 ©Copyright 2007. All Rights Reserved C3: Protected . group_by_expression is also known as a grouping column. GO SELECT AddressLine1. null values are returned for the summary columns of groups that do not meet the search condition..n ] [ WITH { CUBE | ROLLUP } ] ] Arguments ALL Includes all groups and result sets. When GROUP BY is specified. If aggregate functions are included in the SELECT clause <select list>. PostalCode.. group_by_expression Is an expression on which grouping is performed. You cannot specify ALL with the CUBE or ROLLUP operators. even those that do not have any rows that meet the search condition specified in the WHERE clause.Handout . A column alias that is defined in the select list cannot be used to specify a grouping column. GROUP BY clause Specifies the groups into which output rows are to be placed.StateProvinceID = s.StateProvinceID WHERE CountryRegionCode NOT IN ('US') AND City LIKE N'Mn%' .. GROUP BY calculates a summary value for each group. group_by expression can be a column or a nonaggregate expression that references a column returned by the FROM clause. Cognizant Technology Solutions.StateProvince AS s ON a. Examples Using a simple GROUP BY clause The following example retrieves the total for each SalesOrderID from the SalesOrderDetail table.SQL Server 2005 WHERE LargePhotoFileName LIKE '%greena_%' ESCAPE 'a' . AddressLine2. USE AdventureWorks . When ALL is specified.
Address a ON e. the HAVING clause overrides ALL.SQL Server 2005 SELECT SalesOrderID. Syntax [ HAVING <search condition> ] Arguments <search_condition> Specifies the search condition for the group or the aggregate to meet.City ORDER BY a. HAVING behaves like a WHERE clause.00. Using a GROUP BY clause with multiple tables The following example retrieves the number of employees for each City from the Address table joined with the Employee table.SalesOrderDetail sod GROUP BY SalesOrderID HAVING SUM(LineTotal) > 100000. SUM(LineTotal) AS SubTotal FROM Sales. COUNT(e. Cognizant Technology Solutions.AddressID) EmployeeCount FROM HumanResources. GO SELECT SalesOrderID. USE AdventureWorks .City .SalesOrderDetail sod GROUP BY SalesOrderID ORDER BY SalesOrderID .City.Handout . SUM(LineTotal) AS SubTotal FROM Sales.AddressID GROUP BY a.00 ORDER BY SalesOrderID .Employee e INNER JOIN Person. When HAVING is used with GROUP BY ALL. The text. HAVING can be used only with the SELECT statement. Page 43 ©Copyright 2007.AddressID = a. and ntext data types cannot be used in a HAVING clause. image. USE AdventureWorks . HAVING is typically used in a GROUP BY clause. All Rights Reserved C3: Protected . GO SELECT a. When GROUP BY is not used. Examples The following example that uses a simple HAVING clause retrieves the total for each SalesOrderID from the SalesOrderDetail table that exceeds $100000. HAVING clause Specifies a search condition for a group or an aggregate.
unless TOP is also specified. However. The ORDER BY clause can include items not appearing in the select list. when the SELECT statement includes a UNION operator. or a nonnegative integer representing the position of the name or alias in the select list. ASC Specifies that the values in the specified column should be sorted in ascending order. All Rights Reserved C3: Protected . Syntax [ ORDER BY { order_by_expression [ COLLATE collation_name ] [ ASC | DESC ] } [ .Handout . The ORDER BY clause is not valid in views. and nvarchar data types.. COLLATE {collation_name} Specifies that the ORDER BY operation should be performed according to the collation specified in collation_name.. and not according to the collation of the column as defined in the table or view. if SELECT DISTINCT is specified. Page 44 ©Copyright 2007. DESC Specifies that the values in the specified column should be sorted in descending order.n ] ] Arguments order_by_expression Specifies a column on which to sort.. the sort columns must appear in the select list. and subqueries. the column names or column aliases must be those specified in the first select list. it must be unique among all columns listed in the SELECT statement. varchar. A sort column can be specified as a name or column alias. Column names and aliases can be qualified by the table or view name. nchar. For more information. The sequence of the sort columns in the ORDER BY clause defines the organization of the sorted result set. see Collation Settings in Setup and Using SQL Collations. If order_by_expression is not qualified. collation_name can be either a Windows collation name or a SQL collation name. Additionally. qualified column names and aliases are resolved to columns listed in the FROM clause. inline functions. COLLATE is applicable only for columns of the char. or if the SELECT statement contains a UNION operator. derived tables.SQL Server 2005 ORDER BY clause Specifies the sort order used on columns returned in a SELECT statement. from highest value to lowest value. from lowest value to highest value. Multiple sort columns can be specified. In Microsoft SQL Server 2005. Cognizant Technology Solutions.
GO SELECT ProductID.SalesOrderHeader AS Ord A subquery is also called an inner query or inner select. In Transact-SQL.Handout .SalesOrderID) AS MaxUnitPrice FROM AdventureWorks.Product WHERE Name = 'Chainring Bolts' ) /* SELECT statement built using a join that returns the same result set.Product WHERE ListPrice = (SELECT ListPrice FROM AdventureWorks. in some cases where existence must be checked.SQL Server 2005 Example: The following query returns results ordered by ascending ProductID: USE AdventureWorks. Many Transact-SQL statements that include subqueries can be alternatively formulated as joins. A subquery can be used anywhere an expression is allowed.Sales. */ SELECT Name FROM AdventureWorks. All Rights Reserved C3: Protected . */ SELECT Prd1. ProductLine.SalesOrderID = OrdDet. while the statement containing a subquery is also called an outer query or outer select. the nested query must be processed for each result of the outer query to ensure elimination of duplicates. Cognizant Technology Solutions.UnitPrice) FROM AdventureWorks.Product AS Prd1 JOIN AdventureWorks. a join yields better performance.Product ORDER BY ProductID Subqueries A subquery is a query that is nested inside a SELECT.Production. Other questions can be posed only with subqueries. Name = 'Chainring Bolts' Page 45 ©Copyright 2007.ListPrice) WHERE Prd2.Production. Ord.SalesOrderID. or DELETE statement. there is usually no performance difference between a statement that includes a subquery and a semantically equivalent version that does not.OrderDate. ProductModelID FROM Production. a join approach would yield better results.Production.Production. The following is an example showing both a subquery SELECT and a join SELECT that return the same result set: /* SELECT statement built using a subquery. Otherwise.Product AS Prd2 ON (Prd1. (SELECT MAX(OrdDet.ListPrice = Prd2. Name FROM AdventureWorks. or inside another subquery.SalesOrderDetail AS OrdDet WHERE Ord.Sales. SELECT Ord. INSERT. However. UPDATE. In such cases. In this example a subquery is used as a column expression named MaxUnitPrice in a SELECT statement.
All Rights Reserved C3: Protected . and may only include an ORDER BY clause when a TOP clause is also specified.Handout . An optional GROUP BY clause. If a table appears only in a subquery and not in the outer query. Cognizant Technology Solutions. Syntax [ WITH <common_table_expression> [ . INSERT Statement Adds a new row to a table or a view. Individual queries may not support nesting up to 32 levels. if it returns a single value. A regular FROM clause including one or more table or view names. then columns from that table cannot be included in the output (the select list of the outer query). Conceptually. INSERT. It cannot include a COMPUTE or FOR BROWSE clause. A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT. Statements that include a subquery usually take one of these formats: WHERE expression [NOT] IN (subquery) WHERE expression comparison_operator [ANY | ALL] (subquery) WHERE [NOT] EXISTS (subquery) In some Transact-SQL statements. the subquery results are substituted into the outer query (although this is not necessarily how Microsoft SQL Server 2005 actually processes Transact-SQL statements with subqueries). An optional WHERE clause. There are three basic types of subqueries. Are introduced with an unmodified comparison operator and must return a single value. An optional HAVING clause.SQL Server 2005 A subquery nested in the outer SELECT statement has the following components: A regular SELECT query including the regular select list components. although the limit varies based on available memory and the complexity of other expressions in the query. Up to 32 levels of nesting is possible.. the subquery can be evaluated as if it were an independent query.. or those that a comparison operator modified by ANY or ALL.n ] ] INSERT [ TOP ( expression ) [ PERCENT ] ] Page 46 ©Copyright 2007. UPDATE. or DELETE statement. or inside another subquery. The SELECT query of a subquery is always enclosed in parentheses. A subquery can appear anywhere an expression can be used. Are existence tests introduced with EXISTS. Those that: Operate on lists introduced with IN..
SQL Server 2005 [ INTO] { <object> | rowset_function_limited [ WITH ( <Table_Hint_Limited> [ . | schema_name .Handout .. ] table_or_view_name } Arguments WITH <common_table_expression>: Specifies the temporary named result set.[ schema_name ] . schema_name . and CREATE VIEW statements. database_name .. The result set is derived from a SELECT statement.. and DELETE statements. or DELETE are not arranged in any order.n ] ) ] } { [ [ { | | } } | DEFAULT VALUES [. UPDATE. TOP ( expression ) [ PERCENT ]: Specifies the number or percent of random rows that will be inserted. Parentheses delimiting expression in TOP are required in INSERT. ( column_list ) ] <OUTPUT Clause> ] VALUES ( { DEFAULT | NULL | expression } [ .. Common table expressions can also be used with the SELECT. All Rights Reserved C3: Protected .. Cognizant Technology Solutions. expression can be either a number or a percent of the rows. ] <object> ::= { [ server_name .. defined within the scope of the INSERT statement. | database_name . also known as common table expression. DELETE.n ] ) derived_table execute_statement Page 47 ©Copyright 2007. UPDATE. INTO: An optional keyword that can be used between INSERT and the target table. The rows referenced in the TOP expression that are used with INSERT. UPDATE.
The OUTPUT clause is not supported in DML statements that reference local partitioned views. o Is a computed column. or remote tables. column_list must be enclosed in parentheses and delimited by commas. Page 48 ©Copyright 2007. schema_name : The name of the schema to which the table or view belongs. database_name and schema_name are required. within its scope. an INSERT into a multitable view must use a column_list that references only columns from one base table.. All Rights Reserved C3: Protected . n ] ) : Specifies one or more table hints that are allowed for a target table. ( column_list ): Is a list of one or more columns in which to insert data. There must be one data value for each column in column_list. and the SET IDENTITY_INSERT option must be ON for the table. the SQL Server 2005 Database Engine must be able to provide a value based on the definition of the column. VALUES: Introduces the list of data values to be inserted. table_or view_name :The name of the table or view that is to receive the data. if specified. For more information about updatable views. If server_name is specified. database_name: The name of the database. If a column is not in column_list. o Has a timestamp data type.Handout . The next incremental identity value is used. rowset_function_limited: Either the OPENQUERY or OPENROWSET function. READPAST. can be used as a table source in an INSERT statement. The view referenced by table_or_view_name must be updatable and reference exactly one base table in the FROM clause of the view. The calculated value is used. WITH ( <table_hint_limited> [. distributed partitioned views. The values list must be enclosed in parentheses. otherwise. The Database Engine automatically provides a value for the column if the column: o Has an IDENTITY property. or in the table. A null value is used. NOLOCK. o Is nullable. the row cannot be loaded. A table variable. The WITH keyword and the parentheses are required. Cognizant Technology Solutions. The current timestamp value is used. OUTPUT Clause: Returns inserted rows as part of the insert operation. o Has a default.SQL Server 2005 server_name: The name of the server (using the OPENDATASOURCE function as the server name) on which the table or view is located. Specifying the TABLOCK hint on a table that is the target of an INSERT statement has the same effect as specifying the TABLOCKX hint.. For example. column_list and VALUES list must be used when explicit values are inserted into an identity column. or INSERT statements that contain an execute_statement. The default value for the column is used. and READUNCOMMITTED are not allowed. An exclusive lock is taken on the table.
each READTEXT statement can return a maximum of 1 MB (1024 KB) of data.UnitMeasure VALUES (N'F2'. NULL is inserted. the column names do not have to be specified in column_list. If a default does not exist for the column and the column allows null values. GO Page 49 ©Copyright 2007. column_list must be used to explicitly specify the column that stores each incoming value. DEFAULT is not valid for an identity column. If execute_statement returns data with the READTEXT statement. Because values for all columns are supplied and are listed in the same order as the columns in the table.SQL Server 2005 If the values in the VALUES list are not in the same order as the columns in the table or do not have a value for each column in the table. The SELECT statement cannot contain a CTE. The expression cannot contain a SELECT or EXECUTE statement. All Rights Reserved C3: Protected .Handout . GETDATE()). DEFAULT VALUES forces the new row to contain the default values defined for each column. For a column defined with the timestamp data type. derived_table: Is any valid SELECT statement that returns rows of data to be loaded into the table. expression: Is a constant. each result set must be compatible with the columns in the table or in column_list. GO INSERT INTO Production. the next timestamp value is inserted. N'Square Feet'.UnitMeasure table. output from threads other than the main thread are not inserted. a variable. If execute_statement is used with INSERT. or an expression. DEFAULT : Forces the Database Engine to load the default value defined for a column. execute_statement: Is any valid EXECUTE statement that returns data with SELECT or READTEXT statements. USE AdventureWorks. execute_statement inserts the data returned by the main thread of the extended procedure. Cognizant Technology Solutions. The procedure in the remote server is executed. and the result sets are returned to the local server and loaded into the table in the local server. execute_statement can be used to execute stored procedures on the same server or a remote server. Examples: Using a simple INSERT statement: The following example inserts one row in the Production. execute_statement can also be used with extended procedures. The SELECT statement cannot contain a common table expression (CTE). however.
Handout - SQL Server 2005
Inserting data that is not in the same order as the table columns The following example uses column_list to explicitly specify the values that are inserted into each column. The column order in the UnitMeasure table is UnitMeasureCode, Name, ModifiedDate; however, the columns are not listed in that order in column_list. USE AdventureWorks; GO INSERT INTO Production.UnitMeasure (Name, UnitMeasureCode, ModifiedDate) VALUES (N'Square Yards', N'Y2', GETDATE()); GO
UPDATE statement
Changes existing data in a table or view. Syntax [ WITH <common_table_expression> [...n] ] UPDATE [ TOP ( expression ) [ PERCENT ] ] { <object> | rowset_function_limited [ WITH ( <Table_Hint_Limited> [ ...n ] ) ] } SET { column_name = { expression | DEFAULT | NULL } | { udt_column_name.{ { property_name = expression | field_name = expression } | method_name ( argument [ ,...n ] ) } } | column_name { .WRITE ( expression , @Offset , @Length ) } | @variable = expression | @variable = column = expression [ ,...n ] } [ ,...n ] [ <OUTPUT Clause> ] [ FROM{ <table_source> } [ ,...n ] ] [ WHERE { <search_condition> | { [ CURRENT OF { { [ GLOBAL ] cursor_name } | cursor_variable_name } ] } } ]
Page 50 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
[ OPTION ( <query_hint> [ ,...n ] ) ] [ ; ] <object> ::= { [ server_name . database_name . schema_name . | database_name .[ schema_name ] . | schema_name . ] table_or_view_name} Arguments:
WITH <common_table_expression> :
Specifies the temporary named result set or view, also known as common table expression (CTE), defined within the scope of the UPDATE statement. The CTE result set is derived from a simple query and is referenced by UPDATE statement. Common table expressions can also be used with the SELECT, INSERT, DELETE, and CREATE VIEW statements.
TOP ( expression ) [ PERCENT ] :
Specifies the number or percent of rows that will be updated. expression can be either a number or a percent of the rows. The rows referenced in the TOP expression used with INSERT, UPDATE, or DELETE are not arranged in any order. Parentheses delimiting expression in TOP are required in INSERT, UPDATE, and DELETE statements. server_name: Is the name of the server (using a linked server name or the OPENDATASOURCE function as the server name) on which the table or view is located. If server_name is specified, database_name and schema_name are required. database_name : Is the name of the database. schema_name: Is the name of the schema to which the table or view belongs.
table_or view_name:
Is the name of the table or view from which the rows are to be updated. A table variable, within its scope, can be used as a table source in an UPDATE statement. The view referenced by table_or_view_name must be updatable and reference exactly one base table in the FROM clause of the view. rowset_function_limited : Is either the OPENQUERY or OPENROWSET function, subject to provider capabilities. For more information about capabilities needed by the provider, see UPDATE and DELETE Requirements for OLE DB Providers.
Page 51 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
WITH ( <Table_Hint_Limited> ) : Specifies one or more table hints that are allowed for a target table. The WITH keyword and the parentheses are required. NOLOCK and READUNCOMMITTED are not allowed SET: Specifies the list of column or variable names to be updated. column_name: Is a column that contains the data to be changed. column_name must exist in table_or view_name. Identity columns cannot be updated. expression: Is a variable, literal value, expression, or a subselect statement (enclosed with parentheses) that returns a single value. The value returned by expression replaces the existing value in column_name or @variable. DEFAULT: Specifies that the default value defined for the column is to replace the existing value in the column. This can also be used to change the column to NULL if the column has no default and is defined to allow null values. <OUTPUT_Clause> : Returns updated data or expressions based on it as part of the UPDATE operation. The OUTPUT clause is not supported in any DML statements that target remote tables or views. FROM <table_source> : Specifies that a table, view, or derived table source is used to provide the criteria for the update operation. If the object being updated is the same as the object in the FROM clause and there is only one reference to the object in the FROM clause, an object alias may or may not be specified. If the object being updated appears more than one time in the FROM clause, one, and only one, reference to the object must not specify a table alias. All other references to the object in the FROM clause must include an object alias. A view with an INSTEAD OF UPDATE trigger cannot be a target of an UPDATE with a FROM clause. WHERE: Specifies the conditions that limit the rows that are updated. There are two forms of update based on which form of the WHERE clause is used: Searched updates specify a search condition to qualify the rows to delete. Positioned updates use the CURRENT OF clause to specify a cursor. The update operation occurs at the current position of the cursor. <search_condition> : Specifies the condition to be met for the rows to be updated. The search condition can also be the condition upon which a join is based. There is no limit to the number of predicates that can be included in a search condition.
Page 52 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
Examples: Using a simple UPDATE statement The following examples show how all rows can be affected when a WHERE clause is not used to specify the row or rows to update. This example updates the values in the Bonus, CommissionPct, and SalesQuota columns for all rows in the SalesPerson table. USE AdventureWorks; GO UPDATE Sales.SalesPerson SET Bonus = 6000, CommissionPct = .10, SalesQuota = NULL; GO You can also use computed values in an UPDATE statement. The following example doubles the value in the ListPrice column for all rows in the Product table. USE AdventureWorks ; GO UPDATE Production.Product SET ListPrice = ListPrice * 2; GO Using the UPDATE statement with a WHERE clause The following example uses the WHERE clause to specify which rows to update. For example, Adventure Works Cycles sells their bicycle model Road-250 in two colors: red and black. The company has decided to change the color of red for this model to metallic red. The following statement updates the rows in the Production.Product table for all red Road-250 products. USE AdventureWorks; GO UPDATE Production.Product SET Color = N'Metallic Red' WHERE Name LIKE N'Road-250%' AND Color = N'Red'; GO Using the UPDATE statement with information from another table The following example modifies the SalesYTD column in the SalesPerson table to reflect the most recent sales recorded in the SalesOrderHeader table. USE AdventureWorks; GO UPDATE Sales.SalesPerson SET SalesYTD = SalesYTD + SubTotal FROM Sales.SalesPerson AS sp JOIN Sales.SalesOrderHeader AS so ON sp.SalesPersonID = so.SalesPersonID
Page 53 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
25 .OrderDate = (SELECT MAX(OrderDate) FROM Sales. The example runs without error.SalesOrderHeader AS so2 WHERE so2.SalesPersonID). GO The previous example assumes that only one sale is recorded for a specified salesperson on a specific date and that updates are current. If more than one sale for a specified salesperson can be recorded on the same day.OrderDate = (SELECT MAX(OrderDate) FROM Sales. GO Using UPDATE with the TOP clause The following example updates the VacationHours column by 25 percent for 10 random rows in the Employee table. All Rights Reserved C3: Protected .SQL Server 2005 AND so. GO UPDATE TOP (10) HumanResources. In the situation in which more than one sale for a specified salesperson can occur on the same day. but each SalesYTD value is updated with only one sale. as shown in this example: USE AdventureWorks.SalesPersonID).SalesPersonID GROUP BY so.SalesOrderHeader WHERE SalesPersonID = sp. regardless of how many sales actually occurred on that day.SalesPersonID = so. GO UPDATE Sales.SalesPersonID) AND Sales.Handout . all the sales for each sales person must be aggregated together within the UPDATE statement.SalesPerson.Employee SET VacationHours = VacationHours * 1.SalesPerson SET SalesYTD = SalesYTD + (SELECT SUM(so. This is because a single UPDATE statement never updates the same row two times.SubTotal) FROM Sales.SalesPersonID = so. Cognizant Technology Solutions. USE AdventureWorks. GO Page 54 ©Copyright 2007.SalesOrderHeader AS so WHERE so. the example shown does not work correctly.
Common table expressions can also be used with the SELECT. | database_name.. ] <object> ::= { [ server_name.n ] ] DELETE [ TOP ( expression ) [ PERCENT ] ] [ FROM ] { <object> | rowset_function_limited [ WITH ( <table_hint_limited> [ .. also known as common table expression..n ] ] [ WHERE { <search_condition> | { [ CURRENT OF { { [ GLOBAL ] cursor_name } | cursor_variable_name } ] } } ] [ OPTION ( <Query Hint> [ .. INSERT. ] table_or_view_name } Arguments WITH <common_table_expression> : Specifies the temporary named result set. defined within the scope of the DELETE statement.. The result set is derived from a SELECT statement.schema_name.. | schema_name. Cognizant Technology Solutions. All Rights Reserved C3: Protected . and CREATE VIEW statements.n ] ) ] } [ <OUTPUT Clause> ] [ FROM <table_source> [ .n ] ) ] [.Handout .database_name. UPDATE... Syntax [ WITH <common_table_expression> [ . Page 55 ©Copyright 2007.. [ schema_name ] .SQL Server 2005 DELETE statement Removes rows from a table or view...
or expressions based on them. UPDATE.Handout . subject to provider capabilities. FROM: Is an optional keyword that can be used between the DELETE keyword and the target table_or_view_name. All Rights Reserved C3: Protected . within its scope. FROM <table_source>: Specifies an additional FROM clause. For more information about the capabilities needed by the provider. n] ): Specifies one or more table hints that are allowed for a target table. server_name : Is the name of the server (using a linked server name or the OPENDATASOURCE (Transact-SQL) function as the server name) on which the table or view is located.. as part of the DELETE operation. also can be used as a table source in a DELETE statement.. specifying a join. WITH ( <table_hint_limited> [. The view referenced by table_or_view_name must be updatable and reference exactly one base table in the FROM clause of the view. see UPDATE and DELETE Requirements for OLE DB Providers. For more information about updatable views. or DELETE are not arranged in any order. can be used instead of a subquery in the WHERE clause to identify rows to be removed. expression can be either a number or a percent of the rows. Cognizant Technology Solutions. The rows referenced in the TOP expression used with INSERT. database_name and schema_name are required. database_name: Is the name of the database. NOLOCK and READUNCOMMITTED are not allowed. or rowset_function_limited. and DELETE statements. Parentheses delimiting expression in TOP are required in INSERT. rowset_function_limited: Is either the OPENQUERY (Transact-SQL) or OPENROWSET (Transact-SQL) function. The WITH keyword and the parentheses are required. If server_name is specified. This extension. <OUTPUT_Clause> : Returns deleted rows. This Transact-SQL extension to DELETE allows specifying data from <table_source> and deleting the corresponding rows from the table in the first FROM clause. schema_name: Is the name of the schema to which the table or view belongs table_or view_name Is the name of the table or view from which the rows are to be removed. For more information. The OUTPUT clause is not supported in any DML statements targeting views or remote tables. UPDATE.SQL Server 2005 TOP ( expression ) [ PERCENT ] : Specifies the number or percent of random rows that will be deleted. Page 56 ©Copyright 2007. A table variable.
This can be more accurate than a searched DELETE statement that uses a WHERE search_condition clause to qualify the rows to be deleted. DELETE removes all the rows from the table.. A searched DELETE statement deletes multiple rows if the search condition does not uniquely identify a single row. CURRENT OF: Specifies that the DELETE is performed at the current position of the specified cursor. If a WHERE clause is not supplied. If both a global and a local cursor with the name cursor_name exist. All Rights Reserved C3: Protected . For example. WHERE column_name = value. it refers to the local cursor. There is no limit to the number of predicates that can be included in a search condition. o Positioned deletes use the CURRENT OF clause to specify a cursor. GO Page 57 ©Copyright 2007. GO DELETE FROM Sales.SQL Server 2005 WHERE: Specifies the conditions used to limit the number of rows that are deleted.SalesPersonQuotaHistory. The delete operation occurs at the current position of the cursor. otherwise. this argument refers to the global cursor if GLOBAL is specified.Handout . n] ) : Are keywords that indicate that optimizer hints are used to customize the way the Database Engine processes the statement. <search_condition>: Specifies the restricting conditions for the rows to be deleted. Examples Using DELETE with no WHERE clause The following example deletes all rows from the SalesPersonQuotaHistory table because a WHERE clause is not used to limit the number of rows deleted. The cursor must allow updates.. There are two forms of delete operations based on what is specified in the WHERE clause: o Searched deletes specify a search condition to qualify the rows to delete. cursor_name : Is the name of the open cursor from which the fetch is made. Cognizant Technology Solutions. GLOBAL: Specifies that cursor_name refers to a global cursor. cursor_variable_name : Is the name of a cursor variable. USE AdventureWorks.. OPTION ( <query_hint> [ . The cursor variable must reference a cursor that allows updates.
EmployeeID) . Cognizant Technology Solutions.SalesPerson Page 58 ©Copyright 2007.SQL-2003 Standard subquery USE AdventureWorks. The first DELETE statement shows the SQL2003-compatible subquery solution. and the second DELETE statement shows the Transact-SQL extension. GO DELETE FROM Production. DELETE FROM HumanResources. GO DELETE FROM Sales. OPEN complex_cursor. The delete operation affects only the single row currently fetched from the cursor. CLOSE complex_cursor.EmployeePayHistory WHERE CURRENT OF complex_cursor.SQL Server 2005 Using DELETE on a set of rows The following example deletes all rows from the ProductCostHistory table in which the value in the StandardCost column is more than 1000. USE AdventureWorks.EmployeePayHistory AS b WHERE a. GO Using DELETE based on a subquery and using the Transact-SQL extension The following example shows the Transact-SQL extension used to delete records from a base table that is based on a join or correlated subquery. All Rights Reserved C3: Protected . GO DECLARE complex_cursor CURSOR FOR SELECT a. USE AdventureWorks. -.SalesPersonQuotaHistory WHERE SalesPersonID IN (SELECT SalesPersonID FROM Sales.00. DEALLOCATE complex_cursor.EmployeeID FROM HumanResources.ProductCostHistory WHERE StandardCost > 1000.EmployeePayHistory AS a WHERE RateChangeDate <> (SELECT MAX(RateChangeDate) FROM HumanResources. FETCH FROM complex_cursor.EmployeeID = b.Handout . GO Using DELETE on the current row of a cursor The following example deletes a single row from the EmployeePayHistory table using a cursor named complex_cursor. Both queries remove rows from the SalesPersonQuotaHistory table based on the yearto-date sales stored in the SalesPerson table.00.
| schema_name . GO -.SalesPersonQuotaHistory AS spqh INNER JOIN Sales.SQL Server 2005 WHERE SalesYTD > 2500000. ] Arguments database_name: Is the name of the database schema_name: Is the name of the schema to which the table belongs.SalesPersonQuotaHistory FROM Sales. TRUNCATE TABLE is faster and uses fewer system and transaction log resources. GO TRUNCATE TABLE statement Removes all rows from a table without logging the individual row deletions. TRUNCATE TABLE is functionally the same as the DELETE statement with no WHERE clause. Examples The following example removes all data from the JobCandidate table. GO DELETE TOP (2. however. USE AdventureWorks.SalesPersonID = sp. Cognizant Technology Solutions. SELECT statements are included before and after the TRUNCATE TABLE statement to compare results. table_name: Is the name of the table to truncate or from which all rows are removed. All Rights Reserved C3: Protected .00). GO DELETE FROM Sales. } ] table_name [ . USE AdventureWorks. GO SELECT COUNT(*) AS BeforeTruncateCount Page 59 ©Copyright 2007. GO Using DELETE with the TOP clause The following example deletes 2.SalesPerson AS sp ON spqh.SalesYTD > 2500000. Syntax TRUNCATE TABLE [ { database_name.00.5) PERCENT FROM Production.SalesPersonID WHERE sp.Transact-SQL extension USE AdventureWorks.5 percent of the rows (27 rows) in the ProductInventory table.[ schema_name ].ProductInventory.Handout .
GO TRUNCATE TABLE HumanResources..JobCandidate. [ schema_name ] . Cognizant Technology Solutions....JobCandidate.. Syntax CREATE TABLE [ database_name . All Rights Reserved C3: Protected . | schema_name . . ] table_name ( { <column_definition> | <computed_column_definition> } [ <table_constraint> ] [ .n ] ) ] [ ON { partition_scheme_name (partition_column_name) | CHECK Page 60 ©Copyright 2007. GO SELECT COUNT(*) AS AfterTruncateCount FROM HumanResources.SQL Server 2005 FROM HumanResources..n ] ) [ WITH FILLFACTOR = fillfactor |WITH ( <index_option> [ .JobCandidate.Handout ... GO CREATE TABLE statement Creates a new table.n ] ) [ ON { partition_scheme_name ( partition_column_name ) | filegroup | "default" } ] [ PERSISTED [ NOT NULL ] ] [ [ CONSTRAINT constraint_name ] { PRIMARY KEY | UNIQUE } [ CLUSTERED | NONCLUSTERED ] | [ FOREIGN KEY ] REFERENCES referenced_table_name [ ( ref_column ) ] [ NOT FOR REPLICATION ] ( logical_expression ) [ ON { partition_scheme_name ( partition_column_name ) | filegroup | "default" } ] ] < table_constraint > ::= [ CONSTRAINT constraint_name ] { { PRIMARY KEY | UNIQUE } [ CLUSTERED | NONCLUSTERED ] (column [ ASC | DESC ] [ .
and any combination of these connected by one or more operators. but not precise. For example. column_name can be of 1 through 128 characters. and that user ID must have CREATE TABLE permissions. The expression can be a noncomputed column name. column_name: Is the name of a column in the table. schema_name: Is the name of the schema to which the new table belongs. o PERSISTED: Specifies that the SQL Server Database Engine will physically store the computed values in the table. For more information. Cognizant Technology Solutions. function. Column names must follow the rules for identifiers and must be unique in the table. A computed column is a virtual column that is not physically stored in the table. if the computed column value is defined by a deterministic expression and the data type of the result is allowed in index columns. WHERE clauses. ORDER BY clauses.n ] ) REFERENCES referenced_table_name [ ( ref_column [ .. Table names must follow the rules for identifiers. All Rights Reserved C3: Protected . see Creating Indexes on Computed Columns. Any computed columns that are used as partitioning columns of a Page 61 ©Copyright 2007. Computed columns can be used in select lists. column_name can be omitted for columns that are created with a timestamp data type. variable.n ] ) ] | CHECK [ NOT FOR REPLICATION ] ( logical_expression ) } Arguments database_name: Is the name of the database in which the table is created. If column_name is not specified... or any other locations in which regular expressions can be used. constant. The expression cannot be a subquery or contain alias data types. The column is computed from an expression that uses other columns in the same table. with the following exceptions: o A computed column cannot be used as a DEFAULT or FOREIGN KEY constraint definition or with a NOT NULL constraint definition. database_name must specify the name of an existing database. A computed column cannot be the target of an INSERT or UPDATE statement. table_name can be a maximum of 128 characters. Marking a computed column as PERSISTED lets you create an index on a computed column that is deterministic.. However. unless the column is marked PERSISTED.Handout . The login for the current connection must be associated with an existing user ID in the database specified by database_name. a computed column can have the definition: cost AS price * qty. database_name defaults to the current database . If not specified... and update the values when any other columns on which the computed column depends are updated. table_name: Is the name of the new table. except for local temporary table names (names prefixed with a single number sign (#)) that cannot exceed 116 characters. the name of a timestamp column defaults to timestamp. computed_column_expression: Is an expression that defines the value of a computed column.SQL Server 2005 | filegroup | "default" } ] | FOREIGN KEY ( column [ . a computed column can be used as a key column in an index or as part of any PRIMARY KEY or UNIQUE constraint.
ON { <partition_scheme> | filegroup | "default" }: Specifies the partition scheme or filegroup on which the table is stored. [ReceivedQty] [float] NULL. If "default" is specified. computed_column_expression must be deterministic when PERSISTED is specified. Cognizant Technology Solutions. or if ON is not specified at all. the table is stored in the named filegroup. [ModifiedDate] [datetime] NOT NULL CONSTRAINT [DF_PurchaseOrderDetail_ModifiedDate] DEFAULT (getdate()).Product(ProductID). [LineNumber] [smallint] NOT NULL. If <partition_scheme> is specified. [UnitPrice] [money] NULL. the index is stored in the named filegroup. and the other will be ignored. If filegroup is specified. [ProductID] [int] NULL REFERENCES Production. If the PRIMARY KEY or UNIQUE constraint creates a clustered index. [DueDate] [datetime] NULL. All Rights Reserved C3: Protected . only the constraint definition will be honored. the data pages for the table are stored in the same filegroup as the index. CREATE TABLE [dbo]. ON {<partition_scheme> | filegroup | "default"} can also be specified in a PRIMARY KEY or UNIQUE constraint. These constraints create indexes. If "default" is specified. [LineNumber]) Page 62 ©Copyright 2007. Example Showing the complete table definition The following example shows the complete table definitions with all constraint definitions for table PurchaseOrderDetail created in the AdventureWorks database.SQL Server 2005 partitioned table must be explicitly marked PERSISTED.[PurchaseOrderDetail] ( [PurchaseOrderID] [int] NOT NULL REFERENCES Purchasing. the index is stored in the same filegroup as the table. [OrderQty] [smallint] NULL.PurchaseOrderHeader(PurchaseOrderID). the table is to be a partitioned table whose partitions are stored on a set of one or more filegroups specified in <partition_scheme>. [StockedQty] AS (([ReceivedQty]-[RejectedQty])). [LineTotal] AS (([UnitPrice]*[OrderQty])).Handout . The filegroup must exist within the database. CONSTRAINT [PK_PurchaseOrderDetail_PurchaseOrderID_LineNumber] PRIMARY KEY CLUSTERED ([PurchaseOrderID]. [RejectedQty] [float] NULL. [rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL CONSTRAINT [DF_PurchaseOrderDetail_rowguid] DEFAULT (newid()). and a <partition_scheme> is specified that differs from the <partition_scheme> or filegroup of the table definition. The storage mechanism of a table as specified in CREATE TABLE cannot be subsequently altered. If CLUSTERED is specified or the constraint otherwise creates a clustered index. the table is stored on the default filegroup. If filegroup is specified. or vice-versa. or if ON is not specified at all.
Perform trigonometric. deterministic. and MAX. decryption. Examples are COUNT. All Rights Reserved C3: Protected . Return information about the status of a cursor. The following table lists the categories for the SQL Server functions. Scalar functions that return information about configuration settings. binary. for a specific set of input values and database state. Change text and image values. and varbinary values. Deterministic and Nondeterministic Functions In SQL Server 2005. Operate on or report on various system level options and objects. and other numeric operations. Support encryption. Return information about users and roles. geometric. For user-defined functions. and the validation of digital signatures. A user-defined function is deterministic if.SQL Server 2005 WITH (IGNORE_DUP_KEY = OFF) ) ON [PRIMARY] Functions SQL Server 2005 provides built-in functions that can be used to perform certain operations. If the function is not strictly deterministic. functions are classified as strictly deterministic. A function is strictly deterministic if. Page 63 ©Copyright 2007. MIN. Return the rowsets that can be used in the place of a table reference in a Transact-SQL statement. Cognizant Technology Solutions. Nondeterministic functions that return a ranking value for each row in a partition. a less rigid notion of determinism is applied. the function always returns the same results. the function always returns the same results. nchar.Handout . for a specific set of input values. varchar. it can be deterministic in this sense if it is data-accessing. Change date and time values. or nondeterministic. SUM. digital signing. nvarchar. Return information about the performance of SQL Server. Return information about the attributes of databases and database objects. Function category Aggregate Functions (Transact-SQL) Configuration functions Cryptographic Functions (Transact-SQL) Cursor functions Date and Time functions Mathematical functions Metadata functions Ranking functions Rowset Functions (TransactSQL) Security functions String functions System functions System Statistical Functions (Transact-SQL) Text and image functions Description Perform operations that combine multiple values into one. Change char.
USE AdventureWorks. MIN SUM STDEV STDEVP VAR VARP Page 64 ©Copyright 2007. Therefore. A COMPUTE or COMPUTE BY clause. Transact-SQL provides the following aggregate functions: AVG CHECKSUM CHECKSUM_AGG COUNT COUNT_BIG GROUPING MAX Example: Using the SUM and AVG functions for calculations The following example calculates the average vacation hours and the sum of sick leave hours that the vice presidents of Adventure Works Cycles have used. Each of these aggregate functions produces a single summary value for all the retrieved rows. Aggregate functions are frequently used with the GROUP BY clause of the SELECT statement.Employee WHERE Title LIKE 'Vice President%'. SQL Server puts restrictions on various classes of nondeterminism. A HAVING clause. Aggregate functions can be used as expressions only in the following: The select list of a SELECT statement (either a subquery or an outer query). All Rights Reserved C3: Protected . Aggregate Functions Aggregate functions perform a calculation on a set of values and return a single value. For more information about function determinism. see Deterministic and Nondeterministic Functions.Handout . GO SELECT AVG(VacationHours)as 'Average vacation hours'. Cognizant Technology Solutions. This means aggregate functions return the same value any time they are called by using a specific set of input values. For example. nondeterministic functions should be used carefully.SQL Server 2005 A nondeterministic function may return different results when it is called repeatedly with the same set of input values. the function GETDATE() is nondeterministic. All aggregate functions are deterministic. Except for COUNT. aggregate functions ignore null values. SUM (SickLeaveHours) as 'Total sick leave hours' FROM HumanResources.
The Transact-SQL date and time functions and their determinism property are listed in the following table. number. startdate . DATENAME ( datepart . Function DATEADD DATEDIFF DATENAME Determinism Deterministic Deterministic Nondeterministic Deterministic except when used as DATEPART (dw.Handout .date ) : Returns a character string representing the specified datepart of the specified date. the weekday datepart. All Rights Reserved C3: Protected . date ) : Returns a new datetime value based on adding an interval to the specified date. date ) : Returns an integer that represents the specified datepart of the specified date. depends on the value set by SET DATEFIRST. DAY ( date ) : Returns an integer representing the day GETDATE ( ) : Returns the current system date and time Arguments datepart: Is the parameter that specifies on which part of the date to return a new value. yyyy qq. DATEDIFF ( datepart . Datepart year quarter Abbreviations yy. Cognizant Technology Solutions. q Page 65 ©Copyright 2007. enddate ) : Returns the number of date and time boundaries crossed between two specified dates. date). which sets the first day of the week. The following table lists the dateparts and abbreviations recognized by Microsoft SQL Server 2005. DATEPART ( datepart .SQL Server 2005 Date and Time Functions The following scalar functions perform an operation on a date and time input value and return a string. dw. Deterministic Nondeterministic DATEPART DAY GETDATE GETUTCDATE Nondeterministic MONTH YEAR Deterministic Deterministic Syntax DATEADD (datepart . numeric. or date and time value.
d wk. OrderDate. y dd.SQL Server 2005 Datepart month dayofyear day week weekday hour minute second millisecond Abbreviations mm. GO The following example determines the difference in days between the current date and the order date for products in the AdventureWorks database. GETDATE()) AS NumberOfDays FROM Sales. USE AdventureWorks. All Rights Reserved C3: Protected . m dy. For example. If you specify a value that is not an integer. or a character string in a date format.SalesOrderHeader. date: Is an expression that returns a datetime or smalldatetime value. Values greater than the last two digits of the value of this option are in the century that comes before the cutoff year. ww dw. GO SELECT DATEADD(day. n ss. values less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year.75 for number. OrderDate)AS TimeFrame FROM Sales. 49 is interpreted as 2049 and 2050 is interpreted as 1950. s ms number: Is the value used to increment datepart. Page 66 ©Copyright 2007. date is incremented by 1. GO SELECT DATEDIFF(day. This time frame represents the existing order date plus 21 days. Cognizant Technology Solutions.SalesOrderHeader. the fractional part of the value is discarded. use four-digit years. To avoid ambiguity. w hh mi. For example. 21.Handout . USE AdventureWorks. if twodigit year cutoff is 2049 (default). Examples The following example prints a listing of a time frame for orders in the AdventureWorks database. if you specify day for datepart and1. If you specify only the last two digits of the year.
GO SELECT LastName.' SELECT 'Here is the string without the leading spaces: ' + LTRIM(@string_to_trim) GO Using LEFT with a column Page 67 ©Copyright 2007. Cognizant Technology Solutions. SELECT REPLACE('abcdefghicde'. DECLARE @string_to_trim varchar(60) SET @string_to_trim = ' Five spaces are at the beginning of this string. This means they return the same value any time they are called with a specific set of input values. 1) AS Initial FROM Person.'cde'.'xxx').Contact WHERE LastName like 'Barl%' ORDER BY LastName The following example replaces the string cde in abcdefghi with xxx. All Rights Reserved C3: Protected .SQL Server 2005 GO String Functions The following scalar functions perform an operation on a string input value and return a string or numeric value: ASCII CHAR CHARINDEX DIFFERENCE LEFT LEN LOWER LTRIM NCHAR PATINDEX QUOTENAME REPLACE REPLICATE REVERSE RIGHT RTRIM SOUNDEX SPACE STR STUFF SUBSTRING UNICODE UPPER All built-in string functions are deterministic.Handout . From the Contact table. this query returns the last name in one column with only the first initial in the second column. 1. USE AdventureWorks. GO The following example uses LTRIM to remove leading spaces from a character variable. Examples Using SUBSTRING with a character string The following example shows how to return only a part of a character string. SUBSTRING(FirstName.
ROW_NUMBER() OVER (ORDER BY SalesOrderID) AS RunningCount FROM Sales. USE AdventureWorks. or CREATE VIEW statement. CTE provides the significant advantage of being able to reference itself. CustomerID.SQL Server 2005 The following example returns the five leftmost characters of each product name. Page 68 ©Copyright 2007. CustomerID.SalesOrderHeader WHERE SalesOrderID>10000 Common Table Expressions A Common Table Expression (CTE) closely resembles a nonpersistent view. GO Ranking Functions RANK() Function: Returns the rank of each row within the partition of a result set The rank of a row is one plus the number of ranks that come before the row in question Example The following simple example gives a row number to each row in the result set. Simplify the code required to run a recursive query within a SELECT. A recursive CTE is one in which an initial CTE is repeatedly executed to return subsets of data until the complete result set is obtained.Handout .Product ORDER BY ProductID. Cognizant Technology Solutions. RANK() OVER (ORDER BY CustomerID) AS RunningCount FROM Sales. INSERT. 5) FROM Production. DELETE. GO SELECT LEFT(Name. starting at one for the first row in each partition Example USE AdventureWorks GO SELECT SalesOrderID.SalesOrderHeader WHERE SalesOrderID > 10000 ROW_NUMBER() Function: Returns the sequential number of a row within a partition of a result set. UPDATE. thereby creating a recursive CTE. All Rights Reserved C3: Protected . ordering by SalesOrderID: USE AdventureWorks GO SELECT SalesOrderID.
Handout . COUNT(*) FROM HumanResources. INSERT.Employee AS e WHERE ManagerID IS NOT NULL GROUP BY ManagerID ) SELECT ManagerID. DirectReports FROM DirReps ORDER BY ManagerID. /*Example shows the number of employees reporting directly to each manager at Adventure Works Cycles. */ USE AdventureWorks. TRUNCATE TABLE statement removes all rows from a table without logging the individual row deletions A Common Table Expression (CTE) closely resembles a nonpersistent view. All Rights Reserved C3: Protected . or inside another subquery. or DELETE statement. cursors. which usually requires applying temporary tables. and logic to control the flow of the recursive steps in earlier version of SQL Server. Cognizant Technology Solutions.SQL Server 2005 CTE reduces the complexity of applying recursive query. DirectReports) AS ( SELECT ManagerID. Page 69 ©Copyright 2007. GROUP BY calculates a summary value for each group ORDER BY specifies the sort order used on columns returned in a SELECT statement A subquery is a query that is nested inside a SELECT. GO Summary Transact SQL (T-SQL) is a powerful and unique superset of the SQL standard. GO WITH DirReps(ManagerID. UPDATE.
mdf. Database Files SQL Server 2005 databases have three types of files: Primary data files: The primary data file is the starting point of the database and points to the other files in the database.ndf. and . There must be at least one log file for each database. Cognizant Technology Solutions. Page 70 ©Copyright 2007. Log files: Log files hold all the log information that is used to recover the database.ndf. Filegroups are named collections of files and are used to help with data placement and administrative tasks such as backup and restore operations.0 to SQL Server 2005. The Database Engine uses the file location information from the master database most of the time. When restoring the master database.ldf.mdf. . Some databases may not have any secondary data files. although there can be more than one. SQL Server 2005 does not enforce the . The recommended file name extension for secondary data files is . other than the primary data file.Handout . However. The recommended file name extension for log files is .ldf file name extensions. The recommended file name extension for primary data files is . while others have several secondary data files. Data and log information are never mixed in the same file. the database engine uses the file location information from the primary file to initialize the file location entries in the master database in the following situations: When attaching a database using the CREATE DATABASE statement with either the FOR ATTACH or FOR ATTACH_REBUILD_LOG options. you will be able to: Identify the types of Database Files Explain the Database Filegroups Describe different ways of Creating Databases Overview SQL Server 2005 maps a database over a set of operating-system files. Every database has one primary data file. When upgrading from SQL Server version 2000 or version 7. All Rights Reserved C3: Protected .SQL Server 2005 Session 15: Database and Data files Learning Objectives After completing this session. Secondary data files: Secondary data files make up all the data files. and individual files are used only by one database. but these extensions help you identify the different kinds of files and their use. In SQL Server 2005. the locations of all the files in a database are recorded in the primary file of the database and in the master database.
NTFS is recommended for the security aspects of NTFS. both the file ID and the page number are required. starting with zero (0) for the first page in the file. Read/write data filegroups and log files cannot be placed on an NTFS compressed file system. All Rights Reserved C3: Protected . It must follow the rules for the operating system file names. When multiple instances of SQL Server are run on a single computer. Each file in a database has a unique file ID number.Handout . Data File Pages: Pages in a SQL Server 2005 data file are numbered sequentially. The logical file name must comply with the rules for SQL Server identifiers and must be unique among logical file names in the database. To uniquely identify a page in a database. Only read-only databases and read-only secondary filegroups can be put on an NTFS compressed file system. Page 71 ©Copyright 2007.SQL Server 2005 Logical and Physical File Names SQL Server 2005 files have two names: logical_file_name: The logical_file_name is the name used to refer to the physical file in all Transact-SQL statements. The following example shows the page numbers in a database that has a 4-MB primary data file and a 1-MB secondary data file. o The following illustration shows examples of the logical file names and the physical file names of a database created on a default instance of SQL Server 2005: SQL Server data and log files can be put on either FAT or NTFS file systems. each instance receives a different default directory to hold the files for the databases created in the instance. see File Locations for Default and Named Instances of SQL Server 2005. For more information. Cognizant Technology Solutions. os_file_name: o The os_file_name is the name of the physical file including the directory path.
Database Filegroups Database objects and files can be grouped together in filegroups for allocation and administration purposes. Log space is managed separately from data space. The data of partitioned tables and indexes is divided into units each of which can be placed in a separate filegroup in a database. Log files are never part of a filegroup. the file can continue to grow until it has used all available space on the disk. The user can let the files autogrow as required to reduce the administrative burden of monitoring free space in the database and manually allocating additional space. it increases its size by the growth increment. Every time the file is filled. all their pages will be allocated in that filegroup. All pages for the system tables are allocated in the primary filegroup. There are two types of filegroups: Primary: The primary filegroup contains the primary data file and any other files not specifically assigned to another filegroup. Growth then occurs in a round-robin fashion. All Rights Reserved C3: Protected . you can specify a specific growth increment. No file can be a member of more than one filegroup. such as allocation maps. One of the system pages stored in both the primary data file and the first log file is a database boot page that contains information about the attributes of the database File Size: SQL Server 2005 files can grow automatically from their originally specified size. Several of the other pages at the start of the file also contain system information. When you define a file. Page 72 ©Copyright 2007.Handout . Cognizant Technology Solutions. User-defined: User-defined filegroups are any filegroups that are specified by using the FILEGROUP keyword in a CREATE DATABASE or ALTER DATABASE statement. or the tables and indexes can be partitioned. If there are multiple files in a filegroup. they will not autogrow until all the files are full. Tables.SQL Server 2005 The first page in each file is a file header page that contains information about the attributes of the file. indexes. This feature is especially useful when SQL Server is used as a database embedded in an application where the user does not have convenient access to a system administrator. Each file can also have a maximum size specified. and large object data can be associated with a specified filegroup. If a maximum size is not specified. In this case.
Create the database with the default data -.primary data file. An ALTER DATABASE statement makes the user-defined filegroup the default. Members of the db_owner fixed database role can switch the default filegroup from one filegroup to another. FILEGROWTH=1MB). All Rights Reserved C3: Protected . SIZE = 1MB. a user-defined filegroup.ndf'. it is assumed all pages will be allocated from the default filegroup. The primary data file is in the primary filegroup and the user-defined filegroup has two secondary data files. The database has a primary data file. MAXSIZE=10MB. MAXSIZE=10MB. When a table or index is created without specifying a filegroup.SQL Server 2005 One filegroup in each database is designated the default filegroup. FILENAME = 'c:\Program Files\Microsoft SQL Server\MSSQL. MAXSIZE=10MB. ( NAME = 'MyDB_FG1_Dat2'. Only one filegroup at a time can be the default filegroup. USE master. GO -.1\MSSQL\data\MyDB_FG1_2. FILEGROWTH=1MB) LOG ON ( NAME='MyDB_log'. Cognizant Technology Solutions. File and Filegroup Example The following example creates a database on an instance of SQL Server. If no default filegroup is specified. FILEGROWTH=1MB).1\MSSQL\data\MyDB_FG1_1. FILENAME = 'c:\Program Files\Microsoft SQL Server\MSSQL.growth increment and the max size for the -. and a log file. CREATE DATABASE MyDB ON PRIMARY ( NAME='MyDB_Primary'. SIZE=4MB. FILENAME= 'c:\Program Files\Microsoft SQL Server\MSSQL.mdf'. FILENAME = Page 73 ©Copyright 2007. Specify the -.filegroup and a log file. A table is then created specifying the userdefined filegroup. SIZE = 1MB. FILEGROUP MyDB_FG1 ( NAME = 'MyDB_FG1_Dat1'.ndf'.1\MSSQL\data\MyDB_Prm.Handout . the primary filegroup is the default filegroup.
ldf'. <filegroup> [ . CREATE TABLE MyTable ( cola int PRIMARY KEY.SQL Server 2005 'c:\Program Files\Microsoft SQL Server\MSSQL.Create a table in the user-defined filegroup. CREATE DATABASE (T-SQL Statement) Creates a new database and the files used to store the database. MAXSIZE=10MB. USE MyDB... GO -.... All Rights Reserved C3: Protected . GO The following illustration summarizes the results of the previous example.Handout .n ] [ . SIZE=1MB. FILEGROWTH=1MB). Cognizant Technology Solutions. Syntax CREATE DATABASE database_name [ ON [ PRIMARY ] [ <filespec> [ .n ] ] [ LOG ON { <filespec> [ .. GO ALTER DATABASE MyDB MODIFY FILEGROUP MyDB_FG1 DEFAULT.1\MSSQL\data\MyDB... or attaches a database from the detached files of a previously created database..n ] FOR { ATTACH [ WITH <service_broker_option> ] | ATTACH_REBUILD_LOG } [.. colb char(8) ) ON MyDB_FG1.] <filespec> ::= { Page 74 ©Copyright 2007.n ] } ] ] [ COLLATE collation_name ] [ WITH <external_access_option> ] ] [..] To attach a database CREATE DATABASE database_name ON <filespec> [ . creates a database snapshot..
FILENAME = 'os_file_name' [ . SIZE = size [ KB | MB | GB | TB ] ] [ .. Database names must be unique within an instance of SQL Server and comply with the rules for identifiers.n ] } <filegroup> ::= { FILEGROUP filegroup_name [ DEFAULT ] <filespec> [ ...n ] AS SNAPSHOT OF source_database_name [.. database_name can be a maximum of 128 characters. All Rights Reserved C3: Protected ...Handout . FILEGROWTH = growth_increment [ KB | MB | GB | TB | % ] ] ) [ ...] Arguments database_name Is the name of the new database. If a logical log file name is not specified.SQL Server 2005 ( NAME = logical_file_name . SQL Server generates the logical_file_name and the os_file_name for the log by appending a Page 75 ©Copyright 2007.n ] } <external_access_option> ::= { DB_CHAINING { ON | OFF } | TRUSTWORTHY { ON | OFF } } <service_broker_option> ::= { ENABLE_BROKER | NEW_BROKER | ERROR_BROKER_CONVERSATIONS } Create a database snapshot CREATE DATABASE database_snapshot_name ON ( NAME = logical_file_name. Cognizant Technology Solutions. FILENAME = 'os_file_name' ) [ .. MAXSIZE = { max_size [ KB | MB | GB | TB ] | UNLIMITED } ] [ . unless a logical name is not specified for the log file.
comma-separated list of <filegroup> items that define user filegroups and their files. FOR ATTACH requires the following: All data files (MDF and NDF) must be available. PRIMARY: Specifies that the associated <filespec> list defines the primary file. A database can have only one primary file. FOR ATTACH automatically rebuilds the log file and updates the primary file. For more information. the first file listed in the CREATE DATABASE statement becomes the primary file. If a read/write database has a single log file that is currently unavailable. for a read-only database. whichever is larger. ON is required when followed by a comma-separated list of <filespec> items that define the data files for the primary filegroup. If not specified. All Rights Reserved C3: Protected . A <filespec> entry must be specified for these files. If PRIMARY is not specified.SQL Server 2005 suffix to database_name. The list of files in the primary filegroup can be followed by an optional. Collation name can be either a Windows collation name or a SQL collation name. Therefore. ON: Specifies that the disk files used to store the data sections of the database. log files. you must provide the log files or files in the FOR ATTACH clause. A collation name cannot be specified on a database snapshot. If data file name is not specified. the log cannot be rebuilt because the primary file cannot be updated. If LOG ON is not specified. the database is assigned the default collation of the instance of SQL Server. A collation name cannot be specified with the FOR ATTACH or FOR ATTACH_REBUILD_LOG clauses. Cognizant Technology Solutions. data files. are explicitly defined. are explicitly defined.Handout . when you attach a read-only database whose log is unavailable. In contrast. one log file is automatically created that has a size that is 25 percent of the sum of the sizes of all the data files for the database or 512 KB. Page 76 ©Copyright 2007. they must all be available. and if the database was shut down with no users or open transactions before the attach operation. see Physical Database Files and Filegroups. LOG ON: Specifies that the disk files used to store the database log. LOG ON cannot be specified on a database snapshot. FOR ATTACH: Specifies that the database is created by attaching an existing set of operating system files. The only other <filespec> entries required are those for any files that have a different path from when the database was first created or last attached. This limits database_name to 123 characters so that the generated logical file name is no more than 128 characters. LOG ON is followed by a comma-separated list of <filespec> items that define the log files. The first file specified in the <filespec> entry in the primary filegroup becomes the primary file.. There must be a <filespec> entry that specifies the primary file. COLLATE collation_name: Specifies the default collation for the database. If multiple log files exist. SQL Server uses database_name as both the logical_file_name and as the os_file_name.
SQL Server 2005 In SQL Server 2005. size: Is the initial size of the file. To specify a new path of the full-text catalog. For more information. NAME is required when FILENAME is specified. or the database is read-only. Page 77 ©Copyright 2007. Cognizant Technology Solutions. logical_file_name: Is the logical name used in SQL Server when referencing the file. os_file_name must specify only the drive letter of an existing raw partition.Handout . MAXSIZE. FILENAME ' os_file_name ': Specifies the operating system (physical) file name. or terabyte (TB) suffixes can be used. the Database Engine makes the file 1 MB. the Database Engine uses the size of the primary file in the model database. SIZE. The specified path must exist before executing the CREATE DATABASE statement. megabyte (MB). The file must reside on one of the following devices: the local server on which SQL Server is installed. The size specified for the primary file must be at least as large as the primary file of the model database. see Read-Only Filegroups. When size is not supplied for the primary file. gigabyte (GB). SIZE cannot be specified when the os_file_name is specified as a UNC path. For more information. ' os_file_name ': Is the path and file name used by the operating system when you create the file. and FILEGROWTH parameters cannot be set when a UNC path is specified for the file. see "Database Files and Filegroups" in the Remarks section. or an iSCSI-based network. logical_file_name must be unique in the database and comply with the rules for identifiers. a Storage Area Network [SAN]. Data files should not be put on compressed file systems unless the files are read-only secondary files. Log files should never be put on compressed file systems. The default is MB. see the Examples section. Specify a whole number. do not include a decimal. or a regular or delimited identifier. The name can be a character or Unicode constant. <filespec>: Controls the file properties NAME logical_file_name: Specifies the logical name for the file. except when specifying one of the FOR ATTACH clauses. Only one data file can be created on each raw partition. If the file is on a raw partition. All Rights Reserved C3: Protected . For more information. The kilobyte (KB). any full-text files that are part of the database that is being attached will be attached with the database. When a secondary data file or log file is specified but size is not specified for the file. SIZE size: Specifies the size of the file. FOR ATTACH cannot be specified on a database snapshot. specify the new location without the full-text operating system file name.
or a regular or delimited identifier. the growth increment size is the specified percentage of the size of the file at the time the increment occurs. the default is MB. MAXSIZE cannot be specified when the os_file_name is specified as a UNC path. When OFF. The name can be a character or Unicode constant. The default is MB. Filegroup cannot be specified on a database snapshot. KB. model. To set this option. If FILEGROWTH is not specified. The default is OFF. growth_increment: Is the amount of space added to the file every time new space is required. FILEGROUP filegroup_name: Is the logical name of the filegroup filegroup_name: filegroup_name must be unique in the database and cannot be the systemprovided names PRIMARY and PRIMARY_LOG. <filegroup> : Controls the filegroup properties. If max_size is not specified. the database cannot participate in cross-database ownership chaining. A value of 0 indicates that automatic growth is off and no additional space is allowed. the file grows until the disk is full. requires membership in the sysadmin fixed server role. do not include a decimal. tempdb. DEFAULT: Specifies the named filegroup is the default filegroup in the database. If a number is specified without an MB. and TB suffixes can be used.Handout . Page 78 ©Copyright 2007. and a data file has a maximum size of 16 TB. When % is specified.SQL Server 2005 MAXSIZE max_size: Specifies the maximum size to which the file can grow. The FILEGROWTH setting for a file cannot exceed the MAXSIZE setting. max_size: Is the maximum file size. a log file specified with unlimited growth has a maximum size of 2 TB. the database can be the source or target of a cross-database ownership chain. MB. KB. All Rights Reserved C3: Protected . The value can be specified in MB. The name must comply with the rules for identifiers. In SQL Server 2005. Specify a whole number. GB. the default value is 1 MB for data files and 10% for log files. FILEGROWTH growth_increment: Specifies the automatic growth increment of the file. or percent (%). or % suffix. Cognizant Technology Solutions. FILEGROWTH cannot be specified when the os_file_name is specified as a UNC path. The DB_CHAINING option cannot be set on these system databases: master. TB. <external_access_option>: Controls external access to and from the database. GB. DB_CHAINING { ON | OFF }: When ON is specified. and the minimum value is 64 KB. The KB. UNLIMITED: Specifies that the file grows until the disk is full. The size specified is rounded to the nearest 64 KB.
The snapshot and source database must be on the same instance. To set this option. database modules (for example.SQL Server 2005 TRUSTWORTHY { ON | OFF }: When ON is specified. That is.Handout . For the snapshot to work.. the primary database file is Page 79 ©Copyright 2007. user-defined functions.databases catalog view and message delivery is started. database_snapshot_name can be a maximum of 128 characters. Because the statement has no <filespec> items. requires membership in the sysadmin fixed server role .. FILENAME = 'os_file_name' ) [ . n ]: For creating a database snapshot. <service_broker_option>: Controls Service Broker options on the database. AS SNAPSHOT OF source_database_name: Specifies that the database being created is a database snapshot of the source database specified by source_database_name. However. all the data files must be specified individually. database_snapshot_name: Is the name of the new database snapshot. specifies a list of files in the source database. log files are not allowed for database snapshots. is_broker_enabled is set to true in the sys. ON ( NAME = logical_file_name. The model. The default is OFF. the master database always has TRUSTWORTHY set to ON. All Rights Reserved C3: Protected . NEW_BROKER: Creates a new service_broker_guid in sys. or stored procedures) that use an impersonation context can access resources outside the database. ERROR_BROKER_CONVERSATIONS: Ends all conversations with an error that indicates a copy of the broker has been created. tempdb databases always have TRUSTWORTHY set to OFF and the value cannot be changed for these databases.. ENABLE_BROKER: Specifies that Service Broker is enabled for the specified database.databases and the restored database. Service Broker options can only be specified when the FOR ATTACH clause is used. For descriptions of NAME and FILENAME and their values see the descriptions of the equivalent <filespec> values. database modules in an impersonation context cannot access resources outside the database. By default. Cognizant Technology Solutions. When OFF. Database snapshot names must be unique within an instance of SQL Server and comply with the rules for identifiers. TRUSTWORTHY is set to OFF whenever the database is attached. Examples Creating a database without specifying files The following example creates the database mytest and creates a corresponding primary and transaction log file. views.
USE master. size. GO Creating a database that specifies the data and transaction log files The following example creates the database Sales.1) FROM master. The transaction log is set to the larger of these values: 512KB or 25% the size of the primary data file.sys.ldf''.Get the SQL Server data path DECLARE @data_path nvarchar(256). FILENAME = '''+ @data_path + 'saledat.Verify the database files and sizes SELECT name.mdf'. Page 80 ©Copyright 2007.execute the CREATE DATABASE statement EXECUTE ('CREATE DATABASE Sales ON ( NAME = Sales_dat. Because MAXSIZE is not specified. GO -. it uses MB and is allocated in megabytes. the files can grow to fill all available disk space. the first file (Sales_dat) becomes the primary file. -. LOWER(physical_name)) . size*1.master_files WHERE name = N'mytest'. All Rights Reserved C3: Protected .0/128 AS [Size in MBs] FROM sys.SQL Server 2005 the size of the model database primary file. GO CREATE DATABASE mytest. GO IF DB_ID (N'Sales') IS NOT NULL DROP DATABASE Sales. USE master. FILEGROWTH = 5 ) LOG ON ( NAME = Sales_log. GO -. CHARINDEX(N'master. GO IF DB_ID (N'mytest') IS NOT NULL DROP DATABASE mytest. SET @data_path = (SELECT SUBSTRING(physical_name.mdf''. MAXSIZE = 50. The Sales_log file is allocated in megabytes because the MB suffix is explicitly stated in the SIZE parameter. 1. Because the keyword PRIMARY is not used. Cognizant Technology Solutions. Because neither MB nor KB is specified in the SIZE parameter for the Sales_dat file.master_files WHERE database_id = 1 AND file_id = 1). FILENAME = '''+ @data_path + 'salelog. SIZE = 10.Handout .
Get the SQL Server data path DECLARE @data_path nvarchar(256). SIZE = 100MB. CHARINDEX(N'master.mdf'.sys. Cognizant Technology Solutions. SIZE = 100MB. FILEGROWTH = 20).ndf''.SQL Server 2005 SIZE = 5MB. ( NAME = Arch3.mdf''.mdf is used for primary data files. USE master. The transaction log files are specified following the LOG ON keywords. LOWER(physical_name)) .execute the CREATE DATABASE statement EXECUTE ('CREATE DATABASE Archive ON PRIMARY (NAME = Arch1. SIZE = 100MB. All Rights Reserved C3: Protected . 1. FILENAME = '''+ @data_path + 'archdat2. Note the extensions used for the files in the FILENAME option: .ndf''. . MAXSIZE = 200.master_files WHERE database_id = 1 AND file_id = 1).ldf is used for transaction log files. The primary file is the first file in the list and is explicitly specified with the PRIMARY keyword.Handout .1) FROM master. FILEGROWTH = 20). -. GO -. MAXSIZE = 200. FILEGROWTH = 5MB )' ). ( NAME = Arch2.ndf is used for the secondary data files. FILENAME = '''+ @data_path + 'archdat1. GO GO Creating a database by specifying multiple data and transaction log files The following example creates the database Archive that has three 100-MB data files and two 100-MB transaction log files. Page 81 ©Copyright 2007. and . SET @data_path = (SELECT SUBSTRING(physical_name. FILENAME = '''+ @data_path + 'archdat3. GO IF DB_ID (N'Archive') IS NOT NULL DROP DATABASE Archive. MAXSIZE = 25MB. MAXSIZE = 200.
A filegroup named SalesGroup2 with the files SGrp2Fi1 and SGrp2Fi2. MAXSIZE = 50. GO Creating a database that has filegroups The following example creates the database Sales that has the following filegroups: The primary filegroup with the files Spri1_dat and Spri2_dat.Get the SQL Server data path DECLARE @data_path nvarchar(256). MAXSIZE = 200. SET @data_path = (SELECT SUBSTRING(physical_name.SQL Server 2005 FILEGROWTH = 20) LOG ON (NAME = Archlog1. FILENAME = '''+ @data_path + 'SPri2dt. (NAME = Archlog2.execute the CREATE DATABASE statement EXECUTE ('CREATE DATABASE Sales ON PRIMARY ( NAME = SPri1_dat. All Rights Reserved C3: Protected .ndf''. CHARINDEX(N'master.Handout . Page 82 ©Copyright 2007. USE master. ( NAME = SPri2_dat. Cognizant Technology Solutions. -.mdf'. GO -.ldf''. SIZE = 100MB. FILEGROWTH = 20)' ). FILENAME = '''+ @data_path + 'ldf''. A filegroup named SalesGroup1 with the files SGrp1Fi1 and SGrp1Fi2. SIZE = 10. The FILEGROWTH increments for these files is specified as 15%. FILENAME = '''+ @data_path + 'SPri1dat. SIZE = 100MB. MAXSIZE = 200.sys.1) FROM master. GO IF DB_ID (N'Sales') IS NOT NULL DROP DATABASE Sales.mdf''. 1. SIZE = 10.master_files WHERE database_id = 1 AND file_id = 1). FILEGROWTH = 15% ). FILEGROWTH = 20). FILENAME = '''+ @data_path + 'archlog1. LOWER(physical_name)) .
FILENAME = '''+ @data_path SIZE = 5MB. and then attaches it by using the FOR ATTACH clause. FILENAME = '''+ @data_path SIZE = 10.Get the SQL Server data path DECLARE @data_path nvarchar(256). + 'SG2Fi1dt.Handout . + 'salelog. FILENAME = '''+ @data_path SIZE = 10. FILEGROWTH = 15% ). FILEGROUP SalesGroup1 ( NAME = SGrp1Fi1_dat. ( NAME = SGrp1Fi2_dat. Cognizant Technology Solutions.ndf''. GO sp_detach_db Archive. USE master. In SQL Server 2005. FILEGROWTH = 5 ) LOG ON ( NAME = Sales_log. only the primary file has to be specified in the FOR ATTACH clause. FILEGROUP SalesGroup2 ( NAME = SGrp2Fi1_dat. GO -. FILEGROWTH = 5 ). ( NAME = SGrp2Fi2_dat. because the location of the files has not changed since they were created. Archive was defined to have multiple data and log files. FILENAME = '''+ @data_path SIZE = 10. However. Page 83 ©Copyright 2007.ndf''. MAXSIZE = 50.SQL Server 2005 MAXSIZE = 50. FILEGROWTH = 5 ). FILEGROWTH = 5MB )' ). Attaching a database: The following example detaches the database Archive created in example D.ndf''. All Rights Reserved C3: Protected . FILEGROWTH = 5 ). MAXSIZE = 50. MAXSIZE = 25MB. MAXSIZE = 50. MAXSIZE = 50. GO + 'SG1Fi1dt. any full-text files that are part of the database that is being attached will be attached with the database. FILENAME = '''+ @data_path SIZE = 10.ldf''.ndf''. + 'SG2Fi2dt. + 'SG1Fi2dt.
click the Filegroups page. Page 84 ©Copyright 2007. CHARINDEX(N'master. click OK. All Rights Reserved C3: Protected . To create the database by accepting all default values.mdf'') FOR ATTACH').mdf'. 4. click OK. In New Database. 7.master_files WHERE database_id = 1 AND file_id = 1). GO Creating Database (Using using SQL Server Management Studio) Steps to Create Database: 1. LOWER(physical_name)) . Click Add and then enter the values for the filegroup. connect to an instance of the SQL Server 2005 Database Engine and then expand that instance.SQL Server 2005 SET @data_path = (SELECT SUBSTRING(physical_name. Right-click Databases and then click New Database. To add a new filegroup.Handout . In Object Explorer.1) FROM master. To create the database. otherwise. To change the default values of the primary data and transaction log files. in the Database files grid. Summary SQL Server 2005 databases have three types of files o o o Primary data files Secondary data files Log files Filegroup is a logical collection of data files that enables administrators to manage all files within the filegroup as single item. 5. click the appropriate cell and enter the new value 6.sys. continue with the following optional steps. enter a database name. 3. 1. -. Cognizant Technology Solutions. 2.Execute CREATE DATABASE FOR ATTACH statement EXEC ('CREATE DATABASE Archive ON (FILENAME = '''+ @data_path + 'archdat1.
Validation: Validation operations on a database. and logical integrity of all the objects in the specified database.SQL Server 2005 Session 17: Views and Partition Tables Learning Objectives After completing this session. Informational: Tasks that gather and display various types of information. Miscellaneous: Miscellaneous tasks such as enabling trace flags or removing a DLL from memory. Page 85 ©Copyright 2007. index or filegroup. Some useful DBCC commands are as follows: DBCC SHRINKDATABASE: Shrinks the size of the data files in the specified database. filegroup or allocation. table. you will be able to: Execute Database Console Commands Identify the types of views and their advantages Explain Partition Tables Database Console Commands T-SQL provides DBCC statements that act as Database Console Commands for SQL Server 2005. DBCC CLEANTABLE: Reclaims space for dropped variable length columns and text columns. DBCC SHOW_STATISTICS: Displays the current distribution statistics for the specified target on the specified table. Cognizant Technology Solutions.They are grouped into the following categories: Maintenance: Maintenance tasks on a database. DBCC CHECKDB: Checks the allocation. DBCC SHRINKFILE: Shrinks the size of the specified data file or log file for the related database. structural. DBCC DBREINDEX: Rebuilds one or more indexes for a table in the specified database. Views A view is a virtual table whose contents are defined by a query. a view consists of a set of named columns and rows of data. a view does not exist as a stored set of data values in a database. The query that defines the view can be from one or more tables or from other views in the current or other databases. The rows and columns of data come from tables referenced in the query defining the view and are produced dynamically when the view is referenced. Like a real table. catalog. All Rights Reserved C3: Protected . A view acts as a filter on the underlying tables referenced in the view. DBCC INDEXDEFRAG: Defragments indexes of the specified table or view.Handout . Unless indexed. index.
This means it has been computed and stored. This is useful. for example. you can create standard views.SQL Server 2005 Distributed queries can also be used to define views that use data from multiple heterogeneous sources. Page 86 ©Copyright 2007.Handout . and partitioned views: Standard Views: Combining data from one or more tables through a standard view lets you satisfy most of the benefits of using views. indexed views. They are not wellsuited for underlying data sets that are frequently updated. A federation is a group of servers administered independently. Types of Views In SQL Server 2005. Distributed partitioned views are used to implement a federation of database servers. Indexed views dramatically improve the performance of some types of queries. This makes the data appear as if from one table. Forming a federation of database servers by partitioning data is the mechanism that lets you scale out a set of servers to support the processing requirements of large. There are no restrictions on querying through views and few restrictions on modifying data through them. Partitioned Views: A partitioned view joins horizontally partitioned data from a set of member tables across one or more servers. When a view joins data from tables across servers. These include focusing on specific data and simplifying data manipulation. it is a distributed partitioned view. Cognizant Technology Solutions. This illustration shows a view based on two tables. if you want to combine similarly structured data from different servers. Indexed Views: An indexed view is a view that has been materialized. A view that joins member tables on the same instance of SQL Server is a local partitioned view. You index a view by creating a unique clustered index on it. Indexed views work best for queries that aggregate many rows. but which cooperate to share the processing load of a system. each of which stores data for a different region of your organization. multitiered Web sites. All Rights Reserved C3: Protected .
even when they are using the same data at the same time. Cognizant Technology Solutions. CREATE VIEW Creates a virtual table that represents the data in one or more tables in an alternative way.. To simplify the Data Manipulation: Simplify the users work with data. view_name: Is the name of the view. the view columns acquire the same names as the columns in the SELECT statement. Unnecessary or sensitive data can be left out of the view.n ] ] AS select_statement [ . typically because of a join. If column is not specified. or when a column in a view is specified a name different from that of the column from which it is derived.Handout . This appears to the user as a single table that is called a partitioned view... To Combine Partitioned Data Across Servers: The Transact-SQL UNION set operator can be used within a view to combine the results of two or more queries from separate tables into a single result set.SQL Server 2005 Advantages of Views Views are commonly applied to: To Focus on Specific Data: Views let users focus on specific data that interests them and on the specific tasks for which they are responsible. Column names can also be assigned in the SELECT statement. To Export and Import Data: Views can be used to export data to other applications. View names must follow the rules for identifiers. Page 87 ©Copyright 2007. and SELECT queries as views so that users do not have to specify all the conditions and qualifications every time an additional operation is performed on that data.. projections.. column: Is the name to be used for a column in a view. when two or more columns may otherwise have the same name. Syntax CREATE VIEW [ schema_name . UNION queries. To Customize Data: Views let different users to refer the data in different ways. Specifying the view owner name is optional. ] view_name [ (column [ . or a constant. You can define frequently used joins. All Rights Reserved C3: Protected .. ] [ WITH CHECK OPTION ] <view_attribute> ::= { [ ENCRYPTION ] [ SCHEMABINDING ] [ VIEW_METADATA ] } Arguments schema_name: Is the name of the schema to which the view belongs. a function.n ] ) ] [ WITH <view_attribute> [ . A column name is required only when a column is derived from an arithmetic expression. CREATE VIEW must be the first statement in a query batch.
select_statement: Is the SELECT statement that defines the view. All referenced objects must be in the same database. or user-defined functions that are referenced. SCHEMABINDING cannot be specified if the view contains alias data type columns. Because select_statement uses the SELECT statement.object) of tables. All Rights Reserved C3: Protected . Views or tables that participate in a view created with the SCHEMABINDING clause cannot be dropped unless that view is dropped or changed so that it no longer has schema binding. The statement can use more than one table and other views. CHECK OPTION cannot be specified if TOP is used anywhere in select_statement.syscomments that contain the text of the CREATE VIEW statement. Otherwise. the Microsoft SQL Server 2005 Database Engine raises an error. Cognizant Technology Solutions. When a row is modified through a view. the base table or tables cannot be modified in a way that would affect the view definition. Page 88 ©Copyright 2007. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified. unless there is also a TOP clause in the select list of the SELECT statement The INTO keyword The OPTION clause A reference to a temporary table or a table variable. the select_statement must include the two-part names (schema. Using WITH ENCRYPTION prevents the view from being published as part of SQL Server replication.SQL Server 2005 AS: Specifies the actions the view is to perform. When you use SCHEMABINDING. A view can be created that uses more than one table or other views with a SELECT clause of any complexity. Also. The SELECT clauses in a view definition cannot include the following: o o o o o COMPUTE or COMPUTE BY clauses An ORDER BY clause. ENCRYPTION: Encrypts the entries in sys.Handout . When SCHEMABINDING is specified. the WITH CHECK OPTION makes sure the data remains visible through the view after the modification is committed. views. SCHEMABINDING: Binds the view to the schema of the underlying table or tables. A view does not have to be a simple subset of the rows and columns of one particular table. the SELECT statement must be a single table statement or a multitable JOIN with optional aggregation. Appropriate permissions are required to select from the objects referenced in the SELECT clause of the view that is created. it is valid to use <join_hint> and <table_hint> hints as specified in the FROM clause Functions and multiple SELECT statements separated by UNION or UNION ALL can be used in select_statement. executing ALTER TABLE statements on tables that participate in views that have schema binding fail when these statements affect the view definition. In an indexed view definition. CHECK OPTION : Forces all data modification statements executed against the view to follow the criteria set within select_statement.
When a view is created by using WITH VIEW_METADATA. the browse-mode metadata returns the view name and not the base table names when it describes columns from the view in the result set. are updatable if the view has INSTEAD OF INSERT or INSTEAD OF UPDATE triggers. Browse-mode metadata is additional metadata that the instance of SQL Server returns to these client-side APIs.FirstName. Cognizant Technology Solutions.ContactID = c.ContactID . Browse-mode metadata includes information about the base table that the columns in the result set belong to. GO Using WITH ENCRYPTION The following example uses the WITH ENCRYPTION option and shows computed columns.LastName. and multiple columns. 'V') IS NOT NULL DROP VIEW PurchaseOrderReject .EmployeeID. instead of the base table or tables. c. For more information about updatable views. USE AdventureWorks .Handout .SQL Server 2005 VIEW_METADATA: Specifies that the instance of SQL Server will return to the DB-Library. A simple view is helpful when a combination of columns is queried frequently. The view could be created for the person in charge of tracking work anniversaries but without giving this person access to all the data in these tables. e. 'view') IS NOT NULL DROP VIEW hiredate_view . This metadata enables the client-side APIs to implement updatable client-side cursors. GO CREATE VIEW PurchaseOrderReject WITH ENCRYPTION Page 89 ©Copyright 2007. all its columns. see Remarks. GO IF OBJECT_ID ('hiredate_view'. and OLE DB APIs the metadata information about the view.HireDate FROM HumanResources. GO IF OBJECT_ID ('PurchaseOrderReject'.Employee e JOIN Person.Employee and Person. GO CREATE VIEW hiredate_view AS SELECT c. ODBC. Examples Using a simple CREATE VIEW The following example creates a view by using a simple SELECT statement. when browse-mode metadata is being requested for a query that references the view. The data provides name and hire date information for the employees of Adventure Works Cycles. All Rights Reserved C3: Protected . except a timestamp column. renamed columns. e. The data from this view comes from the HumanResources. For views created with VIEW_METADATA. USE AdventureWorks .Contact c on e.Contact tables of the AdventureWorks database.
GO CREATE VIEW SeattleOnly AS SELECT c.AddressID = a. s.EmployeeID = ea.Handout . RejectedQty. a. All Rights Reserved C3: Protected .StateProvince s ON a. 'V') IS NOT NULL DROP VIEW SeattleOnly . GO CREATE VIEW SalesPersonPerform AS SELECT TOP 100 SalesPersonID. c.City.SalesOrderHeader WHERE OrderDate > '12/31/2000' GROUP BY SalesPersonID ORDER BY TotalSales DESC .PurchaseOrderDetail WHERE RejectedQty / ReceivedQty > 0 AND DueDate > '06/30/2001' .StateProvinceCode FROM Person. GO Page 90 ©Copyright 2007. GO Using built-in functions within a view The following example shows a view definition that includes a built-in function. SUM(TotalDue) AS TotalSales FROM Sales. you must specify a column name for the derived column. USE AdventureWorks . 'view') IS NOT NULL DROP VIEW SalesPersonPerform . USE AdventureWorks . Cognizant Technology Solutions.EmployeeID JOIN Person. When you use functions.Contact c JOIN HumanResources.SQL Server 2005 AS SELECT PurchaseOrderID.EmployeeAddress ea ON e.AddressID JOIN Person. GO IF OBJECT_ID ('SeattleOnly'.Employee e ON c.StateProvinceID = s. GO Using WITH CHECK OPTION The following example shows a view named SeattleOnly that references five tables and allows for data modifications to apply only to employees who live in Seattle.Address a ON ea. GO IF OBJECT_ID ('SalesPersonPerform'.LastName. ReceivedQty.FirstName. RejectedQty / ReceivedQty AS RejectRatio FROM Purchasing.ContactID = e.ContactID JOIN HumanResources.City = 'Seattle' WITH CHECK OPTION .StateProvinceID WHERE a.
GO --Create the view that combines all supplier tables. INSERT SUPPLY1 VALUES ('5'. SUPPLY2. CREATE TABLE SUPPLY3 ( supplyID INT PRIMARY KEY CHECK (supplyID BETWEEN 301 and 450). 'BraziliaLtd'). and SUPPLY4. CREATE VIEW all_supplier_view AS SELECT * FROM SUPPLY1 UNION ALL SELECT * FROM SUPPLY2 UNION ALL SELECT * FROM SUPPLY3 UNION ALL SELECT * FROM SUPPLY4. GO INSERT SUPPLY1 VALUES ('1'.SQL Server 2005 Using partitioned data The following example uses tables named SUPPLY1. 'EuroGroup'). INSERT SUPPLY2 VALUES ('231'. supplier CHAR(50) ). supplier CHAR(50) ). 'Afrique'). located in different countries/regions. INSERT SUPPLY4 VALUES ('475'.Handout . INSERT SUPPLY2 VALUES ('280'. Page 91 ©Copyright 2007. CREATE TABLE SUPPLY2 ( supplyID INT PRIMARY KEY CHECK (supplyID BETWEEN 151 and 300). INSERT SUPPLY4 VALUES ('521'. SUPPLY3. supplier CHAR(50) ). 'India'). 'NZ'). supplier CHAR(50) ). INSERT SUPPLY3 VALUES ('321'. 'CaliforniaCorp'). 'UKArchip'). Cognizant Technology Solutions. All Rights Reserved C3: Protected . 'FarEast'). CREATE TABLE SUPPLY4 ( supplyID INT PRIMARY KEY CHECK (supplyID BETWEEN 451 and 600). --Create the tables and insert the values. INSERT SUPPLY3 VALUES ('442'. These tables correspond to the supplier tables from four offices. CREATE TABLE SUPPLY1 ( supplyID INT PRIMARY KEY CHECK (supplyID BETWEEN 1 and 150).
Steps to create Partitioned Tables: o First create Partition Function: (CREATE PARTITION FUNCTION ) Partition Functions define partition boundaries Boundary values can be assigned either to LEFT to Right Function Second create Partition Scheme: (CREATE PARTITION SCHEME ) A Partition scheme assign partitions to filegroups The "next" filegroup can also be defined Third create Partition table: (CREATE TABLE) o o Page 92 ©Copyright 2007.A completely dynamic object.LastName) AS Name. For example: Recent orders data might be updated frequently and require regular backups. Partitioning makes large tables or indexes more manageable by letting you to access or manage subsets of data quickly and efficiently. d. Cognizant Technology Solutions.LastName. while older orders might change rarely and require only infrequent backups o Control over storage media: Partitioning a table lets you to choose appropriate storage for date based on its access requirements. All Rights Reserved C3: Protected . Partitioned Tables Partitioned tables are tables whose data is horizontally divided into units.ContactID INNER JOIN (SELECT AddressID. c.Handout .FirstName) + ' ' + LTRIM(c.FirstName . Performance benefits partitioned table includes the following: o o o Faster index searches Enhanced JOIN performance Reduced locking Manageability benefits of partitioned tables includes the following: o The ability to implement separate backup strategies: Different sets of data might have different backup requirements. which is faster and less intrusive than managing an entire index. GO SELECT RTRIM(c.City FROM Person. This allows you to reorganize.Employee e ON c.Address) AS d --Derived table ON e. optimize and rebuild indexes by partition.Present only for the duration of query execution Example: USE AdventureWorks .Contact c INNER JOIN HumanResources.AddressID ORDER BY c. City FROM Person. which may be spread across more than one filegroup in a database.ContactID = e.AddressID = d. o Index management benefits: In addition to partitioning a table you can partition its indexes.SQL Server 2005 Derived Tables Derived tables are the result set of a SELECT query in the FROM clause.
GO CREATE TABLE PartitionTable (col1 int. GO CREATE PARTITION SCHEME myRangePS1 AS PARTITION myRangePF1 TO (test1fg. 100. Cognizant Technology Solutions.Handout . All Rights Reserved C3: Protected . GO Summary Views are applied to give a different perspective of data Views are not stored physically and only consists of a stored query You can modify base tables through a view Indexed views are stored physically Partitioned views are applied to increase scalability and performance Page 93 ©Copyright 2007. 1000) .SQL Server 2005 Example: CREATE PARTITION FUNCTION myRangePF1 (int) AS RANGE LEFT FOR VALUES (1. test2fg. col2 char(10)) ON myRangePS1 (col1) . test3fg. test4fg) .
. Use an IF. and made interdependent using programming-like constructs. as they occur. For example.ELSE END (BEGIN... use a BEGIN.. Cognizant Technology Solutions. in batches.END blocks can be nested.. Syntax BEGIN { sql_statement | statement_block } END Page 94 ©Copyright 2007. statement blocks. and another statement or block of statements should be executed if that condition is not met (the ELSE condition).ELSE pair of statements when a certain statement or block of statements needs to be executed IF some condition is met. and in stored procedures.CATCH WAITFOR GOTO label WHILE IF. The control-of-flow statements cannot span multiple batches or stored procedures.END RETURN BREAK CONTINUE TRY. These words can be used in ad hoc Transact-SQL statements. related to each other. These control-of-flow words are useful when you need to direct Transact-SQL to take some kind of action.. and stored procedures.Handout .. separate Transact-SQL statements are performed sequentially. BEGIN... Without control-of-flow language. you will be able to: Execute Control flow statements Overview Transact-SQL provides special words called control-of-flow language that control the flow of execution of Transact-SQL statements... The Transact-SQL control-of-flow language keywords are: BEGIN.SQL Server 2005 Session 19: Control Flow Constructs Learning Objectives After completing this session..END pair of statements when including more than one Transact-SQL statement in a logical block. All Rights Reserved C3: Protected . Control-of-flow language permits statements to be connected..END) Encloses a series of Transact-SQL statements that will execute as a group..
Unless a statement block is used.END block. the IF or ELSE condition can affect the performance of only one Transact-SQL statement.. @cost money EXECUTE usp_GetList '%Bikes%'. In this example. DECLARE @compareprice money. Examples: The following example uses IF…ELSE with output from the usp_GetList stored procedure.ELSE block. To define a statement block (batch).SQL Server 2005 Arguments {sql_statement | statement_block}: Is any valid Transact-SQL statement or statement grouping as defined with a statement block. 700. { sql_statement | statement_block }: Is any Transact-SQL statement or statement grouping as defined by using a statement block.. the SELECT statement must be enclosed in parentheses. @cost OUTPUT IF @cost <= @compareprice BEGIN PRINT 'These products can be purchased for less than $'+RTRIM(CAST(@compareprice AS varchar(20)))+'. The optional ELSE keyword introduces another Transact-SQL statement that is executed when the IF condition is not satisfied: the Boolean expression returns FALSE. the stored procedure returns a list of bikes with a list price less than $700. This causes the first PRINT statement to execute. To define a statement block..Handout . IF. The Transact-SQL statement that follows an IF keyword and its condition is executed if the condition is satisfied: the Boolean expression returns TRUE. use the control-of-flow keywords BEGIN and END. Syntax IF Boolean_expression { sql_statement | statement_block } [ ELSE { sql_statement | statement_block } ] Arguments Boolean_expression:Is an expression that returns TRUE or FALSE.. @compareprice OUT.. All Rights Reserved C3: Protected . certain Transact-SQL statements should not be grouped together within the same batch (statement block).ELSE Imposes conditions on the execution of a Transact-SQL statement.' END Page 95 ©Copyright 2007. Although all Transact-SQL statements are valid within a BEGIN. If the Boolean expression contains a SELECT statement. CREATE TABLE or SELECT INTO statements must refer to the same table name when the CREATE TABLE or SELECT INTO statements are used in both the IF and ELSE areas of the IF. Cognizant Technology Solutions.. use the controlof-flow language keywords BEGIN and END. This stored procedure is defined in Creating Stored Procedures.
Cognizant Technology Solutions.n ] [ ELSE else_result_expression ] END Arguments input_expression: Is the expression evaluated when the simple CASE format is used. result expression is any valid expression.SQL Server 2005 ELSE PRINT 'The prices for all products in this category exceed $'+ RTRIM(CAST(@compareprice AS varchar(20)))+'.. or multiple WHEN Boolean_expression THEN result_expression clauses can be used. All Rights Reserved C3: Protected . The data types of input_expression and each when_expression must be the same or must be an implicit conversion. THEN result_expression: Is the expression returned when input_expression equals when_expression evaluates to TRUE.' CASE Both formats support an optional ELSE argument..Handout . Syntax Simple CASE function: CASE input_expression WHEN when_expression THEN result_expression [ . or Boolean_expression evaluates to TRUE.. input_expression is any valid expression. when_expression is any valid expression. Page 96 ©Copyright 2007.n ] [ ELSE else_result_expression ] END Searched CASE function: CASE WHEN Boolean_expression THEN result_expression [ . n: Is a placeholder that indicates that multiple WHEN when_expression THEN result_expression clauses.. WHEN when_expression: Is a simple expression to which input_expression is compared when the simple CASE format is used.
no other comparisons are made.Product ORDER BY ProductNumber. Boolean_expression is any valid Boolean expression. USE AdventureWorks.not for resale' < 50 THEN 'Under $50' >= 50 and ListPrice < 250 THEN 'Under $250' Page 97 ©Copyright 2007. see Data Type Precedence (Transact-SQL). Result Types: Returns the highest precedence type from the set of types in result_expressions and the optional else_result_expression. The following example displays the list price as a text comment based on the price range for a product. Cognizant Technology Solutions. else_result_expression is any valid expression. CASE WHEN ListPrice WHEN ListPrice WHEN ListPrice Name. If this argument is omitted and no comparison operation evaluates to TRUE. Name FROM Production. Category = CASE ProductLine WHEN 'R' THEN 'Road' WHEN 'M' THEN 'Mountain' WHEN 'T' THEN 'Touring' WHEN 'S' THEN 'Other sale items' ELSE 'Not for sale' END. the searched CASE function allows for values to be replaced in the result set based on comparison values. GO SELECT ProductNumber. For more information. USE AdventureWorks. Examples: Using a SELECT statement with a simple CASE function Within a SELECT statement.SQL Server 2005 ELSE else_result_expression: Is the expression returned if no comparison operation evaluates to TRUE. 'Price Range' = = 0 THEN 'Mfg item . WHEN Boolean_expression: Is the Boolean expression evaluated when using the searched CASE format. The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion. All Rights Reserved C3: Protected . The following example uses the CASE function to change the display of product line categories to make them more understandable. GO Using a SELECT statement with simple and searched CASE function Within a SELECT statement. CASE returns NULL.Handout . a simple CASE function allows for only an equality check. GO SELECT ProductNumber.
The Transact-SQL statement or statements that follow GOTO are skipped and processing continues at the label. If no Boolean_expression evaluates to TRUE. GO Result Values: Simple CASE function: Evaluates input_expression. A label can be used as a commenting method whether GOTO is used. evaluates input_expression = when_expression for each WHEN clause. Cognizant Technology Solutions. or a NULL value if no ELSE clause is specified. Returns the result_expression of the first input_expression = when_expression that evaluates to TRUE. If no input_expression = when_expression evaluates to TRUE. All Rights Reserved C3: Protected . Examples: The following example shows GOTO looping as an alternative to using WHILE. Labels must follow the rules for identifiers. batch. Searched CASE function: Evaluates. or statement block. GO DECLARE @tablename sysname Page 98 ©Copyright 2007. USE AdventureWorks.Handout . the SQL Server 2005 Database Engine returns the else_result_expression if an ELSE clause is specified. the Database Engine returns the else_result_expression if an ELSE clause is specified. Syntax Define the label: label : Alter the execution: GOTO label Arguments label: Is the point after which processing starts if a GOTO is targeted to that label.Product ORDER BY ProductNumber . in the order specified. GOTO statements and labels can be used anywhere within a procedure. Boolean_expression for each WHEN clause. GOTO statements can be nested. or a NULL value if no ELSE clause is specified.SQL Server 2005 WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000' ELSE 'Over $1000' END FROM Production. Returns result_expression of the first Boolean_expression that evaluates to TRUE. and then in the order specified. GOTO Alters the flow of execution to a label.
WHILE Sets a condition for the repeated execution of an SQL statement or statement block. but not always. All Rights Reserved C3: Protected . Any statements appearing after the END keyword. Page 99 ©Copyright 2007. the SELECT statement must be enclosed in parentheses. The statements are executed repeatedly as long as the specified condition is true. opened by an IF test. If the Boolean expression contains a SELECT statement.Handout . BREAK is frequently. Any statements after the CONTINUE keyword are ignored. CONTINUE is frequently. The execution of statements in the WHILE loop can be controlled from inside the loop with the BREAK and CONTINUE keywords. started by an IF test. use the control-of-flow keywords BEGIN and END.SQL Server 2005 SET @tablename = N'Person. are executed. To define a statement block. but not always. Syntax WHILE Boolean_expression { [ { [ { sql_statement | statement_block } BREAK ] sql_statement | statement_block } CONTINUE ] sql_statement | statement_block } Arguments: Boolean_expression: Is an expression that returns TRUE or FALSE.AddressType' table_loop: IF (@@FETCH_STATUS <> -2) BEGIN SELECT @tablename = RTRIM(UPPER(@tablename)) EXEC ('SELECT ''' + @tablename + ''' = COUNT(*) FROM ' + @tablename ) PRINT ' ' END FETCH NEXT FROM tnames_cursor INTO @tablename IF (@@FETCH_STATUS <> -1) GOTO table_loop GO BREAK Exits the innermost loop in a WHILE or IF…ELSE statement. Cognizant Technology Solutions. marking the end of the loop. {sql_statement | statement_block}: Is any Transact-SQL statement or statement grouping as defined with a statement block. CONTINUE Restarts a WHILE loop.
All Rights Reserved C3: Protected . or a specified statement modifies or returns at least one row. Any statements that appear after the END keyword. stored procedure. Syntax WAITFOR { DELAY 'time_to_pass' | TIME 'time_to_execute' | ( receive_statement ) [ . USE AdventureWorks. Remarks: If two or more WHILE loops are nested. are executed. or transaction until a specified time or time interval is reached. WAITFOR Blocks the execution of a batch. Examples: Using BREAK and CONTINUE with nested IF.All the statements after the end of the inner loop run first. Cognizant Technology Solutions. marking the end of the loop.ELSE and WHILE In the following example.Product IF (SELECT MAX(ListPrice) FROM Production.Handout .Product) < $300 BEGIN UPDATE Production. and then the next outermost loop restarts. This loop continues doubling the prices until the maximum price is greater than $500. CONTINUE: Causes the WHILE loop to restart.Product SET ListPrice = ListPrice * 2 SELECT MAX(ListPrice) FROM Production. ignoring any statements after the CONTINUE keyword.SQL Server 2005 BREAK: Causes an exit from the innermost WHILE loop. TIMEOUT timeout ] } Page 100 ©Copyright 2007. and then exits the WHILE loop and prints a message. the inner BREAK exits to the next outermost loop... the WHILE loop restarts and doubles the prices again. if the average list price of a product is less than $300.Product) > $500 BREAK ELSE CONTINUE END PRINT 'Too much for the market to bear'. the WHILE loop doubles the prices and then selects the maximum price. If the maximum price is less than or equal to $500. GO WHILE (SELECT AVG(ListPrice) FROM Production.
the date part of the datetime value is not allowed. (22:20). time_to_pass can be specified in one of the acceptable formats for datetime data. All Rights Reserved C3: Protected .SQL Server 2005 Arguments: DELAY: Is the specified period of time that must pass. receive_statement: Is a valid RECEIVE statement. USE msdb.. Examples: Using WAITFOR TIME: The following example executes the stored procedure sp_update_job at 10:20 P. or transaction runs. BEGIN WAITFOR DELAY '02:00'.. If an error Page 101 ©Copyright 2007.Handout . therefore. stored procedure. END. stored procedure. in milliseconds. therefore. GO TRY. TIME: Is the specified time when the batch. BEGIN WAITFOR TIME '22:20'. up to a maximum of 24 hours. or it can be specified as a local variable. Cognizant Technology Solutions. @new_name = 'UpdatedJob'. time_to_execute can be specified in one of the acceptable formats for datetime data. GO Using WAITFOR DELAY: The following example executes the stored procedure after a 2-hour delay. 'time_to_pass': Is the period of time to wait. or transaction proceeds. before execution of a batch. to wait for a message to arrive on the queue. or it can be specified as a local variable. EXECUTE sp_update_job @job_name = 'TestJob'. 'time_to_execute': Is the time at which the WAITFOR statement finishes. END. the date part of the datetime value is not allowed. Dates cannot be specified. A group of Transact-SQL statements can be enclosed in a TRY block. EXECUTE sp_helpdb. Dates cannot be specified.CATCH Implements error handling for Transact-SQL that is similar to the exception handling in the C# and C++ languages.M. TIMEOUT timeout: Specifies the period of time. EXECUTE sp_add_job @job_name = 'TestJob'.
For example. A TRY…CATCH construct cannot span multiple batches. Either a TRY block or a CATCH block can contain nested TRY…CATCH constructs. control is passed to another group of statements enclosed in a CATCH block. any error in the nested TRY block will Page 102 ©Copyright 2007. A TRY…CATCH construct cannot span multiple blocks of Transact-SQL statements. Placing any other statements between the END TRY and BEGIN CATCH statements generates a syntax error.CATCH in Transact-SQL.SQL Server 2005 occurs within the TRY block. control passes to the statement immediately after the associated END CATCH statement. If there are no errors in the code enclosed in a TRY block. For more information about using RAISERROR in conjunction with TRY…CATCH. If there is an error in the code enclosed in a TRY block. control passes to the first statement in the associated CATCH block. control is passed back to the statement that invoked the stored procedure or trigger. see Using TRY. If any of the error information must be returned to the application. Errors trapped by a CATCH block are not returned to the calling application. Errors encountered in a CATCH block are treated like errors generated anywhere else.Handout . For example. If the CATCH block contains a nested TRY…CATCH construct. the code in the CATCH block must do so using mechanisms. All Rights Reserved C3: Protected . TRY…CATCH constructs can be nested. If the END CATCH statement is the last statement in a stored procedure or trigger. Cognizant Technology Solutions. Syntax: BEGIN TRY { sql_statement | statement_block } END TRY BEGIN CATCH { sql_statement | statement_block } END CATCH [ . when the last statement in the TRY block completes. control passes to the statement immediately after the END CATCH statement.. a TRY…CATCH construct cannot span two BEGIN…END blocks of Transact-SQL statements and cannot span an IF…ELSE construct. A TRY block must be followed immediately by an associated CATCH block. a CATCH block can contain an embedded TRY…CATCH construct to handle errors encountered by the CATCH code. When the code in the CATCH block completes. Remarks: A TRY…CATCH construct catches all execution errors with severity greater than 10 that do not terminate the database connection. ] Arguments: sql_statement: Is any Transact-SQL statement.. such as SELECT result sets or the RAISERROR and PRINT statements. statement_block: Any group of Transact-SQL statements in a batch or enclosed in a BEGIN…END block.
ERROR_STATE() returns the error state number. In the CATCH block of a TRY…CATCH construct. TRY…CATCH constructs catch unhandled errors from stored procedures or triggers executed by the code in the TRY block.SQL Server 2005 pass control to the nested CATCH block. 'P' ) IS NOT NULL DROP PROCEDURE usp_GetErrorInfo. If there is no nested TRY…CATCH construct. control is passed back to the statement immediately after the EXECUTE statement that called the stored procedure. the stored procedures or triggers can contain their own TRY…CATCH constructs to handle errors generated by their code. The TRY…CATCH construct cannot be used within a user-defined function. object names. GOTO statements cannot be used to enter a TRY or CATCH block. the script below demonstrates a stored procedure that contains error-handling functions. when a TRY block executes a stored procedure and an error occurs in the stored procedure. Retrieving Error Information Within the scope of a CATCH block. If the stored procedure contains a TRY…CATCH construct. For example. GO Page 103 ©Copyright 2007. All Rights Reserved C3: Protected . Error information may be retrieved using these functions from anywhere within the scope of the CATCH block. ERROR_SEVERITY() returns the severity. IF OBJECT_ID ( 'usp_GetErrorInfo'. GOTO statements can be used to jump to a label within the same TRY or CATCH block or to leave a TRY or CATCH block. such as lengths. ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred. the error transfers control to the CATCH block in the stored procedure. USE AdventureWorks. the error returns control to the CATCH block associated with the TRY block containing the EXECUTE statement. For example. ERROR_LINE() returns the line number inside the routine that caused the error. The text includes the values supplied for any substitutable parameters. Cognizant Technology Solutions. the error can be handled in the following ways: If the stored procedure does not contain its own TRY…CATCH construct. GO -.Verify that the stored procedure does not already exist. Alternatively. When the CATCH block code completes. the following system functions can be used to obtain information about the error that caused the CATCH block to be executed: ERROR_NUMBER() returns the number of the error. ERROR_MESSAGE() returns the complete text of the error message. the stored procedure is called and information about the error is returned. the error is passed back to the caller. or times.Handout . These functions return NULL if called outside the scope of the CATCH block.
Generate divide-by-zero error.Create procedure to retrieve error information. ERROR_SEVERITY() AS ErrorSeverity. Syntax: DECLARE {{ @local_variable [AS] data_type } | { @cursor_variable_name CURSOR } | { @table_variable_name < table_type_definition > } } [ ..SQL Server 2005 -.. ERROR_PROCEDURE() AS ErrorProcedure.n] < table_type_definition > ::= TABLE ( { < column_definition > | < table_constraint > } [ . EXECUTE usp_GetErrorInfo. ERROR_LINE() AS ErrorLine.Handout . DECLARE @local_variable Variables are declared in the body of a batch or procedure with the DECLARE statement and are assigned values with either a SET or SELECT statement. GO BEGIN TRY -. Cognizant Technology Solutions. SELECT 1/0..increment ) ] ] Page 104 ©Copyright 2007. After declaration. CREATE PROCEDURE usp_GetErrorInfo AS SELECT ERROR_NUMBER() AS ErrorNumber. END CATCH. END TRY BEGIN CATCH -.. Cursor variables can be declared with this statement and used with other cursor-related statements. All Rights Reserved C3: Protected .Execute error retrieval routine.. ERROR_MESSAGE() AS ErrorMessage. ERROR_STATE() AS ErrorState. all variables are initialized as NULL.. ] ) < column_definition > ::= column_name { scalar_data_type | AS computed_column_expression } [ COLLATE collation_name ] [ [ DEFAULT constant_expression ] | IDENTITY [ ( seed.
Local variable names must conform to the rules for identifiers. CLR user-defined type.SQL Server 2005 [ ROWGUIDCOL ] [ < column_constraint > ] < column_constraint > ::= { [ NULL | NOT NULL ] | [ PRIMARY KEY | UNIQUE ] | CHECK ( logical_expression ) } < table_constraint > ::= { { PRIMARY KEY | UNIQUE } ( column_name [ . or alias data type. The table declaration includes column definitions. For example.Handout . Elements and essential definitions are included here. CURSOR: Specifies that the variable is a local cursor variable. or image data type. n: Is a placeholder indicating that multiple variables can be specified and assigned values. The only constraint types allowed are PRIMARY KEY. UNIQUE. ntext. An alias data type cannot be used as a column scalar data type if a rule or default definition is bound to the type.. Cognizant Technology Solutions. NULL. It is computed from an expression using other columns in the same table. A variable cannot be of text. and constraints. Cursor variable names must begin with an at (@) sign and conform to the rules for identifiers. @cursor_variable_name: Is the name of a cursor variable. data_type: Is any system-supplied. The expression can be a noncomputed Page 105 ©Copyright 2007. @table_variable_name: Is the name of a variable of type table. table_type_definition: Defines the table data type.. the table variable must be the only variable being declared in the DECLARE statement.. computed_column_expression: Is an expression defining the value of a computed column. names. data types. Variable names must begin with an at (@) sign and conform to the rules for identifiers. a computed column can have the definition cost AS price * qty. All Rights Reserved C3: Protected . and CHECK. table_type_definition is a subset of information used to define a table in CREATE TABLE. When declaring table variables. column_name: Is the name of the column in the table. ] ) | CHECK ( search_condition ) } Arguments: @local_variable: Is the name of a variable. Variable names must begin with an at (@) sign. scalar_data_type : Specifies that the column is a scalar data type.
To maintain compatibility with earlier versions of SQL Server. SQL Server provides a unique incremental value for the column. The ROWGUIDCOL property can be assigned only to a uniqueidentifier column. a constraint name can be assigned to a DEFAULT. Cognizant Technology Solutions. and ntext data types. varchar. A table can have multiple UNIQUE constraints.1). and is applicable only for columns of the char. a system function. The IDENTITY property can be assigned to tinyint. UNIQUE: Is a constraint that provides entity integrity for a given column or columns through a unique index. or NULL can be used as a default. collation_name can be either a Windows collation name or an SQL collation name. add COLLATE database_default to the definitions of char. Only a constant value. and ntext columns. or neither.0) columns. variable. Only one uniqueidentifier column per table can be designated as the ROWGUIDCOL column. such as a character string. NULL | NOT NULL: Are keywords that determine whether or not null values are allowed in the column. seed: Is the value used for the very first row loaded into the table. constant_expression: Is a constant. the column is assigned either the collation of the user-defined data type (if the column is of a user-defined data type) or the default collation of tempdb. Only one PRIMARY KEY constraint can be created per table. or any combination of these connected by one or more operators. DEFAULT definitions are removed when the table is dropped. or numeric(p. PRIMARY KEY: Is a constraint that enforces entity integrity for a given column or columns through a unique index. text. nvarchar. built-in function.SQL Server 2005 column name. If neither is specified.0). the default is (1. such as a SYSTEM_USER(). All Rights Reserved C3: Protected . int. To create a table variable with columns that inherit the collation of the current database. smallint. Identity columns are commonly used in conjunction with PRIMARY KEY constraints to serve as the unique row identifier for the table. constant. DEFAULT definitions can be applied to any columns except those defined as timestamp or those with the IDENTITY property. Page 106 ©Copyright 2007. DEFAULT: Specifies the value provided for the column when a value is not explicitly supplied during an insert. nchar. varchar.Handout . increment: Is the incremental value added to the identity value of the previous row that was loaded. or a system function used as the default value for the column. You must specify both the seed and increment. CHECK: Is a constraint that enforces domain integrity by limiting the possible values that can be entered into a column or columns. Only one identity column can be created per table. nchar. [ COLLATE collation_name ]: Specifies the collation for the column. NULL. Bound defaults and DEFAULT constraints cannot be used with an identity column. When a new row is added to the table. ROWGUIDCOL: Indicates that the new column is a row global unique identifier column. decimal(p. The expression cannot be a subquery or a user-defined function. nvarchar. IDENTITY: Indicates that the new column is an identity column. If not specified. text.
. LOOP. SET @find = 'Man%'. Microsoft SQL Server raises an error if a referenced cursor variable exists but does not have a cursor currently allocated to it. use EXECUTE. In SQL Server version 6. variable values are refreshed every time a cursor is reopened. In all these statements. Page 107 ©Copyright 2007. SQL Server raises the same error raised for an undeclared variable of another type. If a referenced cursor variable does not exist. Examples Using DECLARE The following example uses a local variable named @find to retrieve contact information for all last names beginning with 'Man'. FirstName.. A cursor variable: Can be the target of either a cursor type or another cursor variableCan be referenced as the target of an output cursor parameter in an EXECUTE statement if the cursor variable does not have a cursor currently assigned to it.Contact WHERE LastName LIKE @find. OPEN statement. SET CURSOR variable statement (on the right side). DEALLOCATE statement. Remarks: Variables are often used in a batch or procedure as counters for WHILE. GO DECLARE @find varchar(30). Positioned DELETE or UPDATE statement. Cognizant Technology Solutions. FETCH statement. or for an IF. Cursor variable values do not change after a cursor is declared.Handout . The scope of a local variable is the batch in which it is declared. Variables can be used only in expressions. Phone FROM Person. All Rights Reserved C3: Protected . USE AdventureWorks. not in place of object names or keywords. A cursor variable that currently has a cursor assigned to it can be referenced as a source in a: CLOSE statement. Should be regarded as a pointer to the cursor. SELECT LastName.SQL Server 2005 logical_expression: Is a logical expression that returns TRUE or FALSE.5 and earlier.ELSE block. To construct dynamic SQL statements.
--Display the result set of the table variable. SET @Group = N'North America'. Note the results in the INSERTED.SQL Server 2005 Use DECLARE with two variables The following example retrieves the names of Adventure Works Cycles sales representatives who are located in the North American sales territory and have at least $2. which updates the value of ModifiedDate to the current date. NewVacationHours. Page 108 ©Copyright 2007. GO DECLARE @MyTableVar table( EmpID int NOT NULL.EmployeeID.Employee SET VacationHours = VacationHours * 1. LastName. @Sales money. INSERTED. USE AdventureWorks. ModifiedDate FROM @MyTableVar. --Note that ModifiedDate reflects the value generated by an --AFTER UPDATE trigger. the columns returned from OUTPUT reflect the data before triggers are fired USE AdventureWorks. GO --Display the result set of the table.ModifiedDate INTO @MyTableVar. GO DECLARE @Group nvarchar(50).000. However.VacationHours. All Rights Reserved C3: Protected .25 OUTPUT INSERTED. Cognizant Technology Solutions. GO SET NOCOUNT ON. SET NOCOUNT OFF. DELETED. UPDATE TOP (10) HumanResources. is defined on the Employee table. SET @Sales = 2000000. DECLARE a variable of type table The following example creates a table variable that stores the values specified in the OUTPUT clause of the UPDATE statement. ModifiedDate datetime). SELECT EmpID.VacationHours. SELECT FirstName.vSalesPerson WHERE TerritoryGroup = @Group and SalesYTD >= @Sales.Handout . OldVacationHours int. OldVacationHours. This is because the AFTER UPDATE trigger. Two SELECT statements follow that return the values in @MyTableVar and the results of the update operation in the Employee table.000 in sales for the year. SalesYTD FROM Sales. NewVacationHours int. INSERTED.ModifiedDate column are different from the values in the ModifiedDate column in the Employee table.
ModifiedDate FROM HumanResources. All Rights Reserved C3: Protected .Employee. The searched CASE function evaluates a set of Boolean expressions to determine the result. GO Summary Transact-SQL provides special words called control-of-flow language that control the flow of execution of Transact-SQL statements. CASE has two formats Both formats support an optional ELSE argument: o o The simple CASE function compares an expression to a set of simple expressions to determine the result. WHILE construct sets condition for the repeated execution of an SQL statement or statement block. Cognizant Technology Solutions. VacationHours. WAITFOR blocks the execution of a batch. Page 109 ©Copyright 2007.SQL Server 2005 SELECT TOP (10) EmployeeID.Handout . stored procedure or transaction until a specified time or time interval is reached.
These applications need a mechanism to work with one row or a small block of rows at a time. Supporting different levels of visibility to changes made by other users to the database data that is presented in the result set. Database application programming interface (API) cursor functions SQL Server supports the cursor functionality of these database APIs: ADO (Microsoft ActiveX Data Object) OLE DB ODBC (Open Database Connectivity) An application should never mix these two methods of requesting a cursor. Applications. especially interactive online applications. stored procedures. Requesting a Cursor Microsoft SQL Server 2005 supports two methods for requesting a cursor: Transact-SQL : The Transact-SQL language supports a syntax for using cursors modeled after the SQL-92 cursor syntax. An application that has used the API to specify cursor behaviors should not then execute a Transact-SQL DECLARE CURSOR statement to also request a Transact-SQL cursor.SQL Server 2005 Session 21: Cursors Learning Objectives After completing this session. cannot always work effectively with the entire result set as a unit. and triggers access to the data in a result set. This complete set of rows returned by the statement is known as the result set. you will be able to: Identify cursors and cursor types Apply cursors Cursors Operations in a relational database act on a complete set of rows. All Rights Reserved C3: Protected . Providing Transact-SQL statements in scripts. Retrieving one row or block of rows from the current position in the result set. The set of rows returned by a SELECT statement consists of all the rows that satisfy the conditions in the WHERE clause of the statement. Page 110 ©Copyright 2007. Cursors are an extension to result sets that provide that mechanism. Cursors extend result processing by: Allowing positioning at specific rows of the result set. Cognizant Technology Solutions. Supporting data modifications to the rows at the current position in the result set.Handout . An application should only execute DECLARE CURSOR if it has set all the API cursor attributes back to their defaults.
Additional cursor types: If the SQL Native Client ODBC driver used only client cursors. Retrieve the rows in the cursor you want to see. 4. simulate positioned cursor updates by generating a Transact-SQL searched UPDATE statement. depends on the schema of the underlying tables. Any schema changes to those tables after a cursor has been declared results in an error on any subsequent operation on that cursor. Close the cursor. Cursor Process Transact-SQL cursors and API cursors have different syntax. The operation of all server cursors. More accurate positioned updates: Server cursors directly support positioned operations. it could support only forward-only and static cursors. SQL Server also supports the full range of cursor concurrency attributes only through server cursors. Cognizant Technology Solutions.Handout . All Rights Reserved C3: Protected . except static or insensitive cursors. on the other hand. Execute the Transact-SQL statement to populate the cursor. 2.SQL Server 2005 If neither a Transact-SQL nor API cursor has been requested. Page 111 ©Copyright 2007. By using API server cursors the driver can also support keyset-driven and dynamic cursors. Client cursors are limited in the functionality they support. which leads to unintended updates if more than one row matches the WHERE clause conditions of the UPDATE statement. using server cursors provides optimal performance because only fetched data is sent over the network. 3. to the application. The operation to retrieve one row or one block of rows from a cursor is called a fetch. This allows you to have multiple cursor-based statements active at the same time. Optionally. Server Cursor Advantage Server Cursors versus Client Cursors: There are several advantages to using server cursors instead of client cursors: Performance: If you are going to access a fraction of the data in the cursor (typical of many browsing applications). but the following general process is used with all SQL Server cursors: 1. Client cursors. perform modification operations (update or delete) on the row at the current position in the cursor. Multiple active statements: When using server cursors. such as the ODBC SQLSetPos function or UPDATE and DELETE statements with the WHERE CURRENT OF clause. Memory usage: When using server cursors. no results are left outstanding on the connection between cursor operations. and define characteristics of the cursor. Client cursors cache the entire result set on the client. Associate a cursor with the result set of a Transact-SQL statement. SQL Server defaults to returning a complete result set. Performing a series of fetches to retrieve rows in either a forward or backward direction is called scrolling. such as whether the rows in the cursor can be updated. the client does not need to cache large amounts of data or maintain information about the cursor position because the server does that. 5. known as a default result set.
the SET statement is used. FETCH statement. although they make the lightest use of tempdb. Dynamic cursors detect all changes but consume more resources while scrolling. Locks are not acquired on the rows until they have been fetched. All Rights Reserved C3: Protected . OPEN statement. Cursor variables can be declared with the DECLARE statement and used with other cursor-related statements. These cursors also differ on the types of locks used: Static cursors retrieve the entire result set at the time the cursor is opened. These cursors also vary in their ability to detect changes to the result set and in the resources. SQL Cursor Variables SQL Server 2005 allows declaring variables with a type of cursor. although they store the entire cursor in tempdb. SET CURSOR variable statement (on the right side). Fast forward-only cursors vary in when they acquire their locks depending on the execution plan chosen by the query optimizer. DEALLOCATE statement. Cursors variables cannot be assigned a value with an assignment SELECT. they consume. This locks each row of the result set at open time. Positioned DELETE or UPDATE statement. such as memory and space in tempdb.Handout . Cursor variables can be used to declare any type of cursor. A cursor variable that currently has a cursor assigned to it can be referenced as a source in a: CLOSE statement. Page 112 ©Copyright 2007. no locks are taken until the rows are fetched. If a dynamic plan is chosen. A cursor can detect changes to rows only when it attempts to fetch those rows a second time. There is no way for the data source to notify the cursor of changes to the currently fetched rows. Static cursors detect few or no changes but consume relatively few resources while scrolling. then the rows are read into the worktable and locked at open time. To assign a cursor to a cursor variable.SQL Server 2005 TSQL Cursors The four cursor types for Transact-SQL cursors are: Static cursors Dynamic cursors Forward-only cursors Keyset-driven cursors These cursors differ primarily in how changes to underlying data are handled. The ability of a cursor to detect changes is also influenced by the transaction isolation level. If worktables are generated. This locks each row of the result set at open time. Keyset-driven cursors retrieve the keys of each row of the result set at the time the cursor is opened. Keyset-driven cursors lie in between. Cursor variables store a reference to a cursor definition. Dynamic cursors (including regular forward-only cursors) do not retrieve rows until they are fetched. Cognizant Technology Solutions. detecting most changes but at less expense than dynamic cursors.
FirstName. SELECT FirstName. GO SET NOCOUNT ON. Phone FROM Person. SELECT LastName.000 in sales for the year. SalesYTD FROM Sales. Use DECLARE with two variables The following example retrieves the names of Adventure Works Cycles sales representatives who are located in the North American sales territory and have at least $2.Contact WHERE LastName LIKE @find.Handout . Should be regarded as a pointer to the cursor. GO DECLARE @find varchar(30). SQL Server raises the same error raised for an undeclared variable of another type. such as its scrolling behavior and the query used to build the result set on which the cursor operates. Can be referenced as the target of an output cursor parameter in an EXECUTE statement if the cursor variable does not have a cursor currently assigned to it. SET @Sales = 2000000. USE AdventureWorks. GO DECLARE @Group nvarchar(50). Page 113 ©Copyright 2007.SQL Server 2005 In all these statements. DECLARE CURSOR accepts both a syntax based on the SQL-92 standard and a syntax using a set of Transact-SQL extensions. USE AdventureWorks.000. SET @Group = N'North America'. DECLARE CURSOR Defines the attributes of a Transact-SQL server cursor. SET @find = 'Man%'. Cognizant Technology Solutions. If a referenced cursor variable does not exist. Examples: Using DECLARE The following example uses a local variable named @find to retrieve contact information for all last names beginning with 'Man'. SET NOCOUNT OFF. All Rights Reserved C3: Protected . @Sales money. Microsoft SQL Server raises an error if a referenced cursor variable exists but does not have a cursor currently allocated to it.vSalesPerson WHERE TerritoryGroup = @Group and SalesYTD >= @Sales. LastName. A cursor variable: Can be the target of either a cursor type or another cursor variable.
For more information.n] is specified.. All requests to the cursor are answered from this temporary table in tempdb....] Transact-SQL Extended Syntax DECLARE cursor_name CURSOR[ LOCAL | GLOBAL ][ FORWARD_ONLY | SCROLL ][ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ][ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ][ TYPE_WARNING ]FOR select_statement[ FOR UPDATE [ OF column_name [ . When SQL-92 syntax is used.. if INSENSITIVE is omitted. NEXT. and INTO are not allowed within select_statement of a cursor declaration. all columns can be updated. ABSOLUTE) are available. cursor_name must conform to the rules for identifiers. RELATIVE. FOR BROWSE. If SCROLL is not specified in an SQL-92 DECLARE CURSOR.. All Rights Reserved C3: Protected . Microsoft SQL Server implicitly converts the cursor to another type if clauses in select_statement conflict with the functionality of the requested cursor type.Handout . therefore...n ] ] ] [.. and this cursor does not allow modifications. Page 114 ©Copyright 2007. only the columns listed allow modifications. committed deletes and updates made to the underlying tables (by any user) are reflected in subsequent fetches.n ] ] } ] [. SCROLL: Specifies that all fetch options (FIRST.. see Using Implicit Cursor Conversions. The cursor cannot be referenced in a WHERE CURRENT OF clause in an UPDATE or DELETE statement. For more information about rules for identifiers. UPDATE [OF column_name [. modifications made to base tables are not reflected in the data returned by fetches made to this cursor. The keywords COMPUTE. LAST... This option overrides the default capability of a cursor to be updated. COMPUTE BY. If OF column_name [. If UPDATE is specified without a column list. SCROLL cannot be specified if FAST_FORWARD is also specified. Cognizant Technology Solutions.n]]: Defines updatable columns within the cursor. NEXT is the only fetch option supported. PRIOR. INSENSITIVE: Defines a cursor that makes a temporary copy of the data to be used by the cursor.SQL Server 2005 Syntax: SQL 92 Syntax DECLARE cursor_name [ INSENSITIVE ] [ SCROLL ] CURSOR FOR select_statement [ FOR { READ ONLY | UPDATE [ OF column_name [ . see Using Identifiers as Object Names.] Arguments: cursor_name: Is the name of the Transact-SQL server cursor defined. select_statement: Is a standard SELECT statement that defines the result set of the cursor. READ ONLY: Prevents updates made through this cursor.
KEYSET. unless the keywords STATIC. Updates of key values from outside the cursor resemble a delete of the old row followed by an insert of the new row. Cognizant Technology Solutions. stored procedure. The set of keys that uniquely identify the rows is built into a table in tempdb known as the keyset. All requests to the cursor are answered from this temporary table in tempdb. KEYSET. or DYNAMIC are specified. KEYSET: Specifies that the membership and order of rows in the cursor are fixed when the cursor is opened. FORWARD_ONLY is the default. or a stored procedure OUTPUT parameter. stored procedure. and attempts to fetch the row with the old values return an @@FETCH_STATUS of -2. Unlike database APIs such as ODBC and ADO. LOCAL: Specifies that the scope of the cursor is local to the batch. and membership of the rows can change on each fetch. Page 115 ©Copyright 2007. FETCH NEXT is the only supported fetch option. or DYNAMIC keywords. cursor_name must conform to the rules for identifiers. The ABSOLUTE fetch option is not supported with dynamic cursors. order. and this cursor does not allow modifications. either made by the cursor owner or committed by other users. the cursor operates as a DYNAMIC cursor. An OUTPUT parameter is used to pass the local cursor back to the calling batch. Inserts made by other users are not visible (inserts cannot be made through a Transact-SQL server cursor). The data values. The new values are visible if the update is done through the cursor by specifying the WHERE CURRENT OF clause. KEYSET. If it is passed back in an OUTPUT parameter.SQL Server 2005 cursor_name: Is the name of the Transact-SQL server cursor defined. an attempt to fetch the row returns an @@FETCH_STATUS of -2. see Using Identifiers as Object Names. The cursor name can be referenced in any stored procedure or batch executed by the connection. stored procedure. DYNAMIC: Defines a cursor that reflects all data changes made to the rows in its result set as you scroll around the cursor. Changes to nonkey values in the base tables. unless the cursor was passed back in an OUTPUT parameter. modifications made to base tables are not reflected in the data returned by fetches made to this cursor. or trigger terminates. If a row is deleted. therefore. For more information about rules for identifiers. If FORWARD_ONLY is specified without the STATIC. and DYNAMIC Transact-SQL cursors. which can assign the parameter to a cursor variable to reference the cursor after the stored procedure terminates. FORWARD_ONLY: Specifies that the cursor can only be scrolled from the first to the last row. The cursor is implicitly deallocated when the batch. The cursor can be referenced by local cursor variables in the batch. STATIC. The cursor is only implicitly deallocated at disconnect. are visible as the owner scrolls around the cursor. or trigger in which the cursor was created. the cursor is deallocated when the last variable referencing it is deallocated or goes out of scope. and DYNAMIC cursors default to SCROLL. The row with the new values is not visible. FORWARD_ONLY is supported with STATIC. All Rights Reserved C3: Protected . When neither FORWARD_ONLY nor SCROLL is specified. KEYSET. The cursor name is only valid within this scope. STATIC: Defines a cursor that makes a temporary copy of the data to be used by the cursor. stored procedure. or trigger. or trigger.Handout . GLOBAL: Specifies that the scope of the cursor is global to the connection.
SQL Server implicitly converts the cursor to another type if clauses in select_statement conflict with the functionality of the requested cursor type. It instead uses comparisons of timestamp column values. SCROLL_LOCKS cannot be specified if FAST_FORWARD is also specified.. This option overrides the default capability of a cursor to be updated. Examples: Use simple cursor and syntax: The result set generated at the opening of this cursor includes all rows and all columns in the table. and all updates and deletes are represented in fetches made against this cursor. TYPE_WARNING: Specifies that a warning message is sent to the client if the cursor is implicitly converted from the requested type to another. READ_ONLY cursor with performance optimizations enabled.n]]: Defines updatable columns within the cursor. FAST_FORWARD cannot be specified if SCROLL or FOR_UPDATE is also specified. and INTO are not allowed within select_statement of a cursor declaration..Handout . FOR BROWSE. OPTIMISTIC: Specifies that positioned updates or deletes made through the cursor do not succeed if the row has been updated since it was read into the cursor. unless the READ_ONLY concurrency option was specified. FETCH NEXT is the only fetch available because the SCROLL option has not been specified.n] is supplied. This cursor can be updated. only the columns listed allow modifications. COMPUTE BY. The cursor cannot be referenced in a WHERE CURRENT OF clause in an UPDATE or DELETE statement..Vendor OPEN vend_cursor FETCH NEXT FROM vend_cursor Page 116 ©Copyright 2007. If the row was modified. or a checksum value if the table has no timestamp column. All Rights Reserved C3: Protected . DECLARE vend_cursor CURSOR FOR SELECT * FROM Purchasing. to determine whether the row was modified after it was read into the cursor. If OF column_name [. the attempted positioned update or delete fails.. The keywords COMPUTE. OPTIMISTIC cannot be specified if FAST_FORWARD is also specified. FOR UPDATE [OF column_name [. SQL Server does not lock rows as they are read into the cursor. Cognizant Technology Solutions. SCROLL_LOCKS: Specifies that positioned updates or deletes made through the cursor are guaranteed to succeed.SQL Server 2005 FAST_FORWARD: Specifies a FORWARD_ONLY.. For more information. READ_ONLY: Prevents updates made through this cursor. all columns can be updated. select_statement: Is a standard SELECT statement that defines the result set of the cursor.. Microsoft SQL Server locks the rows as they are read into the cursor to ensure their availability for later modifications. see Implicit Cursor Conversions. If UPDATE is specified without a column list.
Name FROM Purchasing.Handout .Variable value from the outer cursor OPEN product_cursor FETCH NEXT FROM product_cursor INTO @product IF @@FETCH_STATUS <> 0 PRINT ' <<None>>' Page 117 ©Copyright 2007.Product v WHERE pv.Declare an inner cursor based -.SQL Server 2005 Use nested cursors to produce report output This example shows how cursors can be nested to produce complex reports.Name FROM Purchasing. DECLARE product_cursor CURSOR FOR SELECT v. The inner cursor is declared for each vendor.ProductID = v.on vendor_id from the outer cursor. @message varchar(80). SET NOCOUNT ON DECLARE @vendor_id int. @vendor_name WHILE @@FETCH_STATUS = 0 BEGIN PRINT ' ' SELECT @message = '----. All Rights Reserved C3: Protected .Products From Vendor: ' + @vendor_name PRINT @message -. @vendor_name nvarchar(50). @product nvarchar(50) PRINT '-------.VendorID = @vendor_id-.Vendor Products Report --------' DECLARE vendor_cursor CURSOR FOR SELECT VendorID. Production.ProductVendor pv.Vendor WHERE PreferredVendorStatus = 1 ORDER BY VendorID OPEN vendor_cursor FETCH NEXT FROM vendor_cursor INTO @vendor_id.ProductID AND pv. Cognizant Technology Solutions.
Cognizant Technology Solutions.HumanResources. FirstName FROM AdventureWorks. If both a global and a local cursor exist with cursor_name as their name.Handout .Get the next vendor. DECLARE Employee_Cursor CURSOR FOR SELECT LastName. Page 118 ©Copyright 2007. cursor_variable_name: Is the name of a cursor variable that references a cursor. cursor_name refers to the global cursor if GLOBAL is specified. FETCH NEXT FROM vendor_cursor INTO @vendor_id. Examples: The following example opens a cursor and fetches all the rows. cursor_name refers to the local cursor. otherwise.SQL Server 2005 WHILE @@FETCH_STATUS = 0 BEGIN SELECT @message = ' ' + @product PRINT @message FETCH NEXT FROM product_cursor INTO @product END CLOSE product_cursor DEALLOCATE product_cursor -.vEmployee WHERE LastName like 'B%'. OPEN Employee_Cursor. cursor_name: Is the name of a declared cursor. @vendor_name END CLOSE vendor_cursor DEALLOCATE vendor_cursor Opening cursor OPEN opens a Transact-SQL server cursor and populates the cursor by executing the TransactSQL statement specified on the DECLARE CURSOR or SET cursor_variable statement. All Rights Reserved C3: Protected . Syntax: OPEN { { [ GLOBAL ] cursor_name } | cursor_variable_name } Arguments: GLOBAL: Specifies that cursor_name refers to a global cursor.
LAST: Returns the last row in the cursor and makes it the current row. Fetching cursor The operation to retrieve a row from a cursor is called a fetch. Cognizant Technology Solutions. or int. If FETCH NEXT is the first fetch against a cursor. n must be an integer constant and @nvar must be smallint. Syntax: FETCH [ [ NEXT | PRIOR | FIRST | LAST | ABSOLUTE { n | @nvar } | RELATIVE { n | @nvar } ] FROM ] { { [ GLOBAL ] cursor_name } | @cursor_variable_name } [ INTO @variable_name [ . All Rights Reserved C3: Protected . The FETCH keyword is used to retrieve specific rows from a cursor. ABSOLUTE { n | @nvar}: If n or @nvar is positive. FIRST : Returns the first row in the cursor and makes it the current row. it returns the first row in the result set. PRIOR: Returns the result row immediately preceding the current row. DEALLOCATE Employee_Cursor. and decrements the current row to the row returned. NEXT is the default cursor fetch option. If FETCH PRIOR is the first fetch against a cursor. tinyint. no rows are returned..Handout . If n or @nvar is 0..n ] ] Arguments: NEXT: Returns the result row immediately following the current row and increments the current row to the row returned. returns the row n rows from the front of the cursor and makes the returned row the new current row. If n or @nvar is negative. no row is returned and the cursor is left positioned before the first row.. CLOSE Employee_Cursor. returns the row n rows before the end of the cursor and makes the returned row the new current row. Page 119 ©Copyright 2007. WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM Employee_Cursor END.SQL Server 2005 FETCH NEXT FROM Employee_Cursor.
FETCH NEXT FROM contact_cursor -.SQL Server 2005 RELATIVE { n | @nvar}: If n or @nvar is positive. If n or @nvar is negative. cursor_name to the global cursor if GLOBAL is specified and to the local cursor if GLOBAL is not specified. returns the current row. @cursor_variable_name: Is the name of a cursor variable referencing the open cursor from which the fetch should be made..Contact WHERE LastName LIKE 'B%' ORDER BY LastName OPEN contact_cursor -. FETCH NEXT FROM contact_cursor END Page 120 ©Copyright 2007. is associated with the corresponding column in the cursor result set. and uses FETCH NEXT to step through the rows.Check @@FETCH_STATUS to see if there are any more rows to fetch.Handout .Contact table with a last name beginning with B. returns the row n rows prior to the current row and makes the returned row the new current row. WHILE @@FETCH_STATUS = 0 BEGIN -. If both a global and a local cursor exist with cursor_name as their name. tinyint. The FETCH statements return the value for the column specified in the DECLARE CURSOR as a single-row result set. The number of variables must match the number of columns in the cursor select list. Each variable in the list. If n or @nvar is 0. GLOBAL: Specifies that cursor_name refers to a global cursor. from left to right. Cognizant Technology Solutions. cursor_name: Is the name of the open cursor from which the fetch should be made. returns the row n rows beyond the current row and makes the returned row the new current row. no rows are returned. If FETCH RELATIVE is specified with n or @nvar set to negative numbers or 0 on the first fetch done against a cursor.This is executed as long as the previous fetch succeeds. USE AdventureWorks GO DECLARE contact_cursor CURSOR FOR SELECT LastName FROM Person. INTO @variable_name[ .Perform the first fetch. n must be an integer constant and @nvar must be smallint... All Rights Reserved C3: Protected . or int. The data type of each variable must either match or be a supported implicit conversion of the data type of the corresponding result set column.n]: Allows data from the columns of a fetch to be placed into local variables. Examples: Use FETCH in a simple cursor: This example declares a simple cursor for the rows in the Person.
FETCH NEXT FROM contact_cursor INTO @LastName. @FirstName varchar(50) DECLARE contact_cursor CURSOR FOR SELECT LastName. DECLARE @LastName varchar(50). FirstName FROM Person. WHILE @@FETCH_STATUS = 0 BEGIN -.This is executed as long as the previous fetch succeeds. @FirstName -.SQL Server 2005 CLOSE contact_cursor DEALLOCATE contact_cursor GO Use FETCH to store values in variables : This example is similar to the last example. Cognizant Technology Solutions. PRINT 'Contact Name: ' + @FirstName + ' ' + @LastName -. except the output of the FETCH statements is stored in local variables rather than being returned directly to the client. The PRINT statement combines the variables into a single string and returns them to the client. FirstName OPEN contact_cursor -.Note: The variables are in the same order as the columns -. @FirstName END CLOSE contact_cursor DEALLOCATE contact_cursor GO Page 121 ©Copyright 2007. FETCH NEXT FROM contact_cursor INTO @LastName.Check @@FETCH_STATUS to see if there are any more rows to fetch. USE AdventureWorks GO -. All Rights Reserved C3: Protected .Handout .Perform the first fetch and store the values in variables.Contact WHERE LastName LIKE 'B%' ORDER BY LastName.Concatenate and display the current values in the variables. -.in the SELECT statement.Declare the variables to store the values returned by FETCH.
All Rights Reserved C3: Protected .Declare the cursor. but fetches and positioned updates are not allowed until the cursor is reopened.Contact ORDER BY LastName. CLOSE is not allowed on cursors that have only been declared or are already closed. CLOSE must be issued on an open cursor. RELATIVE. FirstName FROM Person. FirstName OPEN contact_cursor -.Fetch the last row in the cursor. SELECT LastName. FETCH ABSOLUTE 2 FROM contact_cursor -. FETCH PRIOR FROM contact_cursor -. DECLARE contact_cursor SCROLL CURSOR FOR SELECT LastName. and ABSOLUTE options.Execute the SELECT statement alone to show the -. CLOSE leaves the data structures available for reopening.SQL Server 2005 Declare a SCROLL cursor and use the other FETCH options : This example creates a SCROLL cursor to allow full scrolling capabilities through the LAST. FETCH RELATIVE 3 FROM contact_cursor -. Page 122 ©Copyright 2007. FirstName FROM Person.full result set that is used by the cursor.Fetch the row that is three rows after the current row. FETCH RELATIVE -2 FROM contact_cursor CLOSE contact_cursor DEALLOCATE contact_cursor GO Closing Cursor CLOSE closes an open cursor by releasing the current result set and freeing any cursor locks held on the rows on which the cursor is positioned. PRIOR. USE AdventureWorks GO -. FirstName -.Fetch the row that is two rows prior to the current row. FETCH LAST FROM contact_cursor -.Fetch the second row in the cursor.Contact ORDER BY LastName. Cognizant Technology Solutions.Handout .Fetch the row immediately prior to the current row in the cursor.
When the last cursor reference is deallocated. If both a global and a local cursor exist with cursor_name as their name. otherwise. cursor_variable_name: Is the name of a cursor variable associated with an open cursor. the data structures comprising the cursor are released by Microsoft SQL Server. @cursor_variable_name: Is the name of a cursor variable. Deallocating Cursors DEALLOCATE removes a cursor reference. cursor_name refers to the local cursor. Cognizant Technology Solutions. Syntax: DEALLOCATE { { [ GLOBAL ] cursor_name } | @cursor_variable_name } Arguments: cursor_name: Is the name of an already declared cursor.SQL Server 2005 Syntax: CLOSE { { [ GLOBAL ] cursor_name } | cursor_variable_name } Arguments: GLOBAL : Specifies that cursor_name refers to a global cursor. keyset cursors are worse for performance o Slower as the entire result set needs to be rebuilt o Take up TempDB space SQL Server is inherently a set-based database o Always more efficient to manipulate data as a set Page 123 ©Copyright 2007. @cursor_variable_name must be of type cursor. cursor_name refers to the global cursor when GLOBAL is specified. cursor_name refers to the global cursor if GLOBAL is specified and to the local cursor if GLOBAL is not specified. If both a global and a local cursor exist with cursor_name as their name. Cursor: Disadvantages Disadvantages of cursor are stated as follows: Individually row processing is very inefficient Default result sets are preferable most of the time Static. cursor_name: Is the name of an open cursor. All Rights Reserved C3: Protected .Handout .
a cursor usage can be replaced by an equivalent set based statement Page 124 ©Copyright 2007.Handout . read-only. and forward-only cursors Cursors are much slower than set based statements In most situations. Cognizant Technology Solutions.SQL Server 2005 Summary Cursors are used for row by row processing operations SQL Server 2005 has a rich set of cursor types You can define static. dynamic. All Rights Reserved C3: Protected .
Contain programming statements that perform operations in the database. and certificates can be attached to them. Cognizant Technology Solutions. you will be able to: Define Stored Procedure Identify the types of Stored Procedures Create Stored Procedures Create Stored Procedures using WITH RECOMPILE option Creating Stored Procedures using WITH ENCRYPTION option Describe System Stored Procedures Explain Error Handling Describe CLR Integration Explain CLR Procedures Write EXECUTE AS clause Stored Procedure Stored procedures in Microsoft SQL Server are similar to procedures in other programming languages in that they can: Accept input parameters and return multiple values in the form of output parameters to the calling procedure or batch. and call it any number of times in your program. The benefits of using stored procedures in SQL Server rather than Transact-SQL programs stored locally on client computers are: They are registered at the server. All Rights Reserved C3: Protected .Handout . Parameterized stored procedures can help protect your application from SQL Injection attacks. They can have security attributes (such as permissions) and ownership chaining. You can use the Transact-SQL EXECUTE statement to run a stored procedure.SQL Server 2005 Session 23: Stored Procedures Learning Objectives After completing this session. They allow modular programming. including calling other procedures. Users can be granted permission to execute a stored procedure without having to have direct permissions on the objects referenced in the procedure. Page 125 ©Copyright 2007. For more information see SQL Injection. Return a status value to a calling procedure or batch to indicate success or failure (and the reason for failure). You can create the procedure once. This can improve the maintainability of your application and allow applications to access the database in a uniform manner. They can enhance the security of your application. Stored procedures are different from functions in that they do not return values in place of their names and they cannot be used directly in an expression.
GRANT. This topic briefly describes each stored procedure type and includes an example of each. System Stored Procedures: o Many administrative activities in SQL Server 2005 are performed through a special kind of procedure known as a system stored procedure. System stored procedures logically appear in the sys schema of every system. They can reduce network traffic. and return output parameters. Extended stored procedures are DLLs that an instance of Microsoft SQL Server can dynamically load and run. In SQL Server 2005.SQL Server 2005 They are named code allowing for delayed binding. For a complete list of extended stored procedures. This provides a level of indirection for easy code evolution. see General Extended Stored Procedures (Transact-SQL). Extended Stored Procedures: Extended stored procedures let you create your own external routines in a programming language such as C. Cognizant Technology Solutions. return tabular or scalar results and messages to the client. o SQL Server supports the system stored procedures that provide an interface from SQL Server to external programs for various maintenance activities. sys. System stored procedures are physically stored in the Resource database and have the sp_ prefix. A stored procedure can take input parameters. For example. Transact-SQL: A Transact-SQL stored procedure is a saved collection of TransactSQL statements that can take and return user-supplied parameters. All Rights Reserved C3: Protected . For example.sp_changedbowner is a system stored procedure. see System Stored Procedures (Transact-SQL). DENY. For more information. Extended stored procedures run directly in the address space of an instance of SQL Server and are programmed by using the SQL Server Extended Stored Procedure API. see CLR Stored Procedures. invoke data definition language (DDL) and data manipulation language (DML) statements.Handout . an e-commerce Web application might use a stored procedure to return information about specific products based on search criteria specified by the online user. a stored procedure might contain the statements needed to insert a new row into one or more tables based on information supplied by the client application. An operation requiring hundreds of lines of TransactSQL code can be performed through a single statement that executes the code in a procedure.NET Framework common language runtime (CLR) method that can take and return user-supplied parameters. CLR: A CLR stored procedure is a reference to a Microsoft . In SQL Server 2005. They are implemented as public. Types of Stored Procedures There are many types of stored procedures available in Microsoft SQL Server 2005. Or. For a complete list of system stored procedures.NET Framework assembly. These extended stored procedures use the xp_ prefix. static methods on a class in a . User-defined Stored Procedures: Stored procedures are modules or routines that encapsulate code for reuse.and user-defined database. a stored procedure can be of two types: TransactSQL or CLR. the stored procedure might return data from the database to the client application. Page 126 ©Copyright 2007. rather than by sending hundreds of lines of code over the network. For example. and REVOKE permissions can be applied to system stored procedures.
ENCRYPTION indicates that SQL Server will convert the original text of the CREATE PROCEDURE statement to an obfuscated format. Cognizant Technology Solutions. can be created with the # and ## prefixes added to the procedure name.n ] [ WITH <procedure_option> [ . ] data_type } [ VARYING ] [ = default ] [ [ OUT [ PUT ] ] [ . This stored procedure does not use any parameters. which are created for replication cannot be executed on the Subscriber. EXECUTE AS specifies the security context under which to execute the stored procedure.. These procedures do not exist after SQL Server is shut down. number ] [ { @parameter [ type_schema_name...n ] [ FOR REPLICATION ] AS { <sql_statement> [. The output of the obfuscation is not directly visible in any of the catalog views in SQL Server 2005.] procedure_name [ . and their department names from a view. their titles..SQL Server 2005 Temporary Stored Procedures: Private and global temporary stored procedures. Page 127 ©Copyright 2007.Handout .] <procedure_option> ::= [ ENCRYPTION ] [ RECOMPILE ] [ EXECUTE_AS_Clause ] Arguments: VARYING specifies the result set supported as an output parameter.. All Rights Reserved C3: Protected . analogous to temporary tables. Creating Stored Procedures Use CREATE PROCEDURE statement to create procedures Syntax: CREATE { PROC | PROCEDURE } [schema_name. Examples: Using a simple procedure with a complex SELECT: The following stored procedure returns all employees (first and last names supplied)... RECOMPILE indicates that the Database Engine does not cache a plan for this procedure and the procedure is compiled at run time.n ] | <method_specifier> } [. This parameter is dynamically constructed by the stored procedure and its contents may vary and applies only to cursor parameters. OUTPUT indicates that the parameter is an output parameter. # denotes a local temporary stored procedure. FOR REPLICATION specifies that stored procedures. ## denotes a global temporary stored procedure.][ ..
Handout .usp_GetEmployees @lastname varchar(40).usp_GetAllEmployees AS SELECT LastName.usp_GetEmployees 'Ackerman'. GO IF OBJECT_ID ( 'HumanResources. FirstName.usp_GetEmployees. 'P' ) IS NOT NULL DROP PROCEDURE HumanResources.Or. GO -. Using a simple procedure with parameters: The following stored procedure returns only the specified employee (first and last name supplied). GO -.usp_GetAllEmployees'.Or EXEC HumanResources.vEmployeeDepartment WHERE FirstName = @firstname AND LastName = @lastname. her title.usp_GetEmployees @lastname = 'Ackerman'. Cognizant Technology Solutions. 'Pilar'. if this procedure is the first statement within a batch: HumanResources. GO The usp_GetEmployees stored procedure can be executed in the following ways: EXECUTE HumanResources.vEmployeeDepartment. -. 'P' ) IS NOT NULL DROP PROCEDURE HumanResources. Page 128 ©Copyright 2007. GO CREATE PROCEDURE HumanResources.SQL Server 2005 USE AdventureWorks. @firstname = 'Pilar'.usp_GetAllEmployees.usp_GetAllEmployees. GO CREATE PROCEDURE HumanResources. USE AdventureWorks.Or EXEC HumanResources. and her department name from a view. JobTitle.usp_GetAllEmployees. Department FROM HumanResources. This stored procedure accepts exact matches for the parameters passed. All Rights Reserved C3: Protected .usp_GetEmployees'. GO The usp_GetEmployees stored procedure can be executed in these ways: EXECUTE HumanResources. Department FROM HumanResources. @firstname varchar(20) AS SELECT LastName. FirstName.usp_GetAllEmployees. JobTitle. GO IF OBJECT_ID ( 'HumanResources.
Or EXECUTE HumanResources. GO CREATE PROCEDURE HumanResources. Cognizant Technology Solutions. HumanResources.usp_GetEmployees 'Ackerman'. This stored procedure pattern matches the parameters passed or. JobTitle. if not supplied. uses the preset default (last names that start with the letter D).usp_GetEmployees2 @lastname varchar(40) = 'D%'. 'P' ) IS NOT NULL DROP PROCEDURE HumanResources. if this procedure is the first statement within a batch: HumanResources. @lastname = 'Ackerman'.Or EXECUTE -.Or EXECUTE -. -. GO The usp_GetEmployees2 stored procedure can be executed in many combinations. @firstname varchar(20) = '%' AS SELECT LastName. FirstName. HumanResources.usp_GetEmployees2. Using a simple procedure with wildcard parameters: The following stored procedure returns only the specified employees (first and last names supplied).usp_GetEmployees2 @firstname = '%'. Department FROM HumanResources.usp_GetEmployees2. 'Pilar'.Or EXECUTE -.Or EXECUTE HumanResources. 'S%'. Only a few combinations are shown here: EXECUTE HumanResources.usp_GetEmployees2 'Hesse'. GO IF OBJECT_ID ( 'HumanResources.usp_GetEmployees2'. USE AdventureWorks. GO -. their titles.usp_GetEmployees @firstname = 'Pilar'.Or. 'Stefen'. HumanResources. All Rights Reserved C3: Protected .usp_GetEmployees2 '[CK]ars[OE]n'.Handout .SQL Server 2005 GO -.usp_GetEmployees2 'H%'.Or EXECUTE -. Page 129 ©Copyright 2007. HumanResources. and their departments from a view.usp_GetEmployees2 'Wi%'.vEmployeeDepartment WHERE FirstName LIKE @firstname AND LastName LIKE @lastname.
@compareprice OUT. a batch.Handout .ProductSubcategoryID WHERE s.ProductSubcategoryID = s. OUTPUT parameters allow an external procedure. @maxprice money . The example shows using multiple SELECT statements and multiple OUTPUT parameters.SQL Server 2005 Using OUTPUT parameters: The following example creates the usp_GetList stored procedure.Populate the output variable @compareprice.Populate the output variable @listprice. which returns a list of products that have prices that do not exceed a specified amount. GO IF OBJECT_ID ( 'Production. -.ListPrice AS 'List Price' FROM Production. p. -. SET @listprice = (SELECT MAX(p. @compareprice money OUTPUT . @cost OUTPUT IF @cost <= @compareprice BEGIN PRINT 'These products can be purchased for less than $'+RTRIM(CAST(@compareprice AS varchar(20)))+'.ListPrice < @maxprice). SET @compareprice = @maxprice. 'P' ) IS NOT NULL DROP PROCEDURE Production.ProductSubcategory s ON p.name AS Product. @cost money EXECUTE Production.ListPrice < @maxprice.ProductSubcategoryID = s.Product p JOIN Production.usp_GetList '%Bikes%'.usp_GetList.' END ELSE Page 130 ©Copyright 2007.ProductSubcategoryID WHERE s.usp_GetList @product varchar(40) . GO Execute usp_GetList to return a list of Adventure Works products (Bikes) that cost less than $700. or more than one Transact-SQL statement to access a value set during the procedure execution.ProductSubcategory s ON p. DECLARE @compareprice money. Cognizant Technology Solutions. @listprice money OUT AS SELECT p.name LIKE @product AND p.ListPrice) FROM Production.usp_GetList'. All Rights Reserved C3: Protected . 700.name LIKE @product AND p. The OUTPUT parameters @cost and @compareprices are used with control-of-flow language to return a message in the Messages window. USE AdventureWorks.Product p JOIN Production. GO CREATE PROCEDURE Production.
Creating a stored procedure that specifies the WITH RECOMPILE option in its definition indicates that SQL Server does not cache a plan for stored procedure.' Creating Stored Procedures WITH RECOMPILE option If database is changed by actions such as adding indexes or changing data in indexed columns.SQL Server 2005 PRINT 'The prices for all products in this category exceed $'+ RTRIM(CAST(@compareprice AS varchar(20)))+'.Name LIKE @name. The output of the obfuscation is not directly visible in any of the catalog views in SQL Server 2005. then the original query plans applied to access its tables should be optimized by recompiling them.VendorID JOIN Production. VacationHours.usp_encrypt_this'. All Rights Reserved C3: Protected . p.ProductID = p.Employee. 'P' ) IS NOT NULL DROP PROCEDURE HumanResources. Page 131 ©Copyright 2007. GO Creating Stored Procedures WITH ENCRYPTION option WITH ENCRYPTION indicates that SQL Server will convert the original text of the CREATE PROCEDURE statement to an obfuscated format.Vendor v JOIN Purchasing. GO CREATE PROCEDURE HumanResources. Cognizant Technology Solutions. GO IF OBJECT_ID ( 'HumanResources.ProductID WHERE v.VendorID = pv.usp_encrypt_this stored procedure.Name AS 'Vendor name'.usp_product_by_vendor @name varchar(30) = '%' WITH RECOMPILE AS SELECT v.usp_encrypt_this. Title.Product p ON pv.usp_encrypt_this WITH ENCRYPTION AS SELECT EmployeeID. Example: CREATE PROCEDURE dbo. Example: The following example creates the HumanResources. USE AdventureWorks. NationalIDNumber. SickLeaveHours FROM HumanResources. The stored procedure is recompiled each time it is executed.ProductVendor pv ON v.Name AS 'Product name' FROM Purchasing.Handout .
sp_stored_procedures Error Handling In SQL Server 2000 and earlier versions @@ERROR function is the primary means of detecting errors in T-SQL statements. Run sp_helptext: EXEC sp_helptext 'HumanResources.usp_encrypt_this'. All Rights Reserved C3: Protected .sql_modules catalog view: USE AdventureWorks. Cognizant Technology Solutions. as shown by the following examples.SQL Server 2005 GO The WITH ENCRYPTION option prevents the definition of the stored procedure from being returned.usp_encrypt_this' is encrypted. Try.Handout .usp_encrypt_this'). The SQL Server 2005 Database Engine introduces the TRY…CATCH blocks to implement structured exception handling.sql_modules WHERE object_id = OBJECT_ID('HumanResources. which provides improved functionality. GO SELECT definition FROM sys. Here is the result set. The text for object 'HumanResources. Directly query the sys. sp_tables. catch block provides the following structure: Page 132 ©Copyright 2007. Here is the result set.. definition ---------------------NULL (1 row(s) affected) System Stored Procedures System stored procedures installed by SQL Server for administrative and informative purposes: Reside on the master database Executable from any database: Takes execution context of current database Start with 'sp_' prefix: o o Example: sp_help. a system procedure that gives information on database objects Best practice: User procedures should not have this prefix Catalog procedures: Access and modify system tables o Examples are sp_databases.
ERROR_SEVERITY() returns the error severity. usp_AddData 1 . Cognizant Technology Solutions. ColB int) CREATE PROCEDURE dbo. or times. A Try…catch construct catches all execution errors with severity greater than 10 that do not terminate the database connection. Errors with severity from zero through 10 are informational messages and do not cause execution to jump from the catch block of a Try…catch construct. usp_AddData @a int . 3 --violates the primary key Try…catch uses error functions to capture error information: ERROR_NUMBER() returns the error number. ERROR_MESSAGE() returns the complete text of the error message. ERROR_MESSAGE() [Message] END CATCH EXEC dbo. Page 133 ©Copyright 2007. usp_AddData 2 . All Rights Reserved C3: Protected .SQL Server 2005 Try block contains protected transactions Catch block handles errors Syntax: BEGIN TRY { sql_statement | statement_block } END TRY BEGIN CATCH { sql_statement | statement_block } END CATCH Example: CREATE TABLE tbl_TestData( ColA int primary key.Handout . 2 EXEC dbo.@b int AS BEGIN TRY INSERT INTO tbl_TestData VALUES (@a. Database Engine Error Severities: When an error is raised by the SQL Server Database Engine. ERROR_LINE() returns the line number inside the routine that caused the error. the severity of the error indicates the type of problem encountered by SQL Server. 1 EXEC dbo. @b) END TRY BEGIN CATCH SELECT ERROR_NUMBER() ErrorNumber. usp_AddData 2 . ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error has occurred. The text includes the values supplied for any substitutable parameters such as lengths. ERROR_STATE() returns the error state number. object names. Error functions can only be applied inside the catch block.
NET language. Before the stored procedure is created. Creating a CLR stored procedure in SQL Server involves the following steps: Define the stored procedure as a static method of a class in a language supported by the . user-defined types. Benefits of Integration: o o Enhanced Programming mode: The .NET Framework. o CLR Procedures In SQL Server 2005. functions. Then.GetPhotoFromDB ( @ProductPhotoID int. All Rights Reserved C3: Protected . aggregate functions. GO CREATE PROCEDURE dbo. @CurrentDirectory nvarchar(1024). Enhanced safety and security: Managed code runs in CLR environment hosted by the SQL Server Database engine. For more information about how to program CLR stored procedures. compile the class to build an assembly in the . @FileName nvarchar(1024) ) Page 134 ©Copyright 2007. Performance and scalability: Managed code and managed execution can deliver improved performance over T-SQL in many situations. see CLR Stored Procedures. stored procedures. you can create a database object inside an instance of SQL Server that is programmed in an assembly created in the Microsoft . are not handled by the catch block because execution is aborted when the connection terminates.dll''. the HandlingLOBUsingCLR assembly is registered in the local database. and aggregates in any .Handout .NET languages offer richer development capabilities than T-SQL does. Including stored procedure. Register the assembly in SQL Server by using the CREATE ASSEMBLY statement. CLR Integration CLR Integration in SQL Server 2005 allows you to create managed objects. CREATE ASSEMBLY HandlingLOBUsingCLR FROM '\\MachineName\HandlingLOBUsingCLR\bin\Debug\HandlingLOBUsingCLR.NET Framework common language runtime (CLR). This provides a safer and more secure system than extended stored procedures do. Create the stored procedure that references the registered assembly by using the CREATE PROCEDURE statement. Database objects that can leverage the rich programming model provided by the CLR include triggers. usually with severity from 20 through 25. triggers.SQL Server 2005 Errors that terminate the database connection.NET Framework by using the appropriate language compiler. and types. Example: The following example creates the GetPhotoFromDB stored procedure that references the GetPhotoFromDB method of the LargeObjectBinary class in the HandlingLOBUsingCLR assembly. Cognizant Technology Solutions.
procedures. GO EXECUTE AS clause In SQL Server 2005 you can implicitly define the execution context of the following user-defined modules: functions (except inline table-valued functions). and DML Triggers { EXEC | EXECUTE } AS { CALLER | SELF | OWNER | 'user_name' } DDL Triggers with Database Scope { EXEC | EXECUTE } AS { CALLER | SELF | 'user_name' } DDL Triggers with Server Scope { EXEC | EXECUTE } AS { CALLER | SELF | 'login_name' } Queues { EXEC | EXECUTE } AS { SELF | OWNER | 'user_name' } Arguments: CALLER: Specifies the statements inside the module are executed in the context of the caller of the module. The actual user ID of the person creating or modifying the modules is stored in the execute_as_principal_id column in the sys. Permissions must be granted to users only on the module itself. Syntax: Functions (except inline table-valued functions).service_queues catalog view.sql_modules or sys.GetPhotoFromDB. SELF is the default for queues. SELF: EXECUTE AS SELF is equivalent to EXECUTE AS user_name. queues. Page 135 ©Copyright 2007. you can control which user account the SQL Server 2005 Database Engine uses to validate permissions on objects that are referenced by the module.LargeObjectBinary. CALLER is the default for all modules except queues. but also on any database objects that are referenced by the module. Cognizant Technology Solutions. and is the same as SQL Server 2000 behavior. CALLER cannot be specified in a CREATE QUEUE or ALTER QUEUE statement. This provides additional flexibility and control in managing permissions across the object chain that exists between user-defined modules and the objects referenced by those modules. By specifying the context in which the module is executed. All Rights Reserved C3: Protected . Only the user that the module is running as must have permissions on the objects accessed by the module. where the specified user is the person creating or altering the module. without having to grant them explicit permissions on the referenced objects. The user executing the module must have appropriate permissions not only on the module itself.Handout . Stored Procedures.SQL Server 2005 AS EXTERNAL NAME HandlingLOBUsingCLR. and triggers.
login_name cannot be a group. Permissions for any objects within the module are verified against user_name.assembly_modules catalog view. or NT AUTHORITY\LocalSystem. Use login_name instead. NT AUTHORITY\NetworkService. The user ID of the execution context is stored in metadata and can be viewed in the execute_as_principal_id column in the sys. CompanyDomain\SqlUser1 is a member of SQLUsers and. certificate. such as NT AUTHORITY\LocalService. role. or built-in account. When the following CREATE PROCEDURE statement is run. OWNER cannot be specified for DDL triggers. The user that is creating or altering the module has permissions to create principals. certificate. role. 'login_name': Specifies the statements inside the module execute in the context of the SQL Server login specified in login_name. user_name must exist in the current database and must be a singleton account. such as NT AUTHORITY\LocalService. Example: Assume the following conditions: CompanyDomain\SQLUsers group has access to the Sales database. All Rights Reserved C3: Protected .usp_Demo WITH EXECUTE AS 'CompanyDomain\SqlUser1' AS SELECT user_name(). or NT AUTHORITY\LocalSystem.SQL Server 2005 OWNER: Specifies the statements inside the module executes in the context of the current owner of the module. has access to the Sales database. user_name cannot be specified for DDL triggers with server scope. Cognizant Technology Solutions. the owner of the schema of the module is used. GO CREATE PROCEDURE dbo. therefore. GO Page 136 ©Copyright 2007. NT AUTHORITY\NetworkService. Permissions for any objects within the module are verified against login_name. login_name can be specified only for DDL triggers with server scope.Handout . the CompanyDomain\SqlUser1 is implicitly created as a database principal in the Sales database.sql_modules or sys. USE Sales. user_name cannot be a group. key. key. or built-in account. 'user_name': Specifies the statements inside the module execute in the context of the user specified in user_name. If the module does not have a specified owner.
Example: The following example alters the usp_vendor_info_all stored procedure (without encryption) to return only those vendors that supply paint.Name. GO ALTER PROCEDURE ALTER PROCEDURE statement modifies a previously created procedure that was created by executing the CREATE PROCEDURE statement. Cognizant Technology Solutions.Vendor v Page 137 ©Copyright 2007. and who currently are available.usp_vendor_info_all @product varchar(25) AS SELECT LEFT(v.Shows execution context is set to SqlUser1. 25) AS 'Product name'.ActiveFlag WHEN 1 THEN 'Yes' ELSE 'No' END FROM Purchasing. 25) AS Vendor. -. ALTER PROCEDURE dbo.Handout .CreditRating WHEN 1 THEN 'Superior' WHEN 2 THEN 'Excellent' WHEN 3 THEN 'Above average' WHEN 4 THEN 'Average' WHEN 5 THEN 'Below average' ELSE 'No rating' END . -.Shows execution context is set to SqlUser1. All Rights Reserved C3: Protected . 'Credit rating' = CASE v. Availability = CASE v. the caller of the module. ALTER PROCEDURE does not change permissions and does not affect any dependent stored procedures or triggers. have an excellent credit rating.SQL Server 2005 Using EXECUTE AS CALLER Stand-alone Statement: Use the EXECUTE AS CALLER stand-alone statement inside a module to set the execution context to the caller of the module. CREATE PROCEDURE dbo. -. REVERT. The LEFT and CASE functions and the ORDER BY clause customize the appearance of the result set. EXECUTE AS CALLER.usp_Demo WITH EXECUTE AS 'SqlUser1' AS SELECT user_name(). SELECT user_name(). Assume the following stored procedure is called by SqlUser2.Shows execution context is set to SqlUser2. SELECT user_name().Name. LEFT(p.
Extended stored procedures are replaced with CLR Store procedures in SQL Server 2005.ProductVendor pv ON v.Name LIKE @product ORDER BY v. Stored procedures increase the security of the data access code.VendorID = pv.SQL Server 2005 INNER JOIN Purchasing. All Rights Reserved C3: Protected .VendorID INNER JOIN Production.Product p ON pv. GO Summary A stored procedure is a piece of TSQL code stored in the database.Name ASC. Stored procedures provide the best possible performance. Cognizant Technology Solutions. Temporary stored procedures are stored in TempDB.ProductID WHERE p.Handout .ProductID = p. Page 138 ©Copyright 2007.
This means the user-defined function does not need to be reparsed and reoptimized with each use resulting in much faster execution times. User-defined functions can be modified independently of the program source code. Scalar functions can be executed by using an EXECUTE statement like stored procedures. string manipulation. They allow faster execution: Similar to stored procedures.Handout . User-defined functions.: You can create the function once. like system functions. store it in the database. and business logic. perform an action.SQL Server 2005 Session 26: Functions Learning Objectives After completing this session. Page 139 ©Copyright 2007. SQL Server 2005 supports three types of user-defined functions: Scalar functions Inline table-valued functions Multi statement table-valued functions CREATE FUNCTION Creates a user-defined function. User-defined Function Benefits: The benefits of using user-defined functions in SQL Server are: They allow modular programming. Cognizant Technology Solutions. such as a complex calculation. User-defined functions are modified by using ALTER FUNCTION and dropped by using DROP FUNCTION. CLR functions offer significant performance advantage over Transact-SQL functions for computational tasks. This is a saved Transact-SQL or common language runtime (CLR) routine that returns a value. can be invoked from a query. Transact-SQL functions are better suited for data-access intensive logic. They can reduce network traffic: An operation that filters data based on some complex constraint that cannot be expressed in a single scalar expression can be expressed as a function. All Rights Reserved C3: Protected . The function can then invoked in the WHERE clause to reduce the number or rows sent to the client. and call it any number of times in your program. The return value can either be a single scalar value or a result set. and return the result of that action as a value. Transact-SQL userdefined functions reduce the compilation cost of Transact-SQL code by caching the plans and reusing them for repeated executions. you will be able to: Apply user-defined functions Create user-defined functions List the types of user-defined functions User-defined Functions Like functions in programming languages. User-defined functions cannot be used to perform actions that modify the database state. Microsoft SQL Server 2005 user-defined functions are routines that accept parameters.
...n ] ] [ AS ] RETURN [ ( ] select_stmt [ ) ] [ .n ] ] ) RETURNS TABLE [ WITH <function_option> [ . ] parameter_data_type [ = default ] } [ ....n ] ] ) RETURNS @return_variable TABLE < table_type_definition > [ WITH <function_option> [ ....SQL Server 2005 Syntax: Scalar Functions CREATE FUNCTION [ schema_name... ] function_name ( [ { @parameter_name [ AS ] [ type_schema_name.Handout .n ] ] [ AS ] BEGIN function_body RETURN Page 140 ©Copyright 2007. ] Multistatement Table-valued Functions CREATE FUNCTION [ schema_name. ] parameter_data_type [ = default ] } [ .. ] function_name ( [ { @parameter_name [ AS ][ type_schema_name... ] Inline Table-valued Functions CREATE FUNCTION [ schema_name.n ] ] [ AS ] BEGIN function_body RETURN scalar_expression END [ .... ] function_name ( [ { @parameter_name [ AS ] [ type_schema_name.. All Rights Reserved C3: Protected . Cognizant Technology Solutions.n ] ] ) RETURNS return_data_type [ WITH <function_option> [ . ] parameter_data_type [ = default ] } [ .
One or more parameters can be declared. The value of each declared parameter must be supplied by the user when the function is executed... Function names must comply with the rules for identifiers and must be unique within the database and to its schema.. function_name: Is the name of the user-defined function.. they cannot be used instead of table names. column names.n ] ] [ AS ] EXTERNAL NAME <method_specifier> [ . All Rights Reserved C3: Protected ..024 parameters. the same parameter names can be used in other functions.. Parameters are local to the function.SQL Server 2005 END [ . @parameter_name: Is a parameter in the user-defined function. ] Method Specifier <method_specifier>::= assembly_name. The parameter name must comply with the rules for identifiers. ] CLR Functions CREATE FUNCTION [ schema_name. ] parameter_data_type [ = default ] } [ .Handout . Page 141 ©Copyright 2007. unless a default for the parameter is defined.n ] ) RETURNS { return_data_type | TABLE <clr_table_type_definition> } [ WITH <clr_function_option> [ .class_name. ] function_name ( { @parameter_name [AS] [ type_schema_name. Specify a parameter name by using an at sign (@) as the first character. Parameters can take the place only of constants. A function can have a maximum of 1.method_name Function Options <function_option>::= { [ ENCRYPTION ] | [ SCHEMABINDING ] | [ RETURNS NULL ON NULL INPUT | CALLED ON NULL INPUT ] | [ EXECUTE_AS_Clause ] } Arguments: schema_name: Is the name of the schema to which the user-defined function belongs. or the names of other database objects. Cognizant Technology Solutions.
including CLR user-defined types. The default schema of the current user in the current database. In multistatement table-valued functions. are allowed except the timestamp data type. image. @return_variable can be specified only for Transact-SQL functions and not for CLR functions. If type_schema_name is not specified. return_data_type: Is the return value of a scalar user-defined function. the keyword DEFAULT must be specified when the function to retrieve the default value. For Transact-SQL functions. are allowed except text. the function can be executed without specifying a value for that parameter. all data types. The nonscalar types cursor and table cannot be specified as a return data type in either Transact-SQL or CLR functions. image. and optionally the schema to which it belongs. ntext. all data types. For CLR functions. the TABLE return value is defined through a single SELECT statement. For Transact-SQL functions.SQL Server 2005 [ type_schema_name. If a default value is defined. In inline table-valued functions. the SQL Server 2005 Database Engine looks for the scalar_parameter_data_type in the following order: o o o The schema that contains the names of SQL Server system data types. function_body is a series of Transact-SQL statements that populate a TABLE return variable. function_body is used only in scalar functions and multistatement table-valued functions. Page 142 ©Copyright 2007. define the value of the function. which together do not produce a side effect such as modifying a table. and timestamp data types. including CLR user-defined types. When a parameter of the function has a default value. are allowed except the timestamp data type. Cognizant Technology Solutions. used to store and accumulate the rows that should be returned as the value of the function. Only constants and @local_variables can be passed to table-valued functions.Handout . are allowed except text. [ = default ]: Is a default value for the parameter. For CLR functions. In multistatement table-valued functions. all data types. including CLR user-defined types. The nonscalar types cursor and table cannot be specified as a parameter data type in either Transact-SQL or CLR functions. all data types. @return_variable is a TABLE variable. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value. function_body: Specifies that a series of Transact-SQL statements. Inline functions do not have associated return variables. In scalar functions. The dbo schema in the current database. and timestamp data types. All Rights Reserved C3: Protected . TABLE: Specifies that the return value of the table-valued function is a table. function_body is a series of Transact-SQL statements that together evaluate to a scalar value. including CLR user-defined types. scalar_expression: Specifies the scalar value that the scalar function returns. ntext. ] parameter_data_type: Is the parameter data type.
the class name must be delimited by using brackets ([ ]) or quotation marks (" "). If not specified.Handout . All Rights Reserved C3: Protected . If the method of a CLR function specified in <method_specifier> already has a custom attribute that indicates RETURNS NULL ON NULL INPUT.) to separate namespace parts. assembly_name must match an existing assembly in SQL Server in the current database with visibility on. The objects referenced by the function are referenced using a two-part name. If the class has a namespace-qualified name that uses a period (. The binding of the function to the objects it references is removed only when one of the following actions occurs: o o The function is dropped. CALLED ON NULL INPUT is implied by default. SCHEMABINDING: Specifies that the function is bound to the database objects that it references. The function and the objects it references belong to the same database. SCHEMABINDING cannot be specified for CLR functions or functions that reference alias data types. The user who executed the CREATE FUNCTION statement has REFERENCES permission on the database objects that the function references. The user-defined functions and views referenced by the function are also schemabound. Cognizant Technology Solutions. ENCRYPTION cannot be specified for CLR functions. The function is modified by using the ALTER statement with the SCHEMABINDING option not specified. EXTERNAL NAME <method_specifier>. it indicates that SQL Server can return NULL when any of the arguments it receives is NULL. This means that the function body executes even if NULL is passed as an argument. Using ENCRYPTION prevents the function from being published as part of SQL Server replication.method_name: Specifies the method of an assembly to bind with the function. RETURNS NULL ON NULL INPUT | CALLED ON NULL INPUT: Specifies the OnNULLCall attribute of a scalar-valued function. ENCRYPTION: Indicates that the Database Engine encrypts the catalog view columns that contain the text of the CREATE FUNCTION statement. without actually invoking the body of the function. This condition will prevent changes to the function if other schema-bound objects are referencing it. but the CREATE FUNCTION Page 143 ©Copyright 2007. method_name must be a valid SQL Server identifier and must exist as a static method in the specified class. If RETURNS NULL ON NULL INPUT is specified in a CLR function. class_name must be a valid SQL Server identifier and must exist as a class in the assembly.class_name. A function can be schema bound only if the following conditions are true: The function is a Transact-SQL function.SQL Server 2005 select_stmt: Is the single SELECT statement that defines the return value of an inline tablevalued function. assembly_name.
BEGIN DECLARE @ret int. GO Page 144 ©Copyright 2007. SELECT @ret = SUM(p. and returns a single data value.. Name. contains a series of Transact-SQL statements that return the single value. USE AdventureWorks. image. Therefore. the scalar value is the result of a single statement.LocationID = '6'.Quantity) FROM Production. For an inline scalar function. the aggregated quantity of the specified product in inventory.ProductID = @ProductID AND p. ntext. Scalar functions User-defined scalar functions return a single data value of the type defined in the RETURNS clause.Returns the stock level for the product.Product WHERE ProductModelID BETWEEN 75 and 80.SQL Server 2005 statement indicates CALLED ON NULL INPUT. Cognizant Technology Solutions. the CREATE FUNCTION statement takes precedence. GO The following example uses the ufnGetStock function to return the current inventory quantity for products that have an ProductModelID between 75 and 80. you can control which user account SQL Server uses to validate permissions on any database objects that are referenced by the function.Handout . Example: The following examples creates a multistatement scalar function. The return type can be any data type except text.. there is no function body.ufnGetStock(ProductID)AS CurrentSupply FROM Production. CREATE FUNCTION dbo. IF (@ret IS NULL) SET @ret = 0 RETURN @ret END. a ProductID.END block. The OnNULLCall attribute cannot be specified for CLR table-valued functions. All Rights Reserved C3: Protected . and timestamp. the function body. The function takes one input value.ProductInventory p WHERE p. defined in a BEGIN.ufnGetStock(@ProductID int) RETURNS int AS -. GO SELECT ProductModelID. cursor. EXECUTE AS Clause: Specifies the security context under which the user-defined function is executed. dbo. For a multistatement scalar function.
SalesOrderDetail AS SD ON SD.SalesOrderID WHERE SH. P.ProductID = P. A single SELECT statement is present in the body of the function. Name. Function body is not delimited by BEGIN and END.UPDATE. and returns the columns ProductID. a customer (store) ID. Example: The following example creates an inline table-valued function.ProductID.SalesOrderHeader AS SH ON SH.SalesOrderID = SD. SUM(SD.Name.ProductID. The function takes one input parameter.LineTotal) AS 'YTD Total' FROM Production. Cognizant Technology Solutions. P. GO CREATE FUNCTION Sales. Multi-Valued Table Functions RETURNS clause always specifies a Table variable Lists the column names and their data types The only statements allowed in the function body are: o Assignment statements o Control-of-flow o DECLARE statements o SELECT that assign values to local variables o Cursors operations on local cursors o INSERT. and the aggregate of year-to-date sales as YTD Total for each product sold to the store. and DELETE that modify local table variables Invocation similar to inline functions Page 145 ©Copyright 2007. USE AdventureWorks. All Rights Reserved C3: Protected .Product AS P JOIN Sales.fn_SalesByStore (@storeid int) RETURNS TABLE AS RETURN ( SELECT P. SELECT * FROM Sales.Handout .ProductID JOIN Sales.SQL Server 2005 Inline Table-Valued Functions Inline functions should only have TABLE as the return type.CustomerID = @storeid GROUP BY P.Name ).fn_SalesByStore (602). GO The following example invokes the function and specifies customer ID 602.
EmployeeID.EmployeeID = @InEmpID UNION ALL SELECT CONVERT(Varchar(255). e. Title.Title. an EmployeeID and returns a list of all the employees who report to the specified employee directly or indirectly. Name nvarchar(255) NOT NULL. e.FirstName + ' ' + c.FirstName + ' ' + c.Title.LastName).ContactID JOIN DirectReports AS d ON e. The function takes a single input parameter. RTRIM(Sort) + '| ' + FirstName + ' ' + LastName) FROM HumanResources. EmployeeLevel) + c.Employee AS e JOIN Person.ContactID = c.Employee as e JOIN Person. EmployeeLevel. Sort nvarchar (255) NOT NULL ) --Returns a result set that lists all the employees who report to the --specific employee directly or indirectly. EmployeeID.ContactID = c.fn_FindReports (@InEmpID INTEGER) RETURNS @retFindReports TABLE ( EmployeeID int primary key NOT NULL. USE AdventureWorks. REPLICATE ('| ' . CONVERT (Varchar(255). Title.SQL Server 2005 Example: The following example creates a table-valued function. EmployeeLevel + 1.copy the required columns to the result of the function INSERT @retFindReports SELECT EmployeeID.Contact AS c ON e.ContactID WHERE e.EmployeeID. All Rights Reserved C3: Protected .LastName) FROM HumanResources. Name.Handout .ManagerID = d.Contact AS c ON e. e. Sort FROM DirectReports Page 146 ©Copyright 2007. Title nvarchar(50) NOT NULL.FirstName + ' ' + c. Cognizant Technology Solutions. GO CREATE FUNCTION dbo. 1.LastName).EmployeeID ) -. EmployeeLevel int NOT NULL.*/ AS BEGIN WITH DirectReports(Name. CONVERT(Varchar(255). c. Sort) AS (SELECT CONVERT(Varchar(255). e. c. EmployeeLevel.
fn_FindReports(109) ORDER BY Sort. All Rights Reserved C3: Protected .Handout . Name. the function is invoked. -. Title.Example invocation SELECT EmployeeID. EmployeeLevel FROM dbo. Cognizant Technology Solutions. Multi-valued table functions can have multiple statements. GO In the following example.SQL Server 2005 RETURN END. Summary Inline table functions have only a simple SELECT statement. Page 147 ©Copyright 2007.
or DELETE statements that modify data in a specified table or view. or DELETE) on a table allow multiple. They can guard against malicious or incorrect INSERT. All Rights Reserved C3: Protected . however. Unlike CHECK constraints. a trigger can use a SELECT from another table to compare to the inserted or updated data and to perform additional actions. Multiple DML triggers of the same type (INSERT. DML events include INSERT. different actions to take place in response to the same modification statement. UPDATE. you will be able to: Define trigger Create trigger Identify the types of trigger Triggers Microsoft SQL Server 2005 provides two primary mechanisms for enforcing business rules and data integrity: constraints and triggers. SQL Server includes two general types of triggers: DML triggers DDL triggers. insufficient disk space).Handout . and DELETE operations and enforce other restrictions that are more complex than those defined with CHECK constraints. These triggers are invoked when a data definition language (DDL) event takes place in the server or database. DML triggers can reference columns in other tables. A trigger is a special type of stored procedure that automatically takes effect when a language event executes. The trigger and the statement that fires it are treated as a single transaction. these changes can be executed more efficiently using cascading referential integrity constraints. They can evaluate the state of a table before and after a data modification and take actions based on that difference. UPDATE. DDL triggers are new to SQL Server 2005. DML triggers are useful in these ways: They can cascade changes through related tables in the database. the entire transaction automatically rolls back. Page 148 ©Copyright 2007. UPDATE. For example. If a severe error is detected (for example. DML triggers are invoked when a data manipulation language (DML) event takes place in the database. such as modify the data or display a user-defined error message. which can be rolled back from within the trigger. A DML trigger can query other tables and can include complex TransactSQL statements. Cognizant Technology Solutions.SQL Server 2005 Session 29: Triggers Learning Objectives After completing this session.
] } [ . or DELETE statement is performed..class_name... AFTER triggers can be specified only on tables.n ] | EXTERNAL NAME < method specifier > <ddl_trigger_option> ::= Page 149 ©Copyright 2007.. where they can extend the types of updates a view can support.SQL Server 2005 Types of DML Triggers AFTER Triggers: AFTER triggers are executed after the action of the INSERT. UPDATE. DROP. Cognizant Technology Solutions. ]trigger_name ON { table | view } [ WITH <dml_trigger_option> [ .n ] ] { FOR | AFTER } { event_type | event_group } [ . Specifying AFTER is the same as specifying FOR.n ] AS { sql_statement [ .. REVOKE.. or DELETE statement to a table or view (DML Trigger) CREATE TRIGGER [ schema_name .Handout . UPDATE.. DENY.. ] [ DELETE ] } [ WITH APPEND ] [ NOT FOR REPLICATION ] AS { sql_statement [ .. a CLR trigger executes one or more methods written in managed code that are members of an assembly created in the . which is the only option available in earlier versions of Microsoft SQL Server.n ] | EXTERNAL NAME <method specifier [ . ALTER. INSTEAD OF Triggers: INSTEAD OF triggers are executed in place of the usual triggering action. CLR Triggers: A CLR Trigger can be either an AFTER or INSTEAD OF trigger.n ] ] { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ . ] > } <dml_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name.. GRANT. INSTEAD OF triggers can also be defined on views with one or more base tables.method_name Trigger on a CREATE.. or UPDATE STATISTICS statement (DDL Trigger) CREATE TRIGGER trigger_name ON { ALL SERVER | DATABASE } [ WITH <ddl_trigger_option> [ . ] [ UPDATE ] [ . ] [ . A CLR trigger can also be a DDL trigger..NET Framework and uploaded in SQL Server CREATE TRIGGER Syntax: Trigger on an INSERT. Instead of executing a Transact-SQL stored procedure. ] [ .. All Rights Reserved C3: Protected .
the trigger fires whenever event_type or event_group occurs anywhere in the current server. INSTEAD OF: Specifies that the DML trigger is executed instead of the triggering SQL statement. UPDATE. However. Cognizant Technology Solutions. If specified.class_name. DATABASE: Applies the scope of a DDL trigger to the current database. one INSTEAD OF trigger per INSERT. Page 150 ©Copyright 2007.method_name Arguments: schema_name: Is the name of the schema to which a DML trigger belongs. WITH ENCRYPTION cannot be specified for CLR triggers. therefore. All referential cascade actions and constraint checks also must succeed before this trigger fires. EXECUTE AS: Specifies the security context under which the trigger is executed. WITH ENCRYPTION: Encrypts the text of the CREATE TRIGGER statement. you can define views on views where each view has its own INSTEAD OF trigger. with the exception that trigger_name cannot start with # or ##. At most. A view can be referenced only by an INSTEAD OF trigger. DML triggers are scoped to the schema of the table or view on which they are created. AFTER is the default when FOR is the only keyword specified. table | view: Is the table or view on which the DML trigger is executed and is sometimes referred to as the trigger table or trigger view. or DELETE statement can be defined on a table or view. schema_name cannot be specified for DDL triggers.SQL Server 2005 [ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name. Specifying the fully qualified name of the table or view is optional.Handout . ALL SERVER: Applies the scope of a DDL trigger to the current server. overriding the actions of the triggering statements. AFTER triggers cannot be defined on views. INSTEAD OF cannot be specified for DDL triggers. AFTER: Specifies that the DML trigger is fired only when all operations specified in the triggering SQL statement have executed successfully. Enables you to control which user account the instance of SQL Server uses to validate permissions on any database objects that are referenced by the trigger. A trigger_name must comply with the rules for identifiers. If specified. All Rights Reserved C3: Protected . the trigger fires whenever event_type or event_group occurs in the current database. trigger_name: Is the name of the trigger. Using WITH ENCRYPTION prevents the trigger from being published as part of SQL Server replication.
The trigger actions specified in the Transact-SQL statements go into effect when the DML or DDL operation is tried. For more information. Any combination of these options in any order is allowed in the trigger definition. WITH APPEND cannot be specified if EXTERNAL NAME is specified (that is. event_type: Is the name of a Transact-SQL language event that.trigger_events catalog view. { [ DELETE ] [ . NOT FOR REPLICATION: Indicates that the trigger should not be executed when a replication agent modifies the table that is involved in the trigger. Events that are valid for use in DDL triggers are listed in DDL Events for Use with DDL Triggers. Event groups that are valid for use in DDL triggers are listed in Event Groups for Use with DDL Triggers. The DDL trigger fires after execution of any Transact-SQL language event that belongs to event_group. Identities. If the compatibility level is 70 or higher. Page 151 ©Copyright 2007. This is the default behavior of CREATE TRIGGER with the compatibility level setting of 70 or higher. event_group: Is the name of a predefined grouping of Transact-SQL language events. Trigger conditions specify additional criteria that determine whether the tried DML or DDL statements cause the trigger actions to be performed. for backward compatibility reasons.Handout . the DELETE option is not allowed on tables that have a referential relationship specifying a cascade action ON DELETE. without INSTEAD OF or AFTER. and Triggers with NOT FOR REPLICATION. SQL Server raises an error when an INSTEAD OF trigger is added to an updatable view WITH CHECK OPTION specified. sql_statement: Is the trigger conditions and actions. event_group also acts as a macro by adding the event types it covers to the sys. the UPDATE option is not allowed on tables that have a referential relationship specifying a cascade action ON UPDATE. WITH APPEND cannot be used with INSTEAD OF triggers or if AFTER trigger is explicitly stated. WITH APPEND: Specifies that an additional trigger of an existing type should be added. Cognizant Technology Solutions. All Rights Reserved C3: Protected . causes a DDL trigger to fire. Use of this optional clause is required only when the compatibility level is 65 or lower. if the trigger is a CLR trigger). the WITH APPEND clause is not required to add an additional trigger of an existing type. Similarly. ] [ UPDATE ] }: Specifies the data modification statements that activate the DML trigger when it is tried against this table or view. WITH APPEND can be used only when FOR is specified. The user must remove that option by using ALTER VIEW before defining the INSTEAD OF trigger. after execution. see Controlling Constraints. At least one option must be specified. ] [ INSERT ] [ . For INSTEAD OF triggers. After the CREATE TRIGGER has finished running.SQL Server 2005 INSTEAD OF triggers are not allowed on updatable views that use WITH CHECK OPTION.
They are structurally similar to the table on which the trigger is defined.Customer AFTER INSERT. see Remarks. the table on which the user action is tried. it should not return data to the user. DML triggers use the deleted and inserted logical (conceptual) tables. USE AdventureWorks IF OBJECT_ID ('Sales. For more information.SQL Server 2005 Triggers can include any number and kind of Transact-SQL statements. see Using the EVENTDATA Function. Cognizant Technology Solutions. When the compatibility level is 65 or lower. For more information. the class name must be delimited by using [ ] or " " delimiters. SQL Server allows for the update of text. To retrieve the new value in either an INSERT or UPDATE trigger. 16. < method_specifier > : For a CLR trigger. All Rights Reserved C3: Protected . The text.reminder1 GO CREATE TRIGGER reminder1 ON Sales. SQL Server does not allow text. and image values in the inserted and deleted tables cannot be accessed. If the class has a namespace-qualified name that uses '. INSERT. Examples: Using a DML trigger with a reminder message The following DML trigger prints a message to the client when anyone tries to add or change data in the Customer table. A trigger is designed to check or change data based on a data modification or definition statement. 10) GO Page 152 ©Copyright 2007. or UPDATE trigger. that is.Handout .reminder1'. use: SELECT * FROM deleted DDL triggers capture information about the triggering event by using the EVENTDATA (Transact-SQL) function. specifies the method of an assembly to bind with the trigger. For example. The deleted and inserted tables hold the old values or new values of the rows that may be changed by the user action. or image columns that allow null values. ntext. 'TR') IS NOT NULL DROP TRIGGER Sales. The Transact-SQL statements in a trigger frequently include controlof-flow language. The method must take no arguments and return void. null values are returned for inserted or deleted text. join the inserted table with the original update table. If the compatibility level is 80 or higher. UPDATE AS RAISERROR ('Notify Customer Relations'. In a DELETE. zero-length strings are returned if the columns are not nullable. ntext. ntext. or image columns through the INSTEAD OF trigger on tables or views. or image column references in the inserted and deleted tables if the compatibility level is set to 70. with exceptions. to retrieve all values in the deleted table. class_name must be a valid SQL Server identifier and must exist as a class in the assembly with assembly visibility. ntext.' to separate namespace parts. The class cannot be a nested class.
INSTEAD OF triggers can also be defined on views with one or more base tables.PurchaseOrderID JOIN Purchasing. INSTEAD OF triggers can be used to perform enhance integrity checks on the data values supplied in INSERT and UPDATE statements. Select @DeleteCount =COUNT(*) FROM deleted. such as a constraint violation or syntax error.PurchaseOrderHeader AFTER INSERT AS DECLARE @creditrating tinyint. AFTER triggers are executed after the action of the INSERT. All Rights Reserved C3: Protected . UPDATE or DELETE statement can be defined on a table or view. @vendorid = p.VendorID = i.'.PurchaseOrderID = i.Handout . where they can extend the types of updates a view can support. then the trigger is not executed.[Employee] INSTEAD OF DELETE NOT FOR REPLICATION AS BEGIN SET NOCOUNT ON. not on views. Example: CREATE TRIGGER LowCredit ON Purchasing. A table can have several AFTER triggers for each triggering action.SQL Server 2005 AFTER Triggers The trigger executes after the statement that triggered it completes. AFTER triggers can be specified only on tables. One INSTEAD OF trigger per INSERT. If the statement fails with an error. 1) ROLLBACK TRANSACTION END INSTEAD OF Triggers INSTEAD OF triggers can be used to perform to enhance integrity checks on the data values supplied in INSERT and UPDATE statements.VendorID IF @creditrating = 5 BEGIN RAISERROR ('This vendor''s credit rating is too low to accept new purchase orders. UPDATE or DELETE statement is performed. Cognizant Technology Solutions. Examples: CREATE TRIGGER [delEmployee] ON [HumanResources].PurchaseOrderHeader p INNER JOIN inserted i ON p.Vendor v on v. IF @DeleteCount > 0 Page 153 ©Copyright 2007. INSTEAD OF triggers are executed in place of the usual triggering action. 16.CreditRating. DECLARE @DeleteCount int. @vendorid int SELECT @creditrating = v.VendorID FROM Purchasing.
NET Framework common language runtime (CLR). Database objects that can leverage the rich programming model provided by the CLR include DML triggers. Microsoft. For more information about how to program triggers in the CLR. using using using using using using System. Creating a CLR trigger (DML or DDL) in SQL Server involves the following steps: Define the trigger as a class in a .Handout .'. 1).Data. System. They can only be marked as not current. Creating CLR Trigger Microsoft SQL Server 2005 provides the ability to create a database object inside SQL Server that is programmed in an assembly created in the . Create the trigger that references the registered assembly.Data. Register the assembly in SQL Server using the CREATE ASSEMBLY statement.--State. END.--Severity.--Message 10.SqlTypes. Triggers written in a CLR language differ from other CLR integration objects in several significant ways.NET Framework using the appropriate language compiler.SqlClient. Page 154 ©Copyright 2007. The following trigger would detect that information and log it to an audit table. functions. but you want to know the users that specifically entered an e-mail address as an ID.Data. compile the class to build an assembly in the .SqlServer. --Rollback any active or uncommitable transactions IF @@TRANCOUNT > 0 BEGIN ROLLBACK TRANSACTION. Then. and types.Server. stored procedures.Sql.NET language. consider the scenario in which you let the user choose any ID they want. Cognizant Technology Solutions. System. System. see CLR Triggers. CLR triggers can: Reference data in the INSERTED and DELETED tables Determine which columns have been modified as a result of an UPDATE operation Access information about database objects affected by the execution of DDL statements. DDL triggers. END END.Data. System.SQL Server 2005 BEGIN RAISERROR (N'Employees cannot be deleted. Sample CLR Trigger: In this example. All Rights Reserved C3: Protected . aggregate functions.
Xml. SqlDataReader reader. All Rights Reserved C3: Protected .Handout . pipe. SqlPipe pipe = SqlContext. Event = "FOR INSERT.[Users]". Cognizant Technology Solutions. DELETE")] public static void EmailAudit() { string userName. UPDATE. userName = (string)reader[0]. command = new SqlCommand(@"SELECT * FROM INSERTED.Close().ExecuteReader(). reader.TriggerContext. reader = command.TriggerAction) { case TriggerAction. SqlTriggerContext triggContext = SqlContext.Insert: // Retrieve the connection that the trigger is using using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.CommandText).Pipe. reader. realName = (string)reader[1]. Target = "[dbo].Send("You inserted: " + userName). if (IsValidEMailAddress(userName)) { command = new SqlCommand( @"INSERT [dbo]. command.".ExecuteNonQuery().Read(). string realName.Open().RegularExpressions. pipe. using System.Send(command.SQL Server 2005 using System.". switch (triggContext. public class CLRTriggers { [SqlTrigger(Name = @"EmailAudit". SqlCommand command.[UserNameAudit] VALUES ('" + userName + @"'. connection). } } Page 155 ©Copyright 2007. '" + realName + @"').Text. connection).
pipe. columnNumber++) { pipe.Close().Delete: using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection. command = new SqlCommand(@"SELECT * FROM INSERTED. connection).Send(@"You deleted the following rows:"). userName = (string)reader[0]. Cognizant Technology Solutions. All Rights Reserved C3: Protected . } reader.IsUpdatedColumn(columnNumber).ColumnCount. columnNumber < triggContext.Update: // Retrieve the connection that the trigger is using using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection. if (reader. reader. reader = command.Open().ToString()).Handout .Open().Read().SQL Server 2005 break. case TriggerAction.". Page 156 ©Copyright 2007. connection).HasRows) { pipe. realName = (string)reader[1]. for (int columnNumber = 0.ExecuteReader(). } break. reader = command. case TriggerAction.Send("Updated column " + reader.Send(@"You updated: '" + userName + @"' .ExecuteReader().".'" + realName + @"'").GetName(columnNumber) + "? " + triggContext. command = new SqlCommand(@"SELECT * FROM DELETED.
)*?[\w-]+@[\w-]+\. } } break.SQL Server 2005 while (reader. Event:="FOR INSERT. All Rights Reserved C3: Protected .SqlClient System.IsMatch(email. } } Visual Basic: Imports Imports Imports Imports Imports Imports Imports System System. to just send a tabular resultset back: //pipe.Close(). Target:="[dbo]. //alternately.Read()) { pipe.GetString(1) + @"'").SqlServer.Data.Sql System. } } public static bool IsValidEMailAddress(string email) { return Regex.ExecuteAndSend(command). DELETE")> _ Public Shared Sub EmailAudit() Page 157 ©Copyright 2007.GetString(0) + @"'.").[Users]".Data System.SqlTypes Microsoft.([\w]+\.Send("No rows affected. UPDATE. Cognizant Technology Solutions.Text.)*?[\w]+$"). } else { pipe.Data.RegularExpressions 'The Partial modifier is only required on one class definition per project. } reader. Partial Public Class CLRTriggers <SqlTrigger(Name:="EmailAudit".Handout .Data.Server System.Send(@"'" + reader. @"^([\w-]+\. '" + reader.
".Pipe Select Case triggContext. Cognizant Technology Solutions.".TriggerAction Case TriggerAction.Open() command = new SqlCommand("SELECT * FROM INSERTED.Close() If IsValidEmailAddress(userName) Then command = New SqlCommand("INSERT [dbo].Handout .Insert Using connection As New SqlConnection("context connection=true") connection. connection) reader = command.ExecuteNonQuery() pipe.Send("You inserted: " & userName) End If End Using Case TriggerAction. String) realName = CType(reader(1). All Rights Reserved C3: Protected .ExecuteReader() reader. connection) pipe.Update Using connection As New SqlConnection("context connection=true") connection.Open() command = new SqlCommand("SELECT * FROM INSERTED.Send(command. String) reader.Read() userName = CType(reader(0).[UserNameAudit] VALUES ('" & _ userName & "'.SQL Server 2005 Dim Dim Dim Dim Dim Dim userName As String realName As String command As SqlCommand triggContext As SqlTriggerContext pipe As SqlPipe reader As SqlDataReader triggContext = SqlContext. connection) Page 158 ©Copyright 2007.".CommandText) command. '" & realName & "').TriggerContext pipe = SqlContext.
" & realName) Dim columnNumber As Integer For columnNumber=0 To triggContext.HasRows Then pipe.ColumnCount-1 pipe.ExecuteReader() reader. Cognizant Technology Solutions. connection) reader = command.GetString(0) & ".ToString() ) Next reader.Send("Updated column " & reader. String) pipe.Handout .Delete Using connection As New SqlConnection("context connection=true") connection.Close() ' Alternately. " & reader. just send a tabular resultset back: Page 159 ©Copyright 2007.IsUpdatedColumn(columnNumber). String) realName = CType(reader(1).SQL Server 2005 reader = command.Read() userName = CType(reader(0).Send("You deleted the following rows:") While reader.GetString(1) ) End While reader.GetName(columnNumber) & _ "? " & triggContext.Open() command = new SqlCommand("SELECT * FROM DELETED.ExecuteReader() If reader.".Send("You updated: " & userName & " .Send( reader.Close() End Using Case TriggerAction.Read() pipe. All Rights Reserved C3: Protected .
GO CREATE TABLE UserNameAudit ( UserName nvarchar(200) NOT RealName nvarchar(200) NOT ) NULL. All Rights Reserved C3: Protected .Handout . Cognizant Technology Solutions.SQL Server 2005 ' pipe. NULL NULL. CREATE TRIGGER EmailAudit ON Users FOR INSERT AS EXTERNAL NAME SQLCLRTest. and assumes assembly SQLCLRTest is already registered in the current SQL Server database.)*?[\w-]+@[\w]+\.EmailAudit Page 160 ©Copyright 2007. "^([\w-]+\.Send("No rows affected.") End If End Using End Select End Sub Public Shared Function IsValidEMailAddress(emailAddress As String) As Boolean return Regex. NULL The Transact-SQL statement that creates the trigger in SQL Server is as follows.CLRTriggers.ExecuteAndSend(command) Else pipe.)*?[\w]+$") End Function End Class Assuming two tables exist with the following definitions: CREATE TABLE Users ( UserName nvarchar(200) NOT RealName nvarchar(200) NOT ).IsMatch(emailAddress.([\w-]+\.
archiving. UPDATE or DELETE statement inside the body of a DML trigger or DML statements to return rows affected a modification.triggers WHERE parent_class = 0 AND name = 'safety') DROP TRIGGER safety ON DATABASE GO CREATE TRIGGER safety ON DATABASE FOR DROP_SYNONYM AS PRINT 'You must disable Trigger "safety" to drop synonyms!' ROLLBACK GO DROP TRIGGER safety ON DATABASE GO OUTPUT Clause Returns information from. Alternatively. Example: Using a database-scoped DDL trigger The following example uses a DDL trigger to prevent any synonym in a database from being or dropped. They can record changes or events in the database schema. USE AdventureWorks IF EXISTS (SELECT * FROM sys. Cognizant Technology Solutions. They can perform administrative tasks and enforce business rules that affect databases. and other such application requirements. Specify the OUTPUT Clause (Transact-SQL) with an INSERT. or expressions based on. UPDATE. or DELETE statement.Handout . All Rights Reserved C3: Protected . results can be inserted into a table or table variable. These results can be returned to the processing application for use in such things as confirmation messages. each row affected by an INSERT. Page 161 ©Copyright 2007.SQL Server 2005 DDL Triggers DDL triggers are used when: They can prevent certain changes to your database schema.
GO Summary A trigger is a special type of stored procedure that automatically takes effect when a language event executes. All Rights Reserved C3: Protected .* WHERE DatabaseLogID = 7. the application is constantly adding or removing rows from the table. or to hold intermediate result sets.DatabaseLog WITH (READPAST) OUTPUT deleted. Cognizant Technology Solutions. That is.Handout . Page 162 ©Copyright 2007. GO DELETE TOP(1) dbo. The following example uses the OUTPUT clause in a DELETE statement to return the deleted row to the calling application. SQL Server uses DDL and DML Triggers.SQL Server 2005 Example: You can use OUTPUT in applications that use tables as queues. USE AdventureWorks.
It is a list of values in a table with the storage locations of rows in the table that contain each value. B-trees cluster records with similar keys. The index provides pointers to the data values stored in specified columns of the table. so that navigating down the tree to find a value and locate a specific record takes only a few page accesses. An index in a database allows the database program to find data in a table without scanning the entire table. and retrieval speed is consistent because the index has the same depth throughout. finding any record requires about the same amount of resources. The B stands for balanced. The trees are managed. Because the trees are balanced. All Rights Reserved C3: Protected . A B-tree for a SQL Server index Page 163 ©Copyright 2007. An index contains an entry with one or more columns (the search key) from each row in a table. A B-tree provides fast access to data by searching on a key value of the index. and bottom-level leaf pages. A B-tree is sorted on the search key.Handout .SQL Server 2005 Session 31: Indexes Learning Objectives After completing this session. and balancing the tree is a core feature of a B-tree's usefulness. and can be searched efficiently on any leading subset of the search key. An index is a structure that orders the values of one or more columns in a database table. you will be able to: Explain indexes Define clustered and non-clustered indexes Implement Database Engine Tuning Advisor Index Indexes in databases are similar to indexes in books. and branches are grafted as necessary. In a book. Cognizant Technology Solutions. an index allows to find information quickly without reading the entire book. and then orders those pointers according to the sort order specified. Indexes can be created on either a single column or a combination of columns in a table and are implemented in the form of B-trees. An index consists of a tree with a root from which the navigation begins possible intermediate index levels.
That is. its data rows are stored in a heap. All Rights Reserved C3: Protected . or group data or to find the first few rows as indicated in a TOP clause. Because the clustered index dictates the physical storage order of the data in the table. The indexes are organized as B-trees. If a table has no clustered index. data itself is part of the index. the Database searches the index to find a particular value and then follows the pointer to the row containing that value. Cognizant Technology Solutions. The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. Each page in an index is called an index node. aggregate. the index can comprise multiple columns (a composite index). Indexes allow data to be organized in a way that allows optimum performance when it is accessed or modified. The two types of SQL Server indexes are: Clustered Nonclustered Clustered Indexes A clustered index determines the physical order of data in a table.Handout . Indexes are also helpful to search or sort by two or more columns at a time. Each index row contains a key value and a pointer to either a lower-level page or a data row. which arranges data by last name. to find matching rows in JOIN clauses. When the index is traversed to the leaf level. indexes can be used to help SQL Server sort. or to efficiently maintain uniqueness of key columns during INSERT and UPDATE operations. The pages in each level of the index are linked together in a doubly-linked list. a table can contain only one clustered index. A clustered index is analogous to a telephone directory. In some cases. PRIMARY KEY constraints create clustered indexes automatically if no clustered index already exists on the table and a nonclustered index is not specified when creating the PRIMARY KEY constraint. The top node of the B-tree is called the root node. Indexes can be used to quickly find data rows that satisfy conditions in WHERE clauses. the data itself has been retrieved.SQL Server 2005 Each page in an index holds a page header followed by index rows. Page 164 ©Copyright 2007. However. In a clustered index. Multiple-column indexes enable to distinguish between rows in which one column may have the same value. For any query. the data pages make up the leaf nodes. Any index levels between the root and the leaves are collectively known as intermediate levels. The bottom layer of nodes in the index are called the leaf nodes. not simply pointed to.
All Rights Reserved C3: Protected . Create a clustered index on the primary key. Columns that are accessed sequentially. After the row with the first value is found using the clustered index. Queries that return large result sets. Queries that return a range of values using operators such as BETWEEN. any nonclustered indexes that are defined on the same table will be significantly larger because the nonclustered index entries contain the clustering key. Page 165 ©Copyright 2007. This improves query performance. rows with subsequent indexed values are guaranteed to be physically adjacent.Usage A clustered index is efficient on columns that are often searched for ranges of values. Columns that are frequently accessed by queries involving join or GROUP BY clauses. A clustered index can be used for: Columns that contain a large number of distinct values. Clustered indexes are also efficient for finding a specific row when the indexed value is unique. uniqueness.SQL Server 2005 The clustered index structure is shown in the following graphic: Clustered Indexes . >=. It is important to define the clustered index key with as few columns as possible. If a large clustered index key is defined. typically these are foreign key columns. Cognizant Technology Solutions. >. <. typically by means of the primary key.Handout . OLTP-type applications where very fast single row lookup is required. Clustered indexes can be defined on columns with high density. that is. and <=. An index on the column(s) specified in the ORDER BY or GROUP BY clause eliminates the need for SQL Server to sort the data because the rows are already sorted.
but the information in the table is stored in a different order (which can be dictated by a clustered index). as is the case with clustered indexes. For a table with a clustered index. Cognizant Technology Solutions. the leaf nodes contain index rows. The leaf layer of a nonclustered index does not consist of the data pages. The pointer from an index row in a nonclustered index to a data row is called a row locator. Each index row contains the nonclustered key value and one or more row locators that point to the data row (or rows if the index is not unique) having the key value. with two significant differences: The data rows are not sorted and stored in order based on their nonclustered keys. Page 166 ©Copyright 2007. The structure of the row locator depends on whether the data pages are stored in a heap or are clustered.SQL Server 2005 Clustered indexes are not a good choice for: Columns that undergo frequent changes: This results in the entire row moving (because SQL Server must keep the data values of a row in physical order). Wide keys: The key values from the clustered index are used by all nonclustered indexes as lookup keys and therefore are stored in each nonclustered index leaf entry Non Clustered Indexes Nonclustered indexes have the same B-tree structure as clustered indexes. a row locator is a pointer to the row. The items in the index are stored in the order of the index key values. Each table can include as many as 249 nonclustered indexes.Handout . If no clustered index is created on the table. the row locator is the clustered index key. This is an important consideration in high-volume transaction processing systems where data tends to be volatile. All Rights Reserved C3: Protected . so there is no restriction to have only one nonclustered index per table. the rows are not guaranteed to be in any particular order. The presence or absence of a nonclustered index doesn't affect how the data pages are organized. Instead. For a heap.
Columns frequently involved in search conditions of a query (WHERE clause) that return exact matches. Covering all columns from one table in a given query.Handout . most queries will not use the index because a table scan is usually more efficient. CREATE INDEX Creates a relational index on a specified table or view.. Syntax: Create Relational Index CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name ON <object> ( column [ ASC | DESC ] [ . Queries that do not return large result sets. An index can be created before there is data in the table... Indexes can be created on tables or views in another database by specifying a qualified database name. such as only 1 and 0.. Decision-support-system applications for which joins and grouping are frequently required.n ] ) ] Page 167 ©Copyright 2007. This eliminates accessing the table or clustered index altogether.. Cognizant Technology Solutions.n ] ) ] [ WITH ( <relational_index_option> [ .. If there are very few distinct values. Create multiple nonclustered indexes on columns involved in join and grouping operations.SQL Server 2005 The Nonclustered index structure is shown in the following graphic: Nonclustered indexes can be used for: Columns that contain a large number of distinct values. and a clustered index on any foreign key columns.n ] ) [ INCLUDE ( column_name [ . All Rights Reserved C3: Protected .. or an XML index on a specified table.. such as a combination of last name and first name (if a clustered index is used for other columns)..
Handout - SQL Server 2005
[ ON { partition_scheme_name ( column_name ) | filegroup_name | default } ] [ ; ] <object> ::= { [ database_name. [ schema_name ] . | schema_name. ] table_or_view_name } <relational_index_option> ::= { | | | | | | | | | } Create XML Index CREATE [ PRIMARY ] XML INDEX index_name ON <object> ( xml_column_name ) [ USING XML INDEX xml_index_name [ FOR { VALUE | PATH | PROPERTY } ] [ WITH ( <xml_index_option> [ ,...n ] ) ] [ ; ] <object> ::= { [ database_name. [ schema_name ] . | schema_name. ] table_name } <xml_index_option> ::= { PAD_INDEX = { ON | OFF } PAD_INDEX = { ON | OFF } FILLFACTOR = fillfactor SORT_IN_TEMPDB = { ON | OFF } IGNORE_DUP_KEY = { ON | OFF } STATISTICS_NORECOMPUTE = { ON | OFF } DROP_EXISTING = { ON | OFF } ONLINE = { ON | OFF } ALLOW_ROW_LOCKS = { ON | OFF } ALLOW_PAGE_LOCKS = { ON | OFF } MAXDOP = max_degree_of_parallelism
Page 168 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
| | | | | | | }
FILLFACTOR = fillfactor SORT_IN_TEMPDB = { ON | OFF } STATISTICS_NORECOMPUTE = { ON | OFF } DROP_EXISTING = { ON | OFF } ALLOW_ROW_LOCKS = { ON | OFF } ALLOW_PAGE_LOCKS = { ON | OFF } MAXDOP = max_degree_of_parallelism
Backward Compatible Relational Index Important The backward compatible relational index syntax structure will be removed in a future version of SQL Server. Avoid using this syntax structure in new development work, and plan to modify applications that currently use the feature. Use the syntax structure specified in <relational_index_option> instead. CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name ON <object> ( column_name [ ASC | DESC ] [ ,...n ] ) [ WITH <backward_compatible_index_option> [ ,...n ] ] [ ON { filegroup_name | "default" } ] <object> ::= { [ database_name. [ owner_name ] . | owner_name. ] table_or_view_name } <backward_compatible_index_option> ::= { | | | | | } Arguments: UNIQUE: Creates a unique index on a table or view. A unique index is one in which no two rows are permitted to have the same index key value. A clustered index on a view must be unique. The SQL Server 2005 Database Engine does not allow creating a unique index on columns that already include duplicate values, whether or not IGNORE_DUP_KEY is set to ON. If this is tried, the Database Engine displays an error message. Duplicate PAD_INDEX FILLFACTOR = fillfactor SORT_IN_TEMPDB IGNORE_DUP_KEY STATISTICS_NORECOMPUTE DROP_EXISTING
Page 169 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
values must be removed before a unique index can be created on the column or columns. Columns that are used in a unique index should be set to NOT NULL, because multiple null values are considered duplicates when a unique index is created. CLUSTERED: Creates an index in which the logical order of the key values determines the physical order of the corresponding rows in a table. The bottom, or leaf, level of the clustered index contains the actual data rows of the table. A table or view is allowed one clustered index at a time. For more information, see Clustered Index Structures. A view with a unique clustered index is called an indexed view. Creating a unique clustered index on a view physically materializes the view. A unique clustered index must be created on a view before any other indexes can be defined on the same view. For more information, see Designing Indexed Views. Create the clustered index before creating any nonclustered indexes. Existing nonclustered indexes on tables are rebuilt when a clustered index is created. If CLUSTERED is not specified, a nonclustered index is created. NONCLUSTERED Creates an index that specifies the logical ordering of a table. With a nonclustered index, the physical order of the data rows is independent of their indexed order. For more information, see Nonclustered Index Structures. Each table can have up to 249 nonclustered indexes, regardless of how the indexes are created: either implicitly with PRIMARY KEY and UNIQUE constraints, or explicitly with CREATE INDEX. For indexed views, nonclustered indexes can be created only on a view that has a unique clustered index already defined. The default is NONCLUSTERED. index_name: Is the name of the index. Index names must be unique within a table or view but do not have to be unique within a database. Index names must follow the rules of identifiers. Primary XML index names cannot start with the following characters: #, ##, @, or @@.
Is the column or columns on which the index is based. Specify two or more column names to create a composite index on the combined values in the specified columns. List the columns to be included in the composite index, in sort-priority order, inside the parentheses after table_or_view_name. Up to 16 columns can be combined into a single composite index key. All the columns in a composite index key must be in the same table or view. The maximum allowable size of the combined index values is 900 bytes. For more information about variable type columns in composite indexes, see the Remarks section. Columns that are of the large object (LOB) data types ntext, text, varchar(max), nvarchar(max), varbinary(max), xml, or image cannot be specified as key columns for an index. Also, a view definition cannot include ntext, text, or image columns, even if they are not referenced in the CREATE INDEX statement.
Page 170 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
You can create indexes on CLR user-defined type columns if the type supports binary ordering. You can also create indexes on computed columns that are defined as method invocations off a user-defined type column, as long as the methods are marked deterministic and do not perform data access operations. For more information about indexing CLR user-defined type columns, see CLR User-defined Types. [ ASC | DESC ]: Determines the ascending or descending sort direction for the particular index column. The default is ASC. INCLUDE ( column [ ,... n ] ): Specifies the nonkey columns to be added to the leaf level of the nonclustered index. The nonclustered index can be unique or nonunique. The maximum number of included nonkey columns is 1,023 columns; the minimum number is 1 column. Column names cannot be repeated in the INCLUDE list and cannot be used simultaneously as both key and nonkey columns. For more information, see Index with Included Columns. All data types are allowed except text, ntext, and image. The index must be created or rebuilt offline (ONLINE = OFF) if any one of the specified nonkey columns are varchar(max), nvarchar(max), or varbinary(max) data types. Computed columns that are deterministic and either precise or imprecise can be included columns. Computed columns derived from image, ntext, text, varchar(max), nvarchar(max), varbinary(max), and xml data types can be included nonkey columns as long as the computed column data types is allowable as an included column. For more information, see Creating Indexes on Computed Columns. ON partition_scheme_name ( column_name ): Specifies the partition scheme that defines the filegroups onto which the partitions of a partitioned index will be mapped. The partition scheme must exist within the database by executing either CREATE PARTITION SCHEME or ALTER PARTITION SCHEME. column_name specifies the column against which a partitioned index will be partitioned. This column must match the data type, length, and precision of the argument of the partition function that partition_scheme_name is using. column_name is not restricted to the columns in the index definition. Any column in the base table can be specified, except when partitioning a UNIQUE index, column_name must be chosen from among those used as the unique key. This restriction allows the Database Engine to verify uniqueness of key values within a single partition only. If partition_scheme_name or filegroup is not specified and the table is partitioned, the index is placed in the same partition scheme, using the same partitioning column, as the underlying table. You cannot specify a partitioning scheme on an XML index. If the base table is partitioned, the XML index uses the same partition scheme as the table. For more information about partitioning indexes, see Special Guidelines for Partitioned Indexes.
Page 171 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
The term default. You cannot create an XML index on a non-xml column. xml_column_name: Is the xml column on which the index is based. For more information. In the PATH secondary index. | FOR { VALUE | PATH PROPERTY }: Specifies the type of secondary XML index. The clustering key of the user table is limited to 15 columns. multiple secondary XML indexes can be created on an xml column. If "default" is specified. VALUE: Creates a secondary XML index on columns where key columns are (node value and path) of the primary XML index. You cannot create a primary XML index on a computed xml column. When PRIMARY is specified. You cannot create an XML index. It is an identifier for the default filegroup and must be delimited. All Rights Reserved C3: Protected . however. is not a keyword. A primary XML index on an xml column must exist before a secondary XML index can be created on the column. Only one xml column can be specified in a single XML index definition. Specifically. the path and node values are key columns that allow efficient seeks when searching for paths. as in ON "default" or ON [default]. The SET option settings must be the same as those required for indexed views and computed column indexes. If no location is specified and the table or view is not partitioned. Each table can have up to 249 XML indexes.Handout .SQL Server 2005 ON filegroup_name: Creates the specified index on the specified filegroup. on an xml column in a view. the QUOTED_IDENTIFIER option must be ON for the current session. An XML index can only be created on a single xml column. This is the default setting. [PRIMARY] XML: Creates an XML index on the specified xml column. Each xml column in a table can have one primary XML index and multiple secondary XML indexes. the index uses the same filegroup as the underlying table or view. or updating values in the xml column. on a table-valued variable with xml columns. the option ARITHABORT must be set to ON when an XML index is created and when inserting. Cognizant Technology Solutions. see SET Options That Affect Results. XML indexes use the same filegroup as the table. a clustered index is created with the clustered key formed from the clustering key of the user table and an XML node identifier. USING XML INDEX xml_index_name: Specifies the primary XML index to use in creating a secondary XML index. Page 172 ©Copyright 2007. The filegroup must already exist. nor can you create a relational index on an xml column. either primary or secondary. Note the following when you create an XML index: A clustered index must exist on the primary key of the user table. in this context. or xml type variables. ON "default" : Creates the specified index on the default filegroup. PATH : Creates a secondary XML index on columns built on path values and node values in the primary XML index. deleting.
If the percentage specified for FILLFACTOR is not large enough to allow for one row. SORT_IN_TEMPDB = { ON | OFF } : Specifies whether to store temporary sort results in tempdb. table_or_view_name: Is the name of the table or view to be indexed. because PAD_INDEX uses the percentage specified by FILLFACTOR. but some space remains within the upper level of the index tree to allow for at least one additional index row. For more information about indexed views. Page 173 ©Copyright 2007. fillfactor must be an integer value from 1 to 100. The default is OFF. If fillfactor is 100 or 0. the Database Engine creates indexes with leaf pages filled to capacity. FILLFACTOR = fillfactor: Specifies a percentage that indicates how full the Database Engine should make the leaf level of each index page during index creation or rebuild. considering the set of keys on the intermediate pages. the Database Engine internally overrides the percentage to allow for the minimum. The default is OFF. ON: The percentage of free space that is specified by fillfactor is applied to the intermediate-level pages of the index.SQL Server 2005 PROPERTY: Creates a secondary XML index on columns (PK. The Database Engine does not dynamically keep the specified percentage of empty space in the pages. schema_name: Is the name of the schema to which the table or view belongs. The FILLFACTOR setting applies only when the index is created or rebuilt. <relational_index_option>:: = Specifies the options to use when you create the index PAD_INDEX = { ON | OFF }: Specifies index padding. WITH PAD_INDEX is equivalent to WITH PAD_INDEX = ON. see the Remarks section. Cognizant Technology Solutions. The number of rows on an intermediate index page is never less than two. leaving sufficient space for at least one row of the maximum size the index can have. regardless of how low the value of fillfactor.Handout . All Rights Reserved C3: Protected . The view must be defined with SCHEMABINDING to create an index on it. OFF or fillfactor is not specified The intermediate-level pages are filled to near capacity. The default is 0. database_name: Is the name of the database. In backward compatible syntax. path and node value) of the primary XML index where PK is the primary key of the base table. The PAD_INDEX option is useful only when FILLFACTOR is specified. <object>::=: Is the fully qualified or nonfully qualified object to be indexed. A unique clustered index must be created on a view before any nonclustered index is created.
However. In addition to the space required in the user database to create the index. The default is OFF. preexisting clustered. Cognizant Technology Solutions. WITH STATISTICS_NORECOMPUTE is equivalent to WITH STATISTICS_NORECOMPUTE = ON. see tempdb and Index Creation. OFF: An error message is issued and the entire INSERT transaction is rolled back. All Rights Reserved C3: Protected .Handout . Page 174 ©Copyright 2007. set the STATISTICS_NORECOMPUTE to OFF. this increases the amount of disk space that is used during the index build. To restore automatic statistics updating. In backward compatible syntax. DROP_EXISTING = { ON | OFF }: Specifies that the named. or XML index is dropped and rebuilt. IGNORE_DUP_KEY cannot be set to ON for XML indexes and indexes created on a view. ON: A warning message is issued and only the rows violating the unique index fail. In backward compatible syntax. WITH SORT_IN_TEMPDB is equivalent to WITH SORT_IN_TEMPDB = ON. For more information. nonclustered. The default is OFF. WITH IGNORE_DUP_KEY is equivalent to WITH IGNORE_DUP_KEY = ON. In backward compatible syntax. The IGNORE_DUP_KEY setting applies only to insert operations that occur after the index is created or rebuilt. This may reduce the time required to create an index if tempdb is on a different set of disks than the user database. The default is OFF. OFF: Automatic statistics updating are enabled. STATISTICS_NORECOMPUTE = { ON | OFF } : Specifies whether distribution statistics are recomputed. The setting has no affect during the index operation. IGNORE_DUP_KEY = { ON | OFF } : Specifies the error response to duplicate key values in a multiple-row insert operation on a unique clustered or unique nonclustered index. ON: Out-of-date statistics are not automatically recomputed. or execute UPDATE STATISTICS without the NORECOMPUTE clause. OFF: The intermediate sort results are stored in the same database as the index.SQL Server 2005 ON: The intermediate sort results that are used to build the index are stored in tempdb. tempdb must have about the same amount of additional space to hold the intermediate sort results.
An offline index operation that creates a nonclustered index acquires a Shared (S) lock on the table. This prevents all user access to the underlying table for the duration of the operation. text. varbinary(max). In backward compatible syntax. At the end of the operation. or an SCH-M (Schema Modification) lock is acquired when a clustered index is created or dropped online and when a clustered or nonclustered index is being rebuilt. ON: Long-term table locks are not held for the duration of the index operation. OFF: An error is displayed if the specified index name already exists. can be created online with the following exceptions: XML index Index on a local temp table Clustered index if the underlying table contains LOB data types: image. sort order. All Rights Reserved C3: Protected . relational or XML. acquires a Schema modification (Sch-M) lock on the table. such as SELECT statements. This prevents updates to the underlying table but allows read operations. For more information. An offline index operation that creates. A nonclustered index can be created online if the table contains LOB data types but none of these columns are used in the index definition as either key or nonkey (included) columns.SQL Server 2005 ON: The existing index is dropped and rebuilt. ntext. cannot be changed by using DROP_EXISTING. an S (Shared) lock is acquired on the source if a nonclustered index is being created. or drops a clustered index. During the main phase of the index operation. For more information. the index definition can be modified. see How Online Index Operations Work. Cognizant Technology Solutions. however. nvarchar(max). for a short period of time.Handout . Page 175 ©Copyright 2007. Initial unique clustered index on a view. or vice versa. At the start of the operation. WITH DROP_EXISTING is equivalent to WITH DROP_EXISTING = ON. The index type. The default is OFF. a primary XML index cannot be redefined as a secondary XML index. or rebuilds or drops a nonclustered index. see Lock Modes. varchar(max). ONLINE cannot be set to ON when an index is being created on a local temporary table. The index name specified must be the same as a currently existing index. OFF: Table locks are applied for the duration of the index operation. you can specify different columns. a Shared (S) lock is held on the source object for a very short period of time. ONLINE = { ON | OFF }: Specifies whether underlying tables and associated indexes are available for queries and data modification during the index operation. Also. rebuilds. Indexes. or index options. only an Intent Share (IS) lock is held on the source table. Nonclustered index defined with LOB data type columns. For more information about locks. This enables queries or updates to the underlying table and indexes to proceed. For example. and xml. including indexes on global temp tables. see Performing Index Operations Online. partition scheme.
The maximum is 64 processors. For more information. OFF: Row locks are not used. The Database Engine determines when row locks are used. The default is ON. >1 Restricts the maximum number of processors used in a parallel index operation to the specified number or fewer based on the current system workload. max_degree_of_parallelism can be 1 Suppresses parallel plan generation. ALLOW_PAGE_LOCKS = { ON | OFF } : Specifies whether page locks are allowed.indexes WHERE name = N'IX_ProductVendor_VendorID') DROP INDEX IX_ProductVendor_VendorID ON Purchasing. see Configuring Parallel Index Operations. All Rights Reserved C3: Protected . Examples: Creating a simple nonclustered index: The following example creates a nonclustered index on the VendorID column of the Purchasing. USE AdventureWorks.Handout . 0 (default) Uses the actual number of processors or fewer based on the current system workload. Use MAXDOP to limit the number of processors used in a parallel plan execution. The Database Engine determines when page locks are used. MAXDOP = max_degree_of_parallelism overrides the max degree of parallelism configuration option for the duration of the index operation.ProductVendor (VendorID). The default is ON. GO CREATE INDEX IX_ProductVendor_VendorID ON Purchasing. OFF: Page locks are not used.ProductVendor. ON: Page locks are allowed when accessing the index. Cognizant Technology Solutions. ON: Row locks are allowed when accessing the index. GO IF EXISTS (SELECT name FROM sys.ProductVendor table. GO Page 176 ©Copyright 2007.SQL Server 2005 ALLOW_ROW_LOCKS = { ON | OFF } : Specifies whether row locks are allowed.
Handout . GO IF EXISTS (SELECT name from sys. 'Ounces'.SalesPerson table. GO INSERT INTO Production.SalesPerson . Level 14. --Verify the existing value. USE AdventureWorks GO IF EXISTS (SELECT name FROM sys.UnitMeasure WHERE Name = N'Ounces'.indexes WHERE name = N'IX_SalesPerson_SalesQuota_SalesYTD') DROP INDEX IX_SalesPerson_SalesQuota_SalesYTD ON Sales.UnitMeasure(Name).indexes WHERE name = N'AK_UnitMeasure_Name') DROP INDEX AK_UnitMeasure_Name ON Production. The index will enforce uniqueness on the data inserted into the Name column. USE AdventureWorks. Name. GO CREATE UNIQUE INDEX AK_UnitMeasure_Name ON Production.UnitMeasure (UnitMeasureCode. GO The following query tests the uniqueness constraint by attempting to insert a row with the same value as that in an existing row. State 1.SQL Server 2005 Creating a simple nonclustered composite index: The following example creates a nonclustered composite index on the SalesQuota and SalesYTD columns of the Sales. Using the IGNORE_DUP_KEY option The following example demonstrates the affect of the IGNORE_DUP_KEY option by inserting multiple rows into a temporary table first with the option set to ON and again with the option set to Page 177 ©Copyright 2007. SELECT Name FROM Production. The resulting error message is: Server: Msg 2601. ModifiedDate) VALUES ('OC'. Cognizant Technology Solutions. GO CREATE NONCLUSTERED INDEX IX_SalesPerson_SalesQuota_SalesYTD ON Sales. SalesYTD).UnitMeasure. All Rights Reserved C3: Protected . The statement has been terminated.SalesPerson (SalesQuota.UnitMeasure table. GO Creating a unique nonclustered index: The following example creates a unique nonclustered index on the Name column of the Production. GetDate()). Line 1 Cannot insert duplicate key row in object 'UnitMeasure' with unique index 'AK_UnitMeasure_Name'.
INSERT INTO #Test SELECT * FROM Production. Cognizant Technology Solutions.Handout . C2 nvarchar(50). Level 16. N'Ounces'. A warning was issued and the duplicate row ignored. GO DROP TABLE #Test. GETDATE()). C3 datetime). Server: Msg 3604. GO INSERT INTO #Test VALUES (N'OC'. C3 datetime). GO SELECT COUNT(*)AS [Number of rows] FROM #Test. GO DROP TABLE #Test. USE AdventureWorks. Number of rows -------------38 Notice that the rows inserted from the Production. GO CREATE TABLE #Test (C1 nvarchar(10). GO CREATE UNIQUE INDEX AK_Index ON #Test (C2) WITH (IGNORE_DUP_KEY = OFF). INSERT INTO #Test SELECT * FROM Production. GO CREATE TABLE #Test (C1 nvarchar(10). USE AdventureWorks. but with IGNORE_DUP_KEY set to OFF. The same statements are executed again. GO Here are the results of the second INSERT statement.SQL Server 2005 OFF. N'Ounces'. GO CREATE UNIQUE INDEX AK_Index ON #Test (C2) WITH (IGNORE_DUP_KEY = ON). GO INSERT INTO #Test VALUES (N'OC'. C2 nvarchar(50).UnitMeasure table that did not violate the uniqueness constraint were successfully inserted. All Rights Reserved C3: Protected . State 1. A single row is inserted into the #Test table that will intentionally cause a duplicate value when the second multiple-row INSERT statement is executed.UnitMeasure. Line 5 Duplicate key was ignored. GO SELECT COUNT(*)AS [Number of rows] FROM #Test. A count of rows in the table returns the number of rows inserted. GO Page 178 ©Copyright 2007.UnitMeasure. but the entire transaction was not rolled back. GETDATE()).
Handout - SQL Server 2005
Here are the results of the second INSERT statement. Server: Msg 2601, Level 14, State 1, Line 5 Cannot insert duplicate key row in object '#Test' with unique index 'AK_Index'. The statement has been terminated. Number of rows -------------1 Notice that none of the rows from the Production.UnitMeasure table were inserted into the table even though only one row in the table violated the UNIQUE index constraint. Using DROP_EXISTING to drop and re-create an index The following example drops and re-creates an existing index on the ProductID column of the Production.WorkOrder table by using the DROP_EXISTING option. The options FILLFACTOR and PAD_INDEX are also set. USE AdventureWorks; GO CREATE NONCLUSTERED INDEX IX_WorkOrder_ProductID ON Production.WorkOrder(ProductID) WITH (FILLFACTOR = 80, PAD_INDEX = ON, DROP_EXISTING = ON); GO Creating an index on a view The following example creates a view and an index on that view. Two queries are included that use the indexed view. USE AdventureWorks; GO --Set the options to support indexed views. SET NUMERIC_ROUNDABORT OFF; SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON; GO --Create view with schemabinding. IF OBJECT_ID ('Sales.vOrders', 'view') IS NOT NULL DROP VIEW Sales.vOrders ; GO CREATE VIEW Sales.vOrders WITH SCHEMABINDING AS SELECT SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount)) AS Revenue, OrderDate, ProductID, COUNT_BIG(*) AS COUNT FROM Sales.SalesOrderDetail AS od, Sales.SalesOrderHeader AS o
Page 179 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
WHERE od.SalesOrderID = o.SalesOrderID GROUP BY OrderDate, ProductID; GO --Create an index on the view. CREATE UNIQUE CLUSTERED INDEX IDX_V1 ON Sales.vOrders (OrderDate, ProductID); GO --This query can use the indexed view even though the view is --not specified in the FROM clause. SELECT SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount)) AS Rev, OrderDate, ProductID FROM Sales.SalesOrderDetail AS od JOIN Sales.SalesOrderHeader AS o ON od.SalesOrderID=o.SalesOrderID AND ProductID BETWEEN 700 and 800 AND OrderDate >= CONVERT(datetime,'05/01/2002',101) GROUP BY OrderDate, ProductID ORDER BY Rev DESC; GO --This query can use the above indexed view. SELECT OrderDate, SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount)) AS Rev FROM Sales.SalesOrderDetail AS od JOIN Sales.SalesOrderHeader AS o ON od.SalesOrderID=o.SalesOrderID AND DATEPART(mm,OrderDate)= 3 AND DATEPART(yy,OrderDate) = 2002 GROUP BY OrderDate ORDER BY OrderDate ASC; GO Creating an index with included (nonkey) columns: The following example creates a nonclustered index with one key column (PostalCode) and four nonkey columns (AddressLine1, AddressLine2, City, StateProvinceID). A query that is covered by the index follows. To display the index that is selected by the query optimizer, on the Query menu in SQL Server Management Studio, select Display Actual Execution Plan before executing the query. USE AdventureWorks; GO IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'IX_Address_PostalCode') DROP INDEX IX_Address_PostalCode ON Person.Address; GO CREATE NONCLUSTERED INDEX IX_Address_PostalCode ON Person.Address (PostalCode) INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID);
Page 180 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
GO SELECT AddressLine1, AddressLine2, City, StateProvinceID, PostalCode FROM Person.Address WHERE PostalCode BETWEEN N'98000' and N'99999'; GO
Creating a primary XML index: The following example creates a primary XML index on the CatalogDescription column in the Production.ProductModel table. USE AdventureWorks; GO IF EXISTS (SELECT * FROM sys.indexes WHERE name = N'PXML_ProductModel_CatalogDescription') DROP INDEX PXML_ProductModel_CatalogDescription ON Production.ProductModel; GO CREATE PRIMARY XML INDEX PXML_ProductModel_CatalogDescription ON Production.ProductModel (CatalogDescription); GO Creating a secondary XML index: The following example creates a secondary XML index on the CatalogDescription column in the Production.ProductModel table. USE AdventureWorks; GO IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'IXML_ProductModel_CatalogDescription_Path') DROP INDEX IXML_ProductModel_CatalogDescription_Path ON Production.ProductModel; GO CREATE XML INDEX IXML_ProductModel_CatalogDescription_Path ON Production.ProductModel (CatalogDescription) USING XML INDEX PXML_ProductModel_CatalogDescription FOR PATH ; GO Creating a partitioned index: The following example creates a nonclustered partitioned index on TransactionsPS1, an existing partition scheme. This example assumes the partitioned index sample has been installed. For installation information, see Readme_PartitioningScript. USE AdventureWorks; GO IF EXISTS (SELECT name FROM sys.indexes
Page 181 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Handout - SQL Server 2005
WHERE name = N'IX_TransactionHistory_ReferenceOrderID') DROP INDEX IX_TransactionHistory_ReferenceOrderID ON Production.TransactionHistory; GO CREATE NONCLUSTERED INDEX IX_TransactionHistory_ReferenceOrderID ON Production.TransactionHistory (ReferenceOrderID) ON TransactionsPS1 (TransactionDate); GO
Database Engine Tuning Advisor
The Database Engine Tuning Advisor is a new tool in SQL Server 2005 that analyses the performance effects of workloads run against one or more databases. (Workload is a set of T-SQL statements that executes against databases) Database Engine Tuning Advisor provides higher quality recommendations to improve the performance. Database Engine Tuning Advisor replaces the most of the features of the Index Tuning Wizard in earlier versions of SQL Server. This tool also provides graphical and command-line interfaces.
Index is an on-disk structure associated with a table or view that speeds retrieval of rows from the table or view. Database Engine Tuning Advisor provides higher quality recommendations to improve the performance.
Page 182 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
but it does not recognize an intermediate state. In a relational database. Explicit transactions: Each transaction is explicitly started with the BEGIN TRANSACTION statement and explicitly ended with a COMMIT or ROLLBACK statement. Atomicity: A transaction must be an atomic unit of work. A logical unit of work must exhibit four properties. isolation. consistency. you will be able to: Identify transactions in SQL Server Define locks List the Isolation Levels Describe Query Processing Explain the overview of using Multiple Servers: o o Distributed Queries Linked Servers Transactions A transaction is a sequence of operations performed as a single logical unit of work.SQL Server 2005 Session 33: Transactions and Locking Learning Objectives After completing this session. a transaction must leave all data in a consistent state. The modifications persist even in the event of a system failure. must be correct at the end of the transaction. A transaction either recognizes data in the state it was in before another concurrent transaction modified it. All internal data structures. All Rights Reserved C3: Protected . Cognizant Technology Solutions. to qualify as a transaction. either all of its data modifications are performed. Consistency: When completed. all rules must be applied to the transaction's modifications to maintain all data integrity.Handout . SQL Server operates in the following transaction modes: Autocommit transactions: Each individual statement is a transaction. This is referred to as serializability because it results in the ability to reload the starting data and replay a series of transactions to end up with the data in the same state it was in after the original transactions were performed. or none of them is performed. called the atomicity. and durability (ACID) properties. Durability: After a transaction has completed. Page 183 ©Copyright 2007. such as B-tree indexes or doubly-linked lists. or it recognizes the data after the second transaction has completed. its effects are permanently in place in the system. Isolation: Modifications made by concurrent transactions must be isolated from the modifications made by any other concurrent transactions.
DB-Library applications and Transact-SQL scripts use the BEGIN TRANSACTION. SELECT @TranName = 'MyTransaction'. All data modifications made in the transaction become a permanent part of the database. ROLLBACK TRANSACTION or ROLLBACK WORK: Used to erase a transaction in which errors are encountered.JobCandidate WHERE JobCandidateID = 13. GO USE AdventureWorks. BEGIN TRANSACTION: Marks the starting point of an explicit transaction for a connection. Explicit Transactions An explicit transaction is one in which you explicitly define both the start and end of the transaction.Handout .0 or earlier. a Transact-SQL explicit or implicit transaction that starts under a MARS session becomes a batch-scoped transaction. COMMIT TRANSACTION. but each transaction is explicitly completed with a COMMIT or ROLLBACK statement. GO COMMIT TRANSACTION MyTransaction. Resources held by the transaction are freed. COMMIT WORK. COMMIT TRANSACTION or COMMIT WORK: Used to end a transaction successfully if no errors were encountered. Batch-scoped transactions: Applicable only to multiple active result sets (MARS). All Rights Reserved C3: Protected . or ROLLBACK WORK TransactSQL statements to define explicit transactions.SQL Server 2005 Implicit transactions: A new transaction is implicitly started when the prior transaction completes. Explicit transactions were also called user-defined or user-specified transactions in SQL Server 7. All data modified by the transaction is returned to the state it was in at the start of the transaction. Cognizant Technology Solutions.HumanResources. ROLLBACK TRANSACTION. Examples: DECLARE @TranName VARCHAR(20). BEGIN TRANSACTION @TranName. GO Page 184 ©Copyright 2007. GO DELETE FROM AdventureWorks. A batch-scoped transaction that is not committed or rolled back when a batch completes is automatically rolled back by SQL Server. Resources held by the transaction are freed.
HumanResources. If the outer transaction is committed. @CharCol) COMMIT TRANSACTION InProc. This is primarily intended to support transactions in stored procedures that can be called either from a process already in a transaction or from processes that have no active transaction. 'aaa'.'bbb'. GO /* Roll back the outer transaction. GO CREATE PROCEDURE TransProc @PriKey INT. regardless of whether or not the inner transactions were individually committed. GO CREATE TABLE TestTrans(Cola INT PRIMARY KEY. This indicates that the commit Page 185 ©Copyright 2007.JobCandidate WHERE JobCandidateID = 13. GO COMMIT TRANSACTION CandidateDelete. */ BEGIN TRANSACTION OutOfProc. GO EXEC TransProc 1. GO /* The following SELECT statement shows only rows 3 and 4 are still in the table. @CharCol) INSERT INTO TestTrans VALUES (@PriKey + 1. this will roll back TransProc's nested transaction. GO Nesting Transactions Explicit transactions can be nested. USE AdventureWorks. GO EXECUTE TransProc 3. */ ROLLBACK TRANSACTION OutOfProc. GO DELETE FROM AdventureWorks. All Rights Reserved C3: Protected . @CharCol CHAR(3) AS BEGIN TRANSACTION InProc INSERT INTO TestTrans VALUES (@PriKey. GO /* Start a transaction and execute TransProc. If the outer transaction is rolled back. then the inner nested transactions are also committed. then all inner transactions are also rolled back.Handout . GO USE AdventureWorks.SQL Server 2005 BEGIN TRANSACTION CandidateDelete WITH MARK N'Deleting a Job Candidate'. The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction. Colb CHAR(3) NOT NULL). Cognizant Technology Solutions.
such as a SELECT statement. Page 186 ©Copyright 2007. SQL server can lock the following resources: RID: Row identifier used to lock a single row within a table Key: Row lock within an index used to protect key changes in serializable transactions Page: Data page or index page (8 KB) Extent: Contiguous group of eight data pages Table: Entire table including all table and indexes DB: Database FILE: A database file. Cognizant Technology Solutions.SQL Server 2005 of the inner transaction from the first EXECUTE statement of TransProc was overridden by the subsequent rollback. The Microsoft SQL Server Database Engine locks resources using different lock modes that determine how the resources can be accessed by concurrent transactions Lock modes that uses Database Engine : Shared (S): Used for read operations that do not change or update data. Achieved by managing the commit process in two phases known as a two-phase commit (2PC). Ensures transactional integrity: Prevent "reads" on data being modified by other users Prevent multiple users from changing same data at simultaneously Locks are managed internally by a part of the Database Engine called the lock manager. All Rights Reserved C3: Protected . such as Microsoft Distributed Transaction Coordinator (MS DTC). Instance of the SQL Server Database Engine can operate as a resource manager in distributed transactions coordinated by transaction managers.Handout . Distributed transactions span two or more servers known as resource managers. The management of the transaction must be coordinated between the resource managers by a server component called a transaction manager.: Prepare phase Commit phase Locks Locking is a mechanism used by the Microsoft SQL Server Database Engine to synchronize access by multiple users to the same piece of data at the same time. GO Distributed Transactions A transaction within a single instance of the Database Engine that spans two or more databases is actually a distributed transaction. */ SELECT * FROM TestTrans.
NET compared with the isolation levels in SQL Server 2005 because ADO. locking. All Rights Reserved C3: Protected . Bulk Update (BU) and Key-range Isolation Levels Isolation levels allow you to control the consistency level while manipulating data when multiple processes might be running concurrently. Put simply. Cognizant Technology Solutions. SQL Server 2005 supports five isolation levels: Read uncommitted Read committed Repeatable read Snapshot Serializable Page 187 ©Copyright 2007. which uses the following syntax: SET TRANSACTION ISOLATION LEVEL { READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SNAPSHOT | SERIALIZABLE } A sample usage of this command with the BEGIN TRANSACTION command is shown here: SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED BEGIN TRANSACTION SELECT TestColumn FROM TestTable COMMIT As you can see from the syntax. Schema .NET was not written exclusively for SQL Server. The isolation behavior of a transaction can be tweaked to your application's needs. Prevents a common form of deadlock that occurs when multiple sessions are reading. This is generally done by setting the isolation level of a transaction. Other lock modes like Intent . Isolation Levels in SQL Server 2005: You can set isolation levels in SQL Server 2005 by using the SET TRANSACTION ISOLATION LEVEL T-SQL command. isolation levels determine how concurrent transactions behave. Do they block each other? Do they let each other step over themselves? Or do they present a snapshot of a previous stable state of data in the event of an overstepping? You might find a slight mismatch between the isolation levels defined in ADO. We'll begin by looking at the isolation-level support in SQL Server 2005. Update (U): Used on resources that can be updated.Handout .SQL Server 2005 Exclusive (X): Ensures that multiple updates cannot be made to the same resource at the same time. and potentially updating resources.
This makes sense because you are trying to read the same data that instance 1 is busy modifying. 4. As you will see shortly. you essentially tell the database to violate all locks and read the current immediate state of data. Execute the SELECT query again. You should get 100 as the result. 9. This isolation level respects locks and prevents dirty reads from occurring. Create a table called Test with the following data in it. In each instance. SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 7. You will find that the query isn't blocked. your query did not get blocked. As a matter of fact. however. Therefore. you ended up reading data that was never meant to be final. our second transaction (the autocommit mode transaction in the SELECT query) was blocked by the transaction executing the UPDATE query. execute the same SELECT query again. You will notice that your SELECT query is blocked. Read Committed Isolation Level Read committed is the default isolation level in both SQL Server and Oracle databases. your query will remain blocked or will simply time out. ------------------100 3. you might end up with a dirty readreading data that is not yet committed. until we explicitly requested that the isolation level be changed to read uncommitted. You should therefore avoid this isolation level because it can return logically corrupt data. SELECT TestColumn FROM Test WHERE TestId = 1 8.Handout . instance 2 returned different results for the same query at different times. TestID TestColumn 2. Back in instance 2. Cognizant Technology Solutions. this isolation level is the default because it represents the best compromise between data integrity and performance. use the database that contains the Test table. In instance 1.SQL Server 2005 Read Uncommitted Isolation Level: By specifying the read uncommitted isolation level. All Rights Reserved C3: Protected . but because you explicitly requested a dirty read by specifying the READ UNCOMMITTED isolation level. On the upside. it produces 200 as a result. So the downside is that you ended up reading logically incorrect data. 1. 10. Go back to instance 1 and issue a ROLLBACK. the value 200 was never committed to the database. Unless instance 1 issues a COMMIT or a ROLLBACK. Open two instances of SQL Server Management Studio. Page 188 ©Copyright 2007. Execute the following T-SQL command to set the isolation level of your SELECT query to read uncommitted on the connection held by instance 2. Let's explore this isolation level by using an example. the connection worked at the read committed isolation level. As you might have noticed. But by doing so. execute the following query: SELECT TestColumn FROM Test WHERE TestId = 1 5. In the example you saw earlier. These two instances will be used to simulate two users running two concurrent transactions. 6. execute an UPDATE on the row of data by executing the following code block: BEGIN TRANSACTION UPDATE Test SET TestColumn = 200 WHERE TestId = 1 In instance 2 of Management Studio. Cancel your blocked SELECT query by pressing Alt+Break or clicking the Cancel button on the toolbar.
is that a concurrent transaction can add new data that matches the WHERE clause of the original transaction. TestColumn = 100. Transaction 1 runs an UPDATE query and modifies TestColumn for the rows with TestColumn = 100. Repeatable Read Isolation Level As the name suggests. so you should use this isolation level only when necessary. Transaction 1 can no longer repeat its initial read because the row no longer exists. Transaction 2 commits. This is because the first transaction will place a lock only on the rows it originally read into its result set. Transaction 2 commits. Transaction 2 changes the value of the same row read by transaction 1. Transaction 1 has inconsistent data because the row now contains different values from the previous read. TestColumn = 100. however. A phantom read can occur in the following type of situation: Transaction 1 begins. phantom reads can still occur.Handout . Transaction 2 commits. Transaction 2 begins. but phantom reads and nonrepeatable reads are still possible when using this isolation level. Transaction 1 reads a row. all within the scope of transaction 1. All Rights Reserved C3: Protected . Transaction 2 deletes the row that was read by transaction 1. If you examine this pattern closely. a transaction using this isolation level acquires read locks on all retrieved data but does not acquire range locks. This also ends up updating the row that transaction 2 inserted. Transaction 2 inserts a new row with TestID = 2. The good news. They can occur under the following circumstances: Transaction 1 begins. Transaction 1 reads all rows with. This is because the read committed isolation level does not prevent one transaction from changing the same data at the same time as another transaction is reading from it. Transaction 1 commits. the repeatable read isolation level prevents nonrepeatable reads. A nonrepeatable read can occur in the following type of situation: Transaction 1 begins. resulting in a phantom row. Cognizant Technology Solutions. you'll see that although nonrepeatable reads are avoided when using this isolation level. In other words. you pay a higher price in terms of concurrent transactions blocking each other. Transaction 2 begins. Page 189 ©Copyright 2007. Transaction 1 reads a row. Transaction 2 begins.SQL Server 2005 Read committed prevents dirty reads. Transaction 1 reads the row again. say. As you might expect. It does so by placing locks on the data that was used in a query within a transaction.
In a sense. Serializable Isolation Level: A transaction running at the serializable isolation level will not permit dirty reads. it will severely affect system performance. This nonblocking. Application architectures frequently present circumstances in which even the smallest transactions become a problem or transactions end up modifying so much data that their duration cannot be kept small. so care must be taken to avoid unexpected results. This places the most restrictive locks on the data being read. other transactions that attempt to work with the same data are blocked until the first transaction commits or rolls back. phantom reads. Of course. thereby affecting concurrent performance or even creating deadlocks. but transactions will block other running transactions. Transactions running under the snapshot isolation level do not create shared locks on the rows being read. the write can occur in a nonblocking fashion and other transactions will see the new version. repeated requests for the same data within a snapshot transaction guarantee the same results. This might sound like an isolation level that gives you perfect isolation behavior. thus ensuring repeatable reads without any blocking. keeping your data perfectly clean. Because the previous version is being read from tempdb. is the increased overhead on the tempdb database. once you enable snapshot isolation for a database. this is the perfect transaction. of course. This isolation level gives you consistent reads without blocking. But neither of these solutions allows you to read logically consistent data while offering nonblocking concurrent behavior. you can get away with a lower isolation level. In most practical situations. other transactions that were started before the write in the current transaction and that have already read the previous version will continue to read that version. This sounds like the best of both worldsthe responsiveness of read uncommitted combined with the consistency of repeatable read. we seem to be trading concurrent performance for logical sanctity of data. As a result. SQL Server requires you to enable the snapshot isolation level before you can use it. All Rights Reserved C3: Protected . repeatable read behavior is made possible by storing previously committed versions of rows in the tempdb database.SQL Server 2005 Because shared locks are not released until the end of the transaction. You shouldn't arbitrarily enable snapshot isolation on databases. concurrency is lower than when using the read committed isolation level. but there is a good reason why you should seldom use this isolation level. you pay a price. or modified. In addition. or nonrepeatable reads. To get around this issue. Snapshot Isolation Level: In all isolation levels previously presented. However. if you decide that your database needs this isolation level. the traditional way of getting around this problem is to allow dirty reads (and hence corrupt data) or simply reduce the duration of transactions. This isolation level places the most restrictive locks on the data being read or modified. Thus even if this transaction will keep your data perfectly clean. Because a transaction locks the data it is working on. SQL Server 2005 introduces a new isolation level: the snapshot isolation level. you can use it on individual connections by using the following T-SQL statement: SET TRANSACTION ISOLATION LEVEL SNAPSHOT Page 190 ©Copyright 2007.Handout . you can enable it by using the following T-SQL commands: ALTER DATABASE Test SET ALLOW_SNAPSHOT_ISOLATION ON As with all isolation levels. The obvious problem. For this reason. But after testing. Cognizant Technology Solutions.
but they are never required to wait until other concurrent transactions release their locks on the data being requested. The obvious advantage over read committed snapshot as compared to read committed is that your readers do not get blocked. When they request data. you are thus assured of repeatable reads. It then selects the series of steps that returns the results fastest while using fewer resources. However. you must first enable it at the database level by using the following T-SQL command: ALTER DATABASE Test SET READ_COMMITTED_SNAPSHOT ON Once you have enabled the read committed snapshot isolation level on a database. This isolation level guarantees consistency of the data over the duration of a read query within a transaction but not over the entire transaction that holds the reader. Page 191 ©Copyright 2007.Handout .SQL Server 2005 Read Committed Snapshot Isolation Level: Snapshot isolation prevents readers from being blocked by writers by providing readers with data from a previously committed version. operators. Over the duration of the transaction. all queries using the read committed isolation level will exhibit snapshot-like behavior. Query Processing Steps that SQL Server applies to process a SELECT statement: 1. 4. To use the read committed snapshot isolation level. 5. The final. Thus. The query tree is updated to record this exact series of steps. 2. It is called the read committed snapshot isolation level. Although this isolation level will give you snapshot-like behavior. 3. As the steps that require data from the base tables are processed. they are offered either a previous state of data (before any write operations) or the new state of data (after write operations). All Rights Reserved C3: Protected . The relational engine processes the data returned from the storage engine into the format defined for the result set and returns the result set to the client. this method of ensuring a repeatable read incurs additional overhead and bookkeeping for the database engine that might not be necessary in all situations. expressions. The query optimizer analyzes different ways the source tables can be accessed. The relational engine starts executing the execution plan. the relational engine requests that the storage engine pass up data from the rowsets requested from the relational engine. depending on the state of other concurrently running transactions. Cognizant Technology Solutions. and identifiers. you will not be able to do repeatable reads over the duration of a transaction. sometimes referred to as a sequence tree. The parser scans the SELECT statement and breaks it into logical units such as keywords. is built describing the logical steps needed to transform the source data into the format required by the result set. SQL Server 2005 offers a slight modification to the read committed isolation level that provides nonrepeatable reads over the duration of the transaction that are not blocked by transactions writers. optimized version of the query tree is called the execution plan. A query tree.
SQL Server 2005 Query Optimization of a single SELECT statement Distributed Queries Access data stored in multiple SQL servers Access data from heterogeneous data sources Implemented using OLE DB o OLE DB to communicate between Relational and storage engines o OLE DB exposes data in tabular objects (rowsets) o Allows rowsets to be accessed in T-SQL statements o Any data source with OLE DB provider allows heterogeneous access Two types of access are as follows: o o AD HOC queries Using linked servers Architecture shows the connections between a client computer.Handout . and an OLE DB provider Page 192 ©Copyright 2007. Cognizant Technology Solutions. an instance of SQL Server. All Rights Reserved C3: Protected .
@srvproduct = N' '. The ability to address diverse data sources similarly. Name') AS a. Cognizant Technology Solutions. SELECT a.'SELECT GroupName. Trusted_Connection=yes.* FROM OPENROWSET('SQLNCLI'.Department ORDER BY GroupName. [ @provider= ] 'provider_name' ] [ . Linked servers are applied to handle distributed queries. Create a linked server definition by running sp_addlinkedserver procedure. [ @catalog= ] 'catalog' ] Example: sp_addlinkedserver @server = N'LinkServer'. Specify connection information and a Table. ad hoc method of connecting and accessing remote data. [ @provstr= ] 'provider_string' ] [ .servers system catalog views. DepartmentID FROM AdventureWorks. Linked servers offer the following advantages: o o o o o o Remote server access. Page 193 ©Copyright 2007. [ @datasrc= ] 'data_source' ] [ . Name. Delete a linked server definition by running sp_dropserver procedure. All Rights Reserved C3: Protected . view or Select query. init_string ) AD HOC naming only for rarely used quires Frequent usage: Apply Linked servers Linked Servers: A linked server configuration enables SQL Server to execute commands against OLE DB data sources on remote servers. [ @location= ] 'location' ] [ . View information about the linked servers defined in a specific instance of SQL Server by running a query against the sys. OPENDATASOURCE function: Provides ad hoc connection information as part of a four-part object name. updates. @provider = N'SQLNCLI'. commands.SQL Server 2005 OPENROWSET function: A one-time.HumanResources. Syntax : OPENDATASOURCE ( provider_name. The ability to issue distributed queries.'. [ @srvproduct= ] 'product_name' ] [ .Handout . 'Server=Seattle1. and transactions on heterogeneous data sources across the enterprise. Apply stored procedures and catalog views to manage linked server definitions: Syntax: sp_addlinkedserver [ @server= ] 'server' [ .
Cognizant Technology Solutions.Handout .AdventureWorks.SQL Server 2005 @datasrc = N'ServerNetName'. Distributed queries access data from multiple heterogeneous data sources. A linked server configuration enables SQL Server to execute commands against OLE DB data sources on remote servers Page 194 ©Copyright 2007. Locking is a mechanism used by the Microsoft SQL Server Database Engine to synchronize access by multiple users to the same piece of data at the same time. @catalog = N'AdventureWorks' GO SELECT * FROM LinkServer. All Rights Reserved C3: Protected .Vendor Summary A transaction is a single unit of work.dbo.
SQL Server 2005 Session 36: XML Support in SQL Server Learning Objectives After completing this session. This limitation also means that you cannot use ORDER BY or GROUP BY with an XML data type. Although this data type can contain and be checked for null values. There are many cases when an application developer must transform data between XML and relational formats. FOR XML Ability to write XML to the database: Using OPENXML Ability to specify an XQuery query against XML data stored in columns and variables of the xml type. unlike other native types. All Rights Reserved C3: Protected . and even store XML and manipulate data natively in a relational database. You can use it as any of the following: A variable A parameter in a stored procedure or a user-defined function (UDF) A return value from a UDF A column in a table There are some limitations of the XML data type that you should be aware of. Page 195 ©Copyright 2007. There are several other restrictions. Any such equality comparisons require first casting the XML type to a character type. you will be able to: Apply XML in SQL Server Identify XML data type Write FOR XML commands Execute XQuery XML in SQL Server Working with XML is a common requirement of many of applications today. which we will discuss in more detail later. you cannot directly compare an instance of an XML data type to another instance of an XML data type. you can store XML in its native format. XML supports in SQL Server are as follows: o Support for URL access o Support for XML data schema o Support to parse an XML document o Ability to specify XPath queries o Ability to read data as XML: Using SELECT …. Cognizant Technology Solutions. efficiently and easily modify data within the XML without having to replace the entire contents. query the data within the XML. and index the data in the XML. o The XML Data Type SQL Server 2005 introduces a new data type for working with XML data: the XML data type.Handout . Using this new data type.
Handout . All Rights Reserved C3: Protected . Oddly enough. (Coincidentally. a string of XML data is assigned to the XML data type and the type parses it into XML. Cognizant Technology Solutions. Working with XML in Tables: As we stated earlier.) The example also checks that the XML is well formed. As with any other T-SQL variable. as shown in the following example: USE AdventureWorks GO --create the table with the XML Datatype CREATE TABLE OrdersXML (OrderDocID INT PRIMARY KEY. Then the variable is assigned a value. The XML data type also has a rich feature set that more than compensates for these limitations. you can also define a column in a table as XML. you simply declare it and assign data to it. but they don't really affect the XML data type when it is used appropriately. Inc</CompanyName> <ContactName>Stephen Forte</ContactName> <ContactTitle>Sales Representative</ContactTitle> <Address>5-9 Union Square West</Address> <City>New York</City> <PostalCode>10028</PostalCode> <Country>USA</Country> <Phone>030-0074321</Phone> <Fax>030-0076545</Fax> </Customers> ' Select @xmlData This basic example shows an XML variable being declared like any other native SQL Server data type by using the DECLARE statement. xOrders XML NOT NULL) Page 196 ©Copyright 2007. CLR-based user-defined types also support and require this same parsing functionality. which uses a generic piece of XML to represent a sales representative's data as XML: DECLARE @xmlData AS XML Set @xmlData=' <Customers> <CustomerID>CORZN</CustomerID> <CompanyName>Corzen. such as by validating that an element's start and end tags match not only in name but also in case. Working with the XML Data Type as a Variable: Let's start by writing some code that uses the new XML data type as a variable.SQL Server 2005 These might seem like pretty severe restrictions. as in the following example.
character 14. or loading from a SELECT statement using the FOR XML TYPE feature. Cognizant Technology Solutions. Line 1 XML parsing: line 1. loading from an XML variable (as shown here). foreign keys. Level 16.Handout . It cannot be declared with a UNIQUE constraint. We stated earlier that you can't compare two instances of the XML data type. which we will discuss shortly. as shown in this fragment: --Fails because of the malformed XML INSERT INTO OrdersXML (OrderDocID. @xmlData) You can insert XML into these columns in a variety of other ways: XML bulk load (which we will discuss later in the chapter). All Rights Reserved C3: Protected .SQL Server 2005 As we also stated earlier. The SQL Server COLLATE statement is meaningless with the XML data type because SQL Server does not store the XML as text. It cannot be used as a foreign key. This example takes some simple static XML and inserts it into the OrdersXML table we just created. XML cannot be used in any of those situations. the XML data type has a few other restrictions. in this case when used as a column in a table: It cannot be used as a primary key. it uses a distinct type of encoding particular to XML. xOrders) VALUES (3. '<nm>steve</NM>') The results produce the following error from SQL Server: Msg 9436. using the XML data type as a variable. It cannot be declared with the COLLATE keyword. Now let's get some data into the column. any attempt to insert malformed XML will result in an exception. therefore. USE AdventureWorks GO --Insert Static XML via a variable DECLARE @xmlData AS XML SET @xmlData = ' <Orders> <Order> <OrderID>5</OrderID> <CustomerID>65</CustomerID> <OrderAmount>25</OrderAmount> </Order> </Orders>' --insert into the table INSERT INTO OrdersXML (OrderDocID. Primary keys. rather. xOrders) Values (1. end tag does not match start tag Page 197 ©Copyright 2007. and unique constraints all require that you must be able to compare any included data types. State 1. Only wellformed XML (including fragments) can be inserted.
OrderDate FROM Sales. We'll first discuss the features common to both versions and then look closely at the new and enhanced features available in SQL Server 2005. The following insert works even if we only want <Orders> in our table because we have not declared a constraint on the column.limits the result rows for demo purposes Customer. All Rights Reserved C3: Protected . OrderHeader.Customer Customer Page 198 ©Copyright 2007. (Joins become relevant in FOR XML AUTO. these three features are also in SQL Server 2005. xOrders) VALUES (2. FOR XML RAW: FOR XML RAW produces what we call attribute-based XML. xOrders XML NOT NULL DEFAULT '<Orders/>' The following insert works because it relies on the default: INSERT INTO OrdersXML (OrderDocID. like other data types. '<blah>steve</blah>') FOR XML Commands SQL Server 2000 introduced an enhancement to the T-SQL syntax that enables normal relational queries to output their result set as XML. FOR XML RAW also doesn't interpret joins in any special way.SQL Server 2005 Defaults and Constraints The XML data type can. Cognizant Technology Solutions. conform to nullability. DEFAULT) Adding a default does not enforce just <Orders> from being added. USE AdventureWorks GO CREATE TABLE OrdersXML (OrderDocID INT PRIMARY KEY.Handout .) example of a simple query that retrieves customer and order header data. we have specified an Orders node as the default but have not yet indicated any way to enforce that. just specify this as you would for any other column. If you want to make a field required (NOT NULL) and provide a default value on your XML column.CustomerID. xOrders) Values (3. FOR XML RAW essentially creates a flat representation of the data where each row returned becomes an element and the returned columns become the attributes of each element. defaults. Insert Into OrdersXML (OrderDocID. Customer and Order Header Data with FOR XML RAW USE AdventureWorks GO SELECT TOP 10 -. and constraints. OrderHeader. using any of these three approaches: FOR XML RAW FOR XML AUTO FOR XML EXPLICIT As you probably expected.SalesOrderID. For example.
we will assume that you are working with SQL Server 2005. so you can click on the XML hyperlink in the returned results to see the results shown here: <row CustomerID="1" SalesOrderID="43860" OrderDate="2001-08-01T00:00:00" /> <row CustomerID="1" SalesOrderID="44501" OrderDate="2001-11-01T00:00:00" /> <row CustomerID="1" SalesOrderID="45283" OrderDate="2002-02-01T00:00:00" /> <row CustomerID="1" SalesOrderID="46042" OrderDate="2002-05-01T00:00:00" /> <row CustomerID="2" SalesOrderID="46976" OrderDate="2002-08-01T00:00:00" /> <row CustomerID="2" SalesOrderID="47997" OrderDate="2002-11-01T00:00:00" /> <row CustomerID="2" SalesOrderID="49054" OrderDate="2003-02-01T00:00:00" /> <row CustomerID="2" SalesOrderID="50216" OrderDate="2003-05-01T00:00:00" /> <row CustomerID="2" SalesOrderID="51728" OrderDate="2003-08-01T00:00:00" /> <row CustomerID="2" SalesOrderID="57044" OrderDate="2003-11-01T00:00:00" /> As promised. as shown here. that you will want more structured XML output.CustomerID FOR XML RAW If you are using SQL Server 2000. For example. All Rights Reserved C3: Protected .OrderDate FROM Sales. Cognizant Technology Solutions. OrderHeader. however.CustomerID. Customer and Order Header Data with FOR XML AUTO USE AdventureWorks GO SELECT TOP 10 -. OrderHeader.CustomerID = Customer.SalesOrderID.SQL Server 2005 INNER JOIN Sales. However.SalesOrderHeader OrderHeader ON OrderHeader. you get flat results where each row returned from the query becomes a single element named row and where all columns are output as attributes of that element. which leads us to the next topic.SalesOrderHeader OrderHeader Page 199 ©Copyright 2007. FOR XML AUTO: FOR XML AUTO produces attribute-based XML by default and can create nested results based on the tables in the query's join clause. you can simply change the FOR XML clause to FOR XML AUTO.Handout . using the same query just demonstrated. Odds are. FOR XML AUTO.limits the result rows for demo purposes Customer. this will be output as a stream of text to Query Analyzer.CustomerID ORDER BY Customer.Customer Customer INNER JOIN Sales.
CustomerID FOR XML AUTO Execute and click the XML hyperlink in the results. Note that FOR XML AUTO determines the element nesting order based on the order of the columns in the SELECT clause. as shown here: SELECT TOP 10 -. All Rights Reserved C3: Protected .limits the result rows for demo purposes OrderHeader.OrderDate.SalesOrderID. Customer. OrderHeader. Cognizant Technology Solutions.CustomerID ORDER BY Customer.SQL Server 2005 ON OrderHeader.CustomerID The output (as viewed in the XML viewer) now looks like this: <OrderHeader SalesOrderID="43860" OrderDate="2001-08-01T00:00:00"> <Customer CustomerID="1" /> </OrderHeader> <OrderHeader SalesOrderID="44501" OrderDate="2001-11-01T00:00:00"> <Customer CustomerID="1" /> </OrderHeader> <OrderHeader SalesOrderID="45283" OrderDate="2002-02-01T00:00:00"> <Customer CustomerID="1" /> </OrderHeader> <OrderHeader SalesOrderID="46042" OrderDate="2002-05-01T00:00:00"> <Customer CustomerID="1" /> </OrderHeader> <OrderHeader SalesOrderID="46976" OrderDate="2002-08-01T00:00:00"> <Customer CustomerID="2" /> </OrderHeader> <OrderHeader SalesOrderID="47997" OrderDate="2002-11-01T00:00:00"> Page 200 ©Copyright 2007.CustomerID = Customer. and you will see the following output: <Customer CustomerID="1"> <OrderHeader SalesOrderID="43860" OrderDate="2001-08-01T00:00:00" <OrderHeader SalesOrderID="44501" OrderDate="2001-11-01T00:00:00" <OrderHeader SalesOrderID="45283" OrderDate="2002-02-01T00:00:00" <OrderHeader SalesOrderID="46042" OrderDate="2002-05-01T00:00:00" </Customer> <Customer CustomerID="2"> <OrderHeader SalesOrderID="46976" OrderDate="2002-08-01T00:00:00" <OrderHeader SalesOrderID="47997" OrderDate="2002-11-01T00:00:00" <OrderHeader SalesOrderID="49054" OrderDate="2003-02-01T00:00:00" <OrderHeader SalesOrderID="50216" OrderDate="2003-05-01T00:00:00" <OrderHeader SalesOrderID="51728" OrderDate="2003-08-01T00:00:00" <OrderHeader SalesOrderID="57044" OrderDate="2003-11-01T00:00:00" </Customer> /> /> /> /> /> /> /> /> /> /> As you can see. You can rewrite the SELECT clause so an OrderHeader column comes before a Customer Column. the XML data has main elements named Customer (based on the alias assigned in the query) and subelements named OrderHeader (again from the alias).Handout .
you must list at least one column from the parent table before any column from a child table. and display name for the XML output. and so on. If there are three levels of tables. you must have two SELECT statements with a UNION.limits the result rows for demo purposes 1 AS Tag. FOR XML EXPLICIT is more complex than its predecessors. you are responsible for defining two additional columns that establish the hierarchical relationship of the XML: a Tag column that acts as a row's identifier and a Parent column that links child records to the parent record's Tag value (similar to EmployeeID and ManagerID). NULL AS Parent. If you add the SalesOrderDetail table. Tag. as shown here.Customer AS Customer Page 201 ©Copyright 2007. you must add another UNION statement and SELECT statement. Customer and Order Header Data with FOR XML EXPLICIT USE AdventureWorks GO SELECT TOP 2 -. So.SQL Server 2005 <Customer CustomerID="2" /> </OrderHeader> <OrderHeader SalesOrderID="49054" <Customer CustomerID="2" /> </OrderHeader> <OrderHeader SalesOrderID="50216" <Customer CustomerID="2" /> </OrderHeader> <OrderHeader SalesOrderID="51728" <Customer CustomerID="2" /> </OrderHeader> <OrderHeader SalesOrderID="57044" <Customer CustomerID="2" /> </OrderHeader> OrderDate="2003-02-01T00:00:00"> OrderDate="2003-05-01T00:00:00"> OrderDate="2003-08-01T00:00:00"> OrderDate="2003-11-01T00:00:00"> These results are probably not the results you wanted. FOR XML EXPLICIT: FOR XML EXPLICIT is the most complex but also the most useful and flexible of the three options. It produces XML by constructing a UNION query of the various levels of output elements. if again you have the Customer and SalesOrderHeader tables and you want to produce XML output. You must also alias all columns to indicate the element. NULL AS [SalesOrder!2!OrderDate] FROM Sales. CustomerID AS [Customer!1!CustomerID]. To keep the XML hierarchy matching the table hierarchy. at least one other column from the child table must come before any from the grandchild table. NULL AS [SalesOrder!2!SalesOrderID]. All Rights Reserved C3: Protected . As we said. For starters. Cognizant Technology Solutions. Keep in mind that only the first SELECT statement must enforce these rules because aliases in subsequent SELECT statements in a UNION query are ignored.Handout .
OrderHeader. Cognizant Technology Solutions.SalesOrderHeader AS OrderHeader ON OrderHeader. 1. OrderHeader. CustomerID AS [Customer!1!CustomerID].limits the result rows for demo purposes 1 AS Tag.SalesOrderID.Handout .CustomerID.CustomerID ORDER BY [Customer!1!CustomerID].limits the result rows for demo purposes 2.Customer AS Customer INNER JOIN Sales. NULL AS Parent. NULL AS [SalesOrder!2!SalesOrderID]. For example.SQL Server 2005 UNION ALL SELECT TOP 10 -. you can specify that certain values be composed as elements instead of attributes by including !ELEMENT on the end of the aliased column. Customer. All Rights Reserved C3: Protected . [SalesOrder!2!SalesOrderID] FOR XML EXPLICIT Execute and click the XML hyperlink to see the following results: <Customer CustomerID="1"> <SalesOrder SalesOrderID="43860" OrderDate="2001-08-01T00:00:00" <SalesOrder SalesOrderID="44501" OrderDate="2001-11-01T00:00:00" <SalesOrder SalesOrderID="45283" OrderDate="2002-02-01T00:00:00" <SalesOrder SalesOrderID="46042" OrderDate="2002-05-01T00:00:00" </Customer> <Customer CustomerID="2"> <SalesOrder SalesOrderID="46976" OrderDate="2002-08-01T00:00:00" <SalesOrder SalesOrderID="47997" OrderDate="2002-11-01T00:00:00" <SalesOrder SalesOrderID="49054" OrderDate="2003-02-01T00:00:00" <SalesOrder SalesOrderID="50216" OrderDate="2003-05-01T00:00:00" <SalesOrder SalesOrderID="51728" OrderDate="2003-08-01T00:00:00" <SalesOrder SalesOrderID="57044" OrderDate="2003-11-01T00:00:00" </Customer> /> /> /> /> /> /> /> /> /> /> FOR XML EXPLICIT allows for some alternative outputs that are not achievable using RAW. Page 202 ©Copyright 2007.OrderDate FROM Sales. Using FOR XML EXPLICIT USE AdventureWorks GO --XML EXPLICIT SELECT TOP 2 -.CustomerID = Customer.
SalesOrderHeader AS OrderHeader ON OrderHeader.Customer AS Customer UNION ALL SELECT TOP 10 -. Cognizant Technology Solutions.limits the result rows for demo purposes 2.SQL Server 2005 NULL AS [SalesOrder!2!OrderDate!ELEMENT] --Render as an element FROM Sales. 1. OrderHeader.CustomerID.SalesOrderID. as shown here: <Customer CustomerID="1"> <SalesOrder SalesOrderID="43860"> <OrderDate>2001-08-01T00:00:00</OrderDate> </SalesOrder> <SalesOrder SalesOrderID="44501"> <OrderDate>2001-11-01T00:00:00</OrderDate> </SalesOrder> <SalesOrder SalesOrderID="45283"> <OrderDate>2002-02-01T00:00:00</OrderDate> </SalesOrder> <SalesOrder SalesOrderID="46042"> <OrderDate>2002-05-01T00:00:00</OrderDate> </SalesOrder> </Customer> <Customer CustomerID="2"> <SalesOrder SalesOrderID="46976"> <OrderDate>2002-08-01T00:00:00</OrderDate> </SalesOrder> <SalesOrder SalesOrderID="47997"> <OrderDate>2002-11-01T00:00:00</OrderDate> </SalesOrder> <SalesOrder SalesOrderID="49054"> <OrderDate>2003-02-01T00:00:00</OrderDate> </SalesOrder> <SalesOrder SalesOrderID="50216"> <OrderDate>2003-05-01T00:00:00</OrderDate> Page 203 ©Copyright 2007. However.Customer AS Customer INNER JOIN Sales.OrderDate FROM Sales. Customer.CustomerID ORDER BY [Customer!1!CustomerID].CustomerID = Customer. [SalesOrder!2!SalesOrderID] FOR XML EXPLICIT Only one minor change was made (as indicated by the comment).Handout . OrderHeader. All Rights Reserved C3: Protected . this change has a major effect on the final output.
NULL AS [SalesOrder!2!OrderDate!ELEMENT]. OrderHeader. it also requires creating even more complex queries to get such results. Although EXPLICIT mode could create robust results.SalesOrderID.limits the result rows for demo purposes 1 AS Tag. NULL AS [SalesDetail!3!LineTotal] FROM Sales.CustomerID IN (1. OrderHeader.SQL Server 2005 </SalesOrder> <SalesOrder SalesOrderID="51728"> <OrderDate>2003-08-01T00:00:00</OrderDate> </SalesOrder> <SalesOrder SalesOrderID="57044"> <OrderDate>2003-11-01T00:00:00</OrderDate> </SalesOrder> </Customer> Notice that the OrderDate is rendered as a child element of the SalesOrder element. NULL AS Parent. OrderHeader. 2) UNION ALL SELECT 2. NULL AS [SalesDetail!3!ProductID].Handout . Cognizant Technology Solutions. you would have to write the query using FOR XML EXPLICIT. 1. NULL AS [SalesDetail!3!OrderQty]. For example.ShipDate. to add a few more fields from OrderHeader and to add some additional fields from OrderDetail. NULL. OrderHeader.CustomerID. Customer. NULL AS [SalesOrder!2!ShipDate!ELEMENT]. Page 204 ©Copyright 2007.TotalDue. NULL AS [SalesOrder!2!SalesOrderID]. NULL. Using FOR XML EXPLICIT with added fields: USE AdventureWorks GO --XML EXPLICIT SELECT --TOP 2 -.Customer AS Customer WHERE Customer. All Rights Reserved C3: Protected . CustomerID AS [Customer!1!CustomerID].OrderDate. NULL AS [SalesOrder!2!TotalDue].
allows you to more easily shape data and produce element-based XML than with the EXPLICIT option.TotalDue. 2) UNION ALL SELECT 3. OrderDetail.Customer AS Customer INNER JOIN Sales.SalesOrderDetail AS OrderDetail ON OrderDetail. the code has become quite complex and will become increasingly complex as you add additional data to the output.ProductID.CustomerID = Customer. Although this query is perfectly valid in SQL Server 2005.OrderQty. OrderDetail. OrderHeader. OrderHeader.OrderDate.CustomerID IN (1.SalesOrderHeader AS OrderHeader ON OrderHeader. Just about all of the SQL Server 2000 XML features revolve around FOR XML..SQL Server 2005 NULL FROM Sales. Page 205 ©Copyright 2007. All Rights Reserved C3: Protected . [SalesOrder!2!SalesOrderID] FOR XML EXPLICIT As you can see. FOR XML Enhancements in SQL Server 2005 As you can see. OrderDetail. 2. You can produce element-based XML with XML AUTO.Customer AS Customer INNER JOIN Sales. Customer. Cognizant Technology Solutions. You can explicitly specify a ROOT element for your output. which leads us to the new and improved FOR XML statement. 2) ORDER BY [Customer!1!CustomerID]. The new option. FOR XML PATH. OrderHeader.CustomerID = Customer.SalesOrderID.SalesOrderHeader AS OrderHeader ON OrderHeader. Following are a few ways SQL Server 2005 enhances the FOR XML feature: Using the TYPE option.ShipDate. OrderHeader.Handout . which in turn allows you to nest the results of SELECT.CustomerID. this solution is unacceptable.CustomerID IN (1. a feature that appears to be much underused by developers.FOR XML into another SELECT statement.CustomerID WHERE Customer.CustomerID INNER JOIN Sales..LineTotal FROM Sales. even some not mentioned here (such as viewing the results over HTTP). FOR XML can output XML (as opposed to streamed results) from a SELECT statement using FOR XML.SalesOrderID = OrderHeader.SalesOrderID WHERE Customer. SQL Server 2000 has a lot of XML features.
CustomerID<3 ORDER BY Customer. whitespace. as a couple of examples.SalesOrderID.customerid WHERE Customer.SQL Server 2005 FOR XML can produce XML using an XSD Schema that uses a namespace you specify.OrderDate From Sales. TYPE)--Casts to XML type SELECT @xmlData This example declares a variable of XML and then sets that variable to a casted result of a FOR XML query using the TYPE statement.Customer Customer inner join Sales.CustomerID. and null handling have been improved. as opposed to streamed results.CustomerID For XML AUTO. All Rights Reserved C3: Protected . like this: USE AdventureWorks DECLARE @xmlData AS XML SET @xmlData = (Select Customer. OrderDetail. OrderDetail. <Customer CustomerID="1"> <OrderDetail SalesOrderID="43860" OrderDate="2001-08-01T00:00:00" /> <OrderDetail SalesOrderID="44501" OrderDate="2001-11-01T00:00:00" /> <OrderDetail SalesOrderID="45283" OrderDate="2002-02-01T00:00:00" /> <OrderDetail SalesOrderID="46042" OrderDate="2002-05-01T00:00:00" /> </Customer> <Customer CustomerID="2"> <OrderDetail SalesOrderID="46976" OrderDate="2002-08-01T00:00:00" /> <OrderDetail SalesOrderID="47997" OrderDate="2002-11-01T00:00:00" /> <OrderDetail SalesOrderID="49054" OrderDate="2003-02-01T00:00:00" /> <OrderDetail SalesOrderID="50216" OrderDate="2003-05-01T00:00:00" /> <OrderDetail SalesOrderID="51728" OrderDate="2003-08-01T00:00:00" /> <OrderDetail SalesOrderID="57044" OrderDate="2003-11-01T00:00:00" /> <OrderDetail SalesOrderID="63198" OrderDate="2004-02-01T00:00:00" /> <OrderDetail SalesOrderID="69488" OrderDate="2004-05-01T00:00:00" /> </Customer> Page 206 ©Copyright 2007. Nesting.customerid=Customer. You accomplish this by using the TYPE keyword after your FOR XML statement. so we can now automatically cast the XML output from the FOR XML query into an XML data type instance.Handout . Cognizant Technology Solutions. The results of this query are shown here for demonstration purposes. but you can use this new XML variable as part of an INSERT statement (to an XML column) or pass it to a stored procedure.SalesOrderHeader OrderDetail on OrderDetail. FOR XML's TYPE Option: XML is an intrinsic data type of SQL Server 2005.
1378" OrderDate="20020201T00:00:00" ShipDate="2002-02-08T00:00:00" /> <OrderHeader SalesOrderID="46042" TotalDue="34722.5166" OrderDate="20030501T00:00:00" ShipDate="2003-05-08T00:00:00" /> <OrderHeader SalesOrderID="51728" TotalDue="3905. TYPE) AS OrderHeaders FROM Sales. The next example uses the FOR XML. TotalDue. ShipDate FROM Sales. TYPE syntax as an expression in the SELECT statement.8674" OrderDate="20011101T00:00:00" ShipDate="2001-11-08T00:00:00" /> <OrderHeader SalesOrderID="45283" TotalDue="37643.CustomerID FOR XML AUTO. 2) FOR XML AUTO The results are shown here: 1 <OrderHeader SalesOrderID="43860" TotalDue="14603.9906" OrderDate="20020501T00:00:00" ShipDate="2002-05-08T00:00:00" /> 2 <OrderHeader SalesOrderID="46976" TotalDue="10184.Customer AS Customer WHERE CustomerID IN (1. All Rights Reserved C3: Protected .2547" OrderDate="20030801T00:00:00" ShipDate="2003-08-08T00:00:00" /> Page 207 ©Copyright 2007. TYPE in any valid SQL expression.0774" OrderDate="2002-0801T00:00:00" ShipDate="2002-08-08T00:00:00" /> <OrderHeader SalesOrderID="47997" TotalDue="5469.Handout . (SELECT SalesOrderID.4078" OrderDate="20030201T00:00:00" ShipDate="2003-02-08T00:00:00" /> <OrderHeader SalesOrderID="50216" TotalDue="1935.SQL Server 2005 You can use FOR XML.7393" OrderDate="2001-0801T00:00:00" ShipDate="2001-08-08T00:00:00" /> <OrderHeader SalesOrderID="44501" TotalDue="26128. Cognizant Technology Solutions. USE AdventureWorks GO SELECT CustomerID.5941" OrderDate="20021101T00:00:00" ShipDate="2002-11-08T00:00:00" /> <OrderHeader SalesOrderID="49054" TotalDue="1739.SalesOrderHeader AS OrderHeader WHERE CustomerID = Customer. OrderDate.
you can use FOR XML PATH to specify column aliases that contain valid XPath expressions that will shape your XML output.3199" OrderDate="2004ShipDate="2004-05-08T00:00:00" /> FOR XML PATH: If you want to create element-based XML.Contact FOR XML PATH The output looks like this: <row Contact_ID="1"> <ContactName> <First>Gustavo</First> <Last>Achong</Last> </ContactName> <ContactPhone> <Phone1>398-555-0132</Phone1> </ContactPhone> </row> <row Contact_ID="2"> <ContactName> <First>Catherine</First> <Last>Abel</Last> </ContactName> <ContactPhone> <Phone1>747-555-0171</Phone1> </ContactPhone> </row> Page 208 ©Copyright 2007.9506" OrderDate="2004ShipDate="2004-02-08T00:00:00" /> SalesOrderID="69488" TotalDue="908. USE AdventureWorks GO --XML FOR PATH SELECT TOP 2 --limits result rows for demo purposes ContactID AS [@Contact_ID]. Phone AS [ContactPhone/Phone1] FROM Person. All Rights Reserved C3: Protected .Handout . LastName AS [ContactName/Last]. FirstName AS [ContactName/First]. Cognizant Technology Solutions.SQL Server 2005 <OrderHeader 1101T00:00:00" <OrderHeader 0201T00:00:00" <OrderHeader 0501T00:00:00" SalesOrderID="57044" TotalDue="4537.8484" OrderDate="2003ShipDate="2003-11-08T00:00:00" /> SalesOrderID="63198" TotalDue="4053.
TYPE) FROM Sales. All Rights Reserved C3: Protected . Using the TYPE option in conjunction with FOR XML PATH..SalesOrderDetail WHERE SalesOrderID = OrderHeader.8674"> <OrderDate>2001-11-01T00:00:00</OrderDate> <ShipDate>2001-11-08T00:00:00</ShipDate> <OrderDetail ProductID="761" OrderQty="1" LineTotal="419. as shown here: USE AdventureWorks GO SELECT CustomerID AS [@CustomerID]. ShipDate. OrderQty AS [@OrderQty].1378"> <OrderDate>2002-02-01T00:00:00</OrderDate> Page 209 ©Copyright 2007.SalesOrderHeader AS OrderHeader WHERE CustomerID = Customer. TYPE) FROM Sales. </OrderHeader> <OrderHeader SalesOrderID="45283" TotalDue="37643.Customer AS Customer WHERE CustomerID IN (1. TotalDue AS [@TotalDue]. This returns each separate Order for the customer as a new child node of the Customer ID node..917800" /> <OrderDetail ProductID="770" OrderQty="1" LineTotal="419.SalesOrderID FOR XML PATH('OrderDetail').CustomerID FOR XML PATH('OrderHeader'). you can see this in the results of the following query: <Customer CustomerID="1"> <OrderHeader SalesOrderID="43860" TotalDue="14603. Cognizant Technology Solutions. </OrderHeader> <OrderHeader SalesOrderID="44501" TotalDue="26128.7393"> <OrderDate>2001-08-01T00:00:00</OrderDate> <ShipDate>2001-08-08T00:00:00</ShipDate> <OrderDetail ProductID="761" OrderQty="2" LineTotal="838. 2) FOR XML PATH ('Customer') Isn't that much better? This query uses a subselect using the XML PATH statement in conjunction with TYPE to produce element-based XML nested inside a much larger FOR XML PATH statement.SQL Server 2005 FOR XML EXPLICIT. LineTotal AS [@LineTotal] FROM Sales.458900" /> <OrderDetail ProductID="768" OrderQty="3" LineTotal="1258. (SELECT ProductID AS [@ProductID]. OrderDate. (SELECT SalesOrderID AS [@SalesOrderID].Handout .458900" /> More.376700" /> More.. you can reproduce that awful and complex query with a much simpler version..
917800" /> <OrderDetail ProductID="757" OrderQty="4" LineTotal="3499.SQL Server 2005 <ShipDate>2002-02-08T00:00:00</ShipDate> <OrderDetail ProductID="759" OrderQty="1" LineTotal="419. TotalDue AS [@TotalDue]. TYPE) FROM Sales.LastName AS [comment()]..FirstName + ' ' + Contact. If you are familiar and comfortable with XPath. Contact. OrderDate.458900" /> <OrderDetail ProductID="758" OrderQty="3" LineTotal="2624.382000" /> <OrderDetail ProductID="750" OrderQty="2" LineTotal="4293... as shown in this example: SELECT Customer.Handout .924000" /> More..CustomerID Page 210 ©Copyright 2007.CustomerID AS [@CustomerID].. Cognizant Technology Solutions.CustomerID = Individual.9906"> <OrderDate>2002-05-01T00:00:00</OrderDate> <ShipDate>2002-05-08T00:00:00</ShipDate> <OrderDetail ProductID="763" OrderQty="2" LineTotal="838. </OrderHeader> <OrderHeader SalesOrderID="46042" TotalDue="34722.176000" /> More. The data method takes the results of the underlying query and places them all inside one element. </OrderHeader> </Customer> More.SalesOrderID FOR XML PATH('')) AS [ProductIDs] FROM Sales. All Rights Reserved C3: Protected .SalesOrderDetail WHERE SalesOrderID = OrderHeader.CustomerID FOR XML PATH('OrderHeader').Individual AS Individual ON Customer. (SELECT ProductID AS [data()] FROM Sales. The comment method takes data and transforms it into an XML comment. you might like some additional XML PATH features.SalesOrderHeader AS OrderHeader WHERE CustomerID = Customer.. ShipDate. (SELECT SalesOrderID AS [@SalesOrderID].Customer AS Customer INNER JOIN Sales. You can use the following XPath node test functions to further control the shape of your XML output: data comment node text processing-instruction The following example uses the data and comment methods of XPath.
CustomerID Page 211 ©Copyright 2007.3640"> <OrderDate>2001-07-18T00:00:00</OrderDate> <ShipDate>2001-07-25T00:00:00</ShipDate> <ProductIDs> 779 878 870 871 884 712</ProductIDs> </OrderHeader> More.CustomerID. All Rights Reserved C3: Protected .SalesOrderHeader OrderDetail ON OrderDetail. element to your FOR XML output. Cognizant Technology Solutions. as shown here: USE AdventureWorks GO --Root SELECT Customer.CustomerID<20 ORDER BY Customer. </Customer> <Customer CustomerID="11001"> <!--Eugene Huang--> <OrderHeader SalesOrderID="43767" TotalDue="3729. OrderDetail. as you can see.OrderDate FROM Sales.. 11001) FOR XML PATH ('Customer') The results are as follows.CustomerID IN (11000.9890"> <OrderDate>2001-07-22T00:00:00</OrderDate> <ShipDate>2001-07-29T00:00:00</ShipDate> <ProductIDs> 966 934 923 707 881</ProductIDs> </OrderHeader> More.Contact AS Contact ON Contact. OrderDetail.ContactID WHERE Customer. You can combine this with other FOR XML keywords. </Customer> Specifying a ROOT Element: The ROOT option allows you to add a main.Customer AS Customer INNER JOIN Sales.Handout .ContactID = Individual.SQL Server 2005 INNER JOIN Person. and the subquery of Product IDs is transformed into one element: <Customer CustomerID="11000"> <!--Jon Yang--> <OrderHeader SalesOrderID="43793" TotalDue="3756...customerid=Customer.customerid WHERE Customer.. the concatenated contact name becomes an XML comment. or root.SalesOrderID.
SQL Server 2005 FOR XML AUTO.. SQL Server 2000 introduced a feature for this purpose called OPENXML.. All Rights Reserved C3: Protected . except that the XML ROOT we specified with the ROOT keyword now surrounds the data. SQL Server 2005 also has the OPENXML functionwith some enhancements. OPENXML uses this handle along with a specified path and behaves like a database view to the XML data. so our output is surrounded with an <Orders> XML element. Cognizant Technology Solutions. OPENXML is a system function that allows an XML document to be shredded into T-SQL rows. we have been composing XML from rows of data. which it returns via an OUTPUT parameter. USE AdventureWorks DECLARE @int int DECLARE @xmlORDER varchar(1000) SET @xmlORDER =' <ROOT> <Customer CustomerID="BRU" ContactName="Andrew Brust"> <Order CustomerID="BRU" EmployeeID="5" OrderDate="2005-11-04"> <OrderDetail OrderID="10248" ProductID="16" Quantity="12"/> <OrderDetail OrderID="10248" ProductID="32" Quantity="10"/> </Order> </Customer> <Customer CustomerID="ZAC" ContactName="Bill Zack"> <Order CustomerID="ZAc" EmployeeID="3" OrderDate="2005-11-16"> <OrderDetail OrderID="10283" ProductID="99" Quantity="3"/> </Order> Page 212 ©Copyright 2007. ROOT ('Orders') The output looks like this: <Orders> <Customer CustomerID="1"> <OrderDetail SalesOrderID="43860" <OrderDetail SalesOrderID="44501" <OrderDetail SalesOrderID="45283" <OrderDetail SalesOrderID="46042" </Customer> . The following code shows an example of OPENXML in action. OPENXML Enhancements in SQL Server 2005 Up until now. To shred data into relational rows using OPENXML. but what if we already have XML data and we want to shred it back into relational data? Well. of course. we used ROOT ('Orders').. you must first create an XML document handle using the system stored procedure sp_xml_preparedocument.. so you simply choose SELECT from the OPENXML function just as you would SELECT from a table or a view.more. In this example.Handout . </Orders> OrderDate="2001-08-01T00:00:00" OrderDate="2001-11-01T00:00:00" OrderDate="2002-02-01T00:00:00" OrderDate="2002-05-01T00:00:00" /> /> /> /> The code output here is the same as any FOR XML AUTO output for this query. This system stored procedure takes an XML document and creates a representation that is referenced via a handle.
SELECT * FROM OPENXML (@int. The output looks like this: CustomerID ContactName --------------------------BRU Andrew Brust ZAC Bill Zack (2 row(s) affected) You can optionally specify if you want OPENXML to use element-based or attribute-based XML relational mapping between the rowset columns and the XML nodes. There are two ways to control the mapping.SQL Server 2005 </Customer> </ROOT>' --Create an internal representation of the XML doc EXEC sp_xml_preparedocument @int OUTPUT. WHERE. but only of elements where the category attribute is equal to "ITPro". Cognizant Technology Solutions.1) WITH (CustomerID varchar(10).Handout . the for. You use the for and let keywords to assign variables and iterate through the data within the context of the XQuery. which assumes that the XML nodes will map to corresponding rowset columns with exactly the same name. You can also use the ColPattern parameter. First. This simple code snippet iterates through each /catalog/book node using the $b variable with the for statement only where the category attribute is "ITPro" and returns as output the resulting information ordered by the author's name using the order keyword. The mapping specified in ColPattern overwrites the mapping specified by the flags parameter.ContactName varchar(20)) The code here takes the XML text and allows you to query and work with it as if it were relational data. All Rights Reserved C3: Protected . and return (FLWOR) keywords form the basis of every XQuery query you write. an XPath expression that allows you to use a schema to perform the mapping as part of SchemaDeclaration in the WITH clause. Selection Logic: FLWOR Expressions Just as SELECT. for $b in /catalog/book where $b/@category="ITPro" order by $b/author[1] descending return ($b) Page 213 ©Copyright 2007. Second. Both of these enhancements enable you to more easily work with existing XML data in an XML column or created data using FOR XML TYPE. @xmlORDER -. GROUP BY. FROM. both involving the new XML data type. For example. and the for keyword initiates a loop. and ORDER BY form the basis of SQL's selection logic. the XML data type is supported as an output column or an overflow column with the OPENXML statement. SQL Server 2005 introduces two enhancements to OPENXML. you can pass an XML data type variable directly into sp_xml_preparedocument. the following basic XQuery uses the XPath expression /catalog/book to obtain a reference to all the <book> nodes. let.OPENXML rowset provider. '/ROOT/Customer'. where. order by. (The let keyword is not supported in the SQL Server 2005 implementation of XQuery.) The where keyword works as a restriction and outputs the value of the variable. The first is to use the flags parameter.
Handout . you are ready to see it in action.99</price> </book> Page 214 ©Copyright 2007. Notice that Stephen's record is first because our order is descending by the author element.NET</title> <author>Andrew Brust</author> <price>39.query('for $b in /catalog/book where $b/@category="ITPro" order by $b/author[1] descending return ($b)') The results are as follows. All Rights Reserved C3: Protected . Cognizant Technology Solutions. DECLARE @XML xml Set @XML='<catalog> <book category="ITPro"> <title>Windows Step By Step</title> <author>Bill Zack</author> <price>49. <book category="ITPro"> <title>Windows Cluster Server</title> <author>Stephen Forte</author> <price>59.SQL Server 2005 Armed with this basic knowledge of XQuery expressions. Andrew's record is not in the output because we are restricting only for "ITPro" in the category element. Here is a simple example that uses this XQuery expression on an XML data type variable.99</price> </book> <book category="Developer"> <title>Developing ADO .99</price> </book> </catalog> ' Select @XML.99</price> </book> <book category="ITPro"> <title>Windows Step By Step</title> <author>Bill Zack</author> <price>49. We assign the XML to the variable and then use the preceding XQuery expression in the query() method (explained in the next section) of the XML data type.93</price> </book> <book category="ITPro"> <title>Windows Cluster Server</title> <author>Stephen Forte</author> <price>59.
But first we must create some sample data.Handout . Then for the Web database. In the real world. We will create a simple table that contains speakers at a software developers conference and the corresponding classes they will teach. It returns 0 if no elements match. We first create an XSD schema (for reasons that will soon become clear) for our XML column.SQL Server 2005 XQuery SQL Server 2005 has a standards-based implementation of XQuery that directly supports XQuery functions on the XML data type. including the XML data types and required properties for particular XML elements: use AdventureWorks go CREATE xml schema collection dbo. it shreds XML into multiple smaller XML results. 1. or modify nodes or sequences of nodes in an XML data type instance using XQuery Data Manipulation Language. 1 if there is a match.0" encoding="UTF-8" ?> <xs:schema xmlns:xs="http://www. depending on the result of the query.nodes() accepts an XQuery as input and returns a single-column rowset from the XML document. delete.value() accepts an XQuery as input and returns an SQL Server scalar type.modify() allows you to insert. This schema will define the type of XML allowed in the column. Instead of using an additional normalized table. we will model this as one table with the speaker's information and one XML column with the speaker's classes. xml.query() accepts an XQuery as input and returns an XML data type stream as output. xml.org/2001/XMLSchema"> <xs:element name="class"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element name="classes"> <xs:complexType> <xs:sequence> <xs:element ref="class" maxOccurs="unbounded" /> </xs:sequence> </xs:complexType> Page 215 ©Copyright 2007. It supports XQuery by using five methods of the XML data type: xml. xml.exist() uses XQuery input to return 0. In essence. you might encounter this scenario when in a back-office database you have the speaker and his classes represented in a series of one-to-many tables. xml. Cognizant Technology Solutions. Usually you normalize the data and have a one-tomany relationship between a speakers table and the classes table.w3. All Rights Reserved C3: Protected .classes_xsd As '<?xml version="1. This method is often used for query predicates. and NULL if there is no XML data on which to query. or NULL. you might "publish" a database on a frequent time interval (like a reporting database) or transform normalized data and use the XML column for easy HTML display (or XSLT transformations). We will discuss the methods of the XML data type shortly.
so you should always use an XSD schema on your XML column for the best performance. we need to get some data into the table by using some T-SQL INSERT statements.Handout . Notice that the XML column. The code here creates a primary and then a structural (PATH) index because our examples do a lot of where restrictions on the values of particular elements. ' Page 216 ©Copyright 2007. ' <classes> <class name="Writing Secure Code for ASP . an XML index works only if there is a primary key constraint on the table (which we have).NET "/> <class name="Using XQuery to Query and Manipulate XML Data in SQL Server 2005"/> <class name="SQL Server and Oracle Working Together"/> <class name="Protecting against SQL Injection Attacks "/> </classes> ' ) Insert into tblSpeakers Values('Richard Campbell'. Speaker_NM nVarChar(50). Create Table tblSpeakers ( Speaker_ID Integer Primary Key Identity.SQL Server 2005 </xs:element> </xs:schema>' Next we create our table. will fail because it violates the classes_xsd schema and does not contain a <classes> element: Insert into tblSpeakers Values('Stephen Forte'. uses the classes_xsd XSD schema described earlier. Speaker_Country nVarChar(25). 'Canada'. The last INSERT. 'Bad Speaker'. Speaker_XML. 'USA'. remember that XQuery works more efficiently if it is strongly typed. All Rights Reserved C3: Protected . As you learned earlier. --XML Index: Primary CREATE Primary XML INDEX idx_1 ON tblSpeakers (Speaker_XML) --PATH CREATE XML INDEX idx_a ON tblSpeakers (Speaker_XML) USING XML INDEX idx_1 FOR PATH Now that we have our index. Cognizant Technology Solutions. Without an XSD schema. the SQL Server 2005 XQuery engine assumes that everything is untyped and treats it as string data. tblSpeakers. Speaker_XML XML (classes_xsd) Not Null) XQuery runs more efficiently when there is an XML index on the XML column. Lastly.
'Turkey'. Cognizant Technology Solutions.SQL Server 2005 <classes> <class name="SQL Server Profiler"/> <class name="Advanced SQL Querying Techniques"/> <class name="SQL Server and Oracle Working Together"/> <class name="T-SQL Error Handling in Yukon"/> </classes> ' ) Insert into tblSpeakers Values('Tim Huckaby'. ' <classes> <class name="SOA"/> <class name="FABRIQ"/> </classes> ' ) Page 217 ©Copyright 2007. All Rights Reserved C3: Protected . 'Germany'. 'Morocco'. ' <classes> <class name="Smart Client Stuff"/> <class name="More Smart Client Stuff"/> </classes> ' ) Insert into tblSpeakers Values('Malek Kemmou'. 'USA'. ' <classes> <class name="SmartPhone 2005"/> <class name="Office System 2003"/> </classes> ' ) Insert into tblSpeakers Values('Clemens F. Vasters'.Handout . ' <classes> <class name="SmartPhone 2005"/> <class name="Office System 2003"/> </classes> ' ) Insert into tblSpeakers Values('Goksin Bakir'.
You have to first create a user-defined function (UDF) to perform the action. ' <CLASSES> <class name="SQL Server Index"/> <class name="SQL Precon"/> </CLASSES> ' ) Now that we have our data. DECLARE @XML xml Set @XML=' <classes> <class name="SQL Server Index"/> <class name="SQL Precon"/> </classes> ' Select @XML. and NULL is returned if there is no data to query on. ' <classes> <class name="SQL Server Index"/> <class name="SQL Precon"/> </classes> ' ) Insert into tblSpeakers Values('Bad Speaker'. 0 is returned if no elements match. xml. XQuery becomes very useful when you can use it to search based on the values of a particular element or attribute. The xml.exist() function accepts an XQuery as input and returns 0. it will return 0. 1 is returned if there is a match. for example). All Rights Reserved C3: Protected .exist(): Having XML in the database is almost useless unless you can query the elements and attributes of the XML data natively.exist as part of a CHECK CONSTRAINT. we will use the aforementioned methods of the XML data type inside a regular TSQL query. SQL Server does not allow you to use an xml.Handout . Cognizant Technology Solutions.SQL Server 2005 Insert into tblSpeakers Values('Kimberly L.exist('/classes') The code returns 1 because the "classes" element exists in the XML variable. To do this. depending on the result of the query. we will see if a node exists in this particular XML string of classes. 1.exist ('/dogs). or NULL. This UDF accepts an XML field and returns the value of an xml. If you change the XQuery expression to search for an XML node that does not exist (Select @XML. You can see this in action as part of a CHECK CONSTRAINT.exist() method looking for an instance of <Orders>: USE AdventureWorks GO Page 218 ©Copyright 2007. it is time to start writing some XQuery expressions in SQL Server 2005. 'USA'. For example. 'France'. Tripp'.
DoesOrderXMLDataExist(xOrders)=1)) You will most likely use the return value of xml.value(): The xml.value() function on that column by passing in the XQuery expression and the data type you Page 219 ©Copyright 2007.SQL Server 2005 CREATE FUNCTION dbo. GO To use this UDF as a CHECK CONSTRAINT. Think about it: You can run a T-SQL query and restrict the query on a value of a particular XML element! Going back to our main example. just create a table and pass to the UDF you just created the column you want to apply the constraint to. Here is the XQuery expression to do this: /classes/class[@name="SQL Server and Oracle Working Together"] This is how you put it to work: Select * From tblSpeakers Where Speaker_XML. or NULL) as part of a T-SQL WHERE clause. let's say you have an XML column and inside of a TSQL query you want to return some data from the XML as an intrinsic SQL data type.exist() (0. Cognizant Technology Solutions. For example.value() function takes a valid XQuery expression and returns an SQL Server scalar value that you specify.Handout . let's look for the value of 'SQL Server and Oracle Working Together' in the <class> element.exist('/Orders') END. All Rights Reserved C3: Protected .DoesOrderXMLDataExist (@XML XML) RETURNS bit AS BEGIN RETURN @XML. --create the table using the function CREATE TABLE OrdersXMLCheck (OrderDocID INT PRIMARY KEY. You call the xml.NET " /> <class name="Using XQuery to Query and Manipulate XML Data in SQL Server 2005" /> <class name="SQL Server and Oracle Working Together" /> <class name="Protecting against SQL Injection Attacks " /> </classes> xml. 1.exist('/classes/ class[@name="SQL Server and Oracle Working Together"]')=1 The results look like this: 1 Stephen Forte USA 2 Richard Campbell Canada < classes>data</classes> <classes/>data</classes> The XML returned in these results look like this for Stephen: <classes> <class name="Writing Secure Code for ASP . xOrders XML NOT NULL Default '<Orders/>' CONSTRAINT xml_orderconstraint CHECK(dbo.
The following XQuery expression does all the work of getting the first class's name: /classes[1]/class[1]/@name Page 220 ©Copyright 2007. This requires you to know and understand the data in your XML column.SQL Server 2005 want to convert the output to. the XML for Stephen looks like this: <classes> <class name="Writing Secure Code for ASP . the XQuery expression is placed in the value() method of the XML column (Speaker_XML in our T-SQL query). Speaker_XML. Speaker_NM. Speaker_Country. 'varchar(40)') This XQuery contains an XPath expression that navigates the first class's name attribute and a cast to varchar(40).value('/classes[1]/class[1]/@name'. You must perform an XQuery expression on an XML column as part of a regular T-SQL query. as shown here. As you'll recall from our earlier listing. What is cool is that SQL Server combines both relational queries and XQuery in one query because in this example we use a traditional T-SQL WHERE clause to show only speakers from the USA. Here's an example of the syntax against our current XML document in the database: xml.Handout . Cognizant Technology Solutions. All Rights Reserved C3: Protected . USE AdventureWorks select Speaker_ID.value('/classes[1]/class[1]/@name'.NET 3 Tim Davis USA Smart Client Stuff 7 Kimberly Smith USA SQL Server Index (3 row(s) affected) Let's dissect the XQuery expression. So in the preceding query.NET) as a varchar(40). 'varchar(40)') as Sessions From tblSpeakers where speaker_country ='USA' The results are shown here: Speaker_ID Speaker_NM Speaker_Country Session ----------------------------------------------------------------------------------1 Stephen Forte USA Writing Secure Code for ASP .NET "/> <class name="Using XQuery to Query and Manipulate XML Data in SQL Server 2005"/> <class name="SQL Server and Oracle Working Together"/> <class name="Protecting against SQL Injection Attacks "/> </classes> The following XQuery path expression returns the value of the first class's name attribute (Writing Secure Code for ASP.
Cognizant Technology Solutions. all the elements.NET " /> Instead of using xml. Speaker_NM. The results of the "sessions" column for Stephen's records are the same as in the previous example except that the Sessions column is now formatted in XML: <class name="Writing Secure Code for ASP . but you want to present the summary column in XML format. Speaker_Country.query --returns XML data type --same as previous example but returns XML select Speaker_ID. All Rights Reserved C3: Protected . xml.Handout .query() works by passing in an XQuery expression that will result in XML output.NET " /> <class name="Using XQuery to Query and Manipulate XML Data in SQL Server 2005" /> <class name="SQL Server and Oracle Working Together" /> <class name="Protecting Against SQL Injection Attacks" /> You can gain further control over your XQuery path expression by using the FLOWR expressions.SQL Server 2005 This approach is useful when you want to pull standard data out of the XML column and display it as regular scalar SQL Server data. you can write an expression like this: Page 221 ©Copyright 2007. use xml. --same as previous but returns all select Speaker_ID.value() function. you can return a larger XML result of many nodes by leaving out the [1] ordinal position indicators in your path expression. Speaker_XML. run the exact same query except with the xml. For example. or use a RETURN (the R in FLOWR) expression to completely transform the results.value(). if you want scalar data. Speaker_NM. If you want to return the same data as in the previous example. the first instance of the class element is returned.query() function works much like the xml. Speaker_Country. In this example. Speaker_XML.query(): The xml. we get all of the XML results as an XML column: <class name="Writing Secure Code for ASP .value().query(): --xml. The XQuery expression can return a single element. so you have a lot more flexibility.query('/classes[1]/class[1]') as Sessions From tblSpeakers where speaker_country ='USA' XML.query('/classes/class') as Sessions From tblSpeakers where speaker_country ='USA' The results are the same except for Stephen's classes. except it returns an XML data type value. It is useful only if you want the end result of the column in the query to be XML.
you can come up with much more interesting examples.query('/classes/ class') As Sessions From tblSpeakers Where Speaker_Country='USA' and Speaker_XML. Speaker_NM. and our XQuery expression filters only for the <class> element we are interested in. <class name="Writing Secure Code for ASP .query() or xml. Summary Reading mode used In FOR XML clause o o o o RAW AUTO EXPLICIT PATH XQuery is a language that can query structured or semi-structured XML data Page 222 ©Copyright 2007.nodes() method takes an XQuery expression just like exist(). and it yields the same results as the preceding example. each of which has its context set to a different node that the XQuery expression you supplied evaluates to. value(). Speaker_XML. All Rights Reserved C3: Protected . and query(). Cognizant Technology Solutions.SQL Server 2005 for $b in /classes/class return ($b) The expression uses the for and return keywords to loop through all of the class elements and return the values. which has '/classes/class' as its XQuery expression.query(' for $b in /classes/class return ($b) ') As Sessions From tblSpeakers Let's say you want to have more control over the XML output using xml.value() as well as combining the XQuery and a traditional T-SQL WHERE clause to show only the speakers in the United States.nodes(): The xml.) You can incorporate this expression into your T-SQL query: Select Speaker_ID. Speaker_NM.exist('/classes/ class[@name="SQL Server and Oracle Working Together"]')=1 The T-SQL WHERE clause restricts on the Speaker_Country column.NET " /> <class name="Using XQuery to Query and Manipulate XML Data in SQL Server 2005" /> <class name="SQL Server and Oracle Working Together" /> <class name="Protecting against SQL Injection Attacks " /> xml. The special XML data type is used for subqueries of XML data in your result set.Handout . Speaker_XML. xml. (Of course. Speaker_Country. Speaker_Country. You can use an XML method in both the SELECT and WHERE clauses of a single query: Select Speaker_ID.nodes() then returns instances of a special XML data type.
o query() o value() o exists() o modify() o nodes() Page 223 ©Copyright 2007.Handout .SQL Server 2005 Methods used to query or modify XML data. All Rights Reserved C3: Protected . Cognizant Technology Solutions.
Handout .com/SQL/ Books MSDN online Help Implementing a Microsoft SQL Server 2005 Database (2779A) Microsoft Offical Curriculum Page 224 ©Copyright 2007.SQL Server 2005 References Websites http://msdn. All Rights Reserved C3: Protected . Cognizant Technology Solutions.microsoft.
All Rights Reserved C3: Protected .Handout .SQL Server 2005 STUDENT NOTES: Page 225 ©Copyright 2007. Cognizant Technology Solutions.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue listening from where you left off, or restart the preview.