SQL Server 2012
SQL Server 2012
SQL Server
Data Management Using Microsoft SQL Server
Learner’s Guide
© 2013 Aptech Limited
All rights reserved.
No part of this book may be reproduced or copied in any form or by any means – graphic, electronic or
mechanical, including photocopying, recording, taping, or storing in information retrieval system or sent
or transferred without the prior written permission of copyright owner Aptech Limited.
All trademarks acknowledged.
APTECH LIMITED Contact E-mail: [email protected]
Edition 2 - 2013
Dear Learner,
We congratulate you on your decision to pursue an Aptech Worldwide course.
Aptech Ltd. designs its courses using a sound instructional design model – from conceptualization to
execution, incorporating the following key aspects:
➢
Scanning the user system and needs assessment
Needs assessment is carried out to find the educational and training needs of the learner
Technology trends are regularly scanned and tracked by core teams at Aptech Ltd. TAG* analyzes these
on a monthly basis to understand the emerging technology training needs for the Industry.
An annual Industry Recruitment Profile Survey# is conducted during August - October to understand the
technologies that Industries would be adapting in the next 2 to 3 years. An analysis of these trends &
recruitment needs is then carried out to understand the skill requirements for different roles & career
opportunities.
The skill requirements are then mapped with the learner profile (user system) to derive the Learning
objectives for the different roles.
➢
Needs analysis and design of curriculum
The Learning objectives are then analyzed and translated into learning tasks. Each learning task or
activity is analyzed in terms of knowledge, skills and attitudes that are required to perform that task.
Teachers and domain experts do this jointly. These are then grouped in clusters to form the subjects to be
covered by the curriculum.
In addition, the society, the teachers, and the industry expect certain knowledge and skills that are related
to abilities such as learning-to-learn, thinking, adaptability, problem solving, positive attitude etc. These
competencies would cover both cognitive and affective domains.
A precedence diagram for the subjects is drawn where the prerequisites for each subject are
graphically illustrated. The number of levels in this diagram is determined by the duration of the
course in terms of number of semesters etc. Using the precedence diagram and the time duration
for each subject, the curriculum is organized.
➢
Design & development of instructional materials
The content outlines are developed by including additional topics that are required for the completion of
the domain and for the logical development of the competencies identified. Evaluation strategy and
scheme is developed for the subject. The topics are arranged/organized in a meaningful sequence.
The detailed instructional material – Training aids, Learner material, reference material, project
guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage.
➢
Strategies for delivery of instruction
Careful consideration is given for the integral development of abilities like thinking, problem solving,
learning-to-learn etc. by selecting appropriate instructional strategies (training methodology),
instructional activities and instructional materials.
The area of IT is fast changing and nebulous. Hence considerable flexibility is provided in the
instructional process by specially including creative activities with group interaction between the students
and the trainer. The positive aspects of web based learning –acquiring information, organizing
information and acting on the basis of insufficient information are some of the aspects, which are
incorporated, in the instructional process.
➢
Assessment of learning
The learning is assessed through different modes – tests, assignments & projects. The assessment system
is designed to evaluate the level of knowledge & skills as defined by the learning objectives.
➢
Evaluation of instructional process and instructional materials
The instructional process is backed by an elaborate monitoring system to evaluate - on-time delivery,
understanding of a subject module, ability of the instructor to impart learning. As an integral part of this
process, we request you to kindly send us your feedback in the reply pre- paid form appended at the end
of each module.
*TAG – Technology & Academics Group comprises of members from Aptech Ltd., professors from
reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software Majors &
representatives from regulatory organizations/forums.
Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology trends.
The group interfaces with the representatives of the TAG thrice a year to review and validate the
technology and academic directions and endeavors of Aptech Ltd.
Aptech New Products Design Model
1
Key Aspects
Scanning the user Evaluation system and needs
assessment
2
3
4
of Instructional Processes and Material
Need Analysis and design of curriculum
6 Assessment of learning
Design and development of instructional material
5 Strategies for delivery of instructions
““
A but little a lot learning of
ignorance is a dangerous is just as
thing,
bad
Preface
SQL Server 2012 is the latest client-server based Relational Database Management System (RDBMS) from
Microsoft. It provides an enterprise-level data management platform for an organization. SQL Server includes
numerous features and tools that make it an outstanding database and data analysis platform. It is also targeted for
large-scale Online Transactional Processing (OLTP), data warehousing, and e-commerce applications. One of the
key features of this version of SQL Server is that it is available on the cloud platform.
The book begins with an introduction to RDBMS concepts and moves on to introduce SQL Azure briefly. The book
then covers various SQL Server 2012 topics such as data types, usage of Transact-SQL, and database objects such as
indexes, stored procedures, functions, and so on. The book also describes transactions, programming elements with
Transact-SQL, and finally troubleshooting errors with error handling techniques.
This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring you the
best and the latest in Information Technology. The process of design has been a part of the ISO 9001 certification
for Aptech-IT Division, Education Support Services. As part of Aptech’s quality drive, this team does intensive
research and curriculum enrichment to keep it in line with industry trends.
We will be glad to receive your suggestions.
Design Team
“
“
Nothing use the is a experience
waste of time wisely
if you
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
Module
RDBMS Concepts 1
Entity-Relationship (E-R) Model and Normalization 27
Introduction to SQL Server 2012 55
SQL Azure 73
Transact-SQL 85
Creating and Managing Databases 105
Creating Tables 135
Accessing Data 161
Advanced Queries and Joins 191
Using Views, Stored Procedures, and Querying Metadata 237
Indexes 281
Triggers 325
Programming Transact-SQL 363
Transactions 401
Error Handling 425
Table of Contents
“
“
Learning is not compulsory but
neither is survival
1 Session - RDBMS Concepts
Welcome to the Session, RDBMS Concepts.
This session deals with the concepts related to databases and database management
systems, explores various database models, and introduces the concept of an
RDBMS.
In this Session, you will learn to:
→
Explain the concept of data and database
→
Describe the approaches to data management
→
Define a Database Management System (DBMS) and list its benefits
→
Explain the different database models
→
Define and explain RDBMS
→
Describe entities and tables and list the characteristics of tables
→
List the differences between a DBMS and an RDBMS
1 Session
RDBMS Concepts
1.1 Introducfion
Organizations often maintain large amounts of data, which are generated as a result of day-to-
day operations. A database is an organized form of such data. It may consist of one or more
related data items called records. Think of a database as a data collection to which different
questions can be asked. For example, 'What are the phone numbers and addresses of the five
nearest post offices?' or 'Do we have any books in our library that deal with health food? If so, on
which shelves are they located?' or 'Show me the personnel records and sales figures of five best-
performing sales people for the current quarter, but their address details need not be shown'.
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
of 45
1 Session
RDBMS Concepts
An example of the file-based system is illustrated in table 1.1.
First Name Last Name Address Phone Eric David [email protected] 213-456-0987 Selena Sol
[email protected] 987-765-4321 Jordan Lim [email protected] 222-3456-123
Table 1.1: File-based System
→
Disadvantages of File-based Systems
In a file-based system, different programs in the same application may be interacting with
different private data files. There is no system enforcing any standardized control on the
organization and structure of these data files.
•
Data redundancy and inconsistency
Since data resides in different private data files, there are chances of redundancy and resulting
inconsistency. For example, a customer can have a savings account as well as a mortgage loan.
Here, the customer details may be duplicated since the programs for the two functions store their
corresponding data in two different data files. This gives rise to redundancy in the customer's
data. Since the same data is stored in two files, inconsistency arises if a change made in the data
of one file is not reflected in the other.
•
Unanticipated queries
In a file-based system, handling sudden/ad-hoc queries can be difficult, since it requires changes
in the existing programs. For example, the bank officer needs to generate a list of all the
customers who have an account balance of $20,000 or more. The bank officer has two choices:
either obtain the list of all customers and have the needed information extracted manually, or hire
a system programmer to design the necessary application program. Both alternatives are
obviously unsatisfactory. Suppose that such a program is written, and several days later, the
officer needs to trim that list to include only those customers who have opened their account one
year ago. As the program to generate such a list does not exist, it leads to a difficulty in accessing
the data.
•
Data isolation
Data are scattered in various files, and files may be in a different format. Though data used by
different programs in the application may be related, they reside as isolated data files.
•
Concurrent access anomalies
In large multi-user systems, the same file or record may need to be accessed by multiple users
simultaneously. Handling this in a file-based system is difficult.
•
Security problems
In data-intensive applications, security of data is a major concern. Users should be given access
only to required data and not to the whole database.
4 of 45
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
5 of 45
1 Session
RDBMS Concepts
Some of the benefits of using such a centralized database system are as follows:
•
The amount of redundancy in the stored data can be reduced
In an organization, several departments often store the same data. Maintaining a centralized
database helps the same data to be accessed by many departments. Thus, duplication of data or
'data redundancy' can be reduced.
•
No more inconsistencies in data
When data is duplicated across several departments, any modifications to the data have to be
reflected across all departments. Sometimes, this can lead to inconsistency in the data. As there is
a central database, it is possible for one person to take up the task of updating the data on a
regular basis. Consider that Mr. Larry Finner, an employee of an organization is promoted as a
Senior Manager from Manager. In such a case, there is just one record in the database that needs
to be changed. As a result, data inconsistency is reduced.
•
The stored data can be shared
A central database can be located on a server, which can be shared by several users. In this way
all users can access the common and updated information all the time.
•
Standards can be set and followed
A central control ensures that a certain standard in the representation of data can be set and
followed. For example, the name of an employee has to be represented as 'Mr. Larry Finner'.
This representation can be broken down into the following components: ◆
A title (Mr.) ◆
First name (Larry) ◆
Last name (Finner)
It is certain that all the names stored in the database will follow the same format if the standards
are set in this manner.
•
Data Integrity can be maintained
Data integrity refers to the accuracy of data in the database. For example, when an employee
resigns and leaves the organization, consider that the Accounts department has updated its
database and the HR department has not updated its records. The data in the company's records is
hence inaccurate.
Centralized control of the database helps in avoiding these errors. It is certain that if a record is
deleted from one table, its linked record in the other table is also deleted.
•
Security of data can be implemented
In a central database system, the privilege of modifying the database is not given to everyone.
This right is given only to one person who has full control over the database. This person is
called as Database Administrator or DBA. The DBA can implement security by placing
restrictions on the data. Based on the permissions granted to them, the users can add, modify, or
query data.
of 45
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
of 45
1 Session
RDBMS Concepts
Figure 1.2 illustrates a database system.
Figure 1.: A Simplified Database System Environment
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
of 45
1 Session
RDBMS Concepts
→
Multi-user access control
At any point of time, more than one user can access the same data. A DBMS takes care of the
sharing of data among multiple users, and maintains data integrity.
→
Database access languages and Application Programming Interfaces (APIs)
The query language of a DBMS implements data access. SQL is the most commonly used query
language. A query language is a non-procedural language, where the user needs to request what
is required and need not specify how it is to be done. Some procedural languages such as C,
Visual Basic, Pascal, and others provide data access to programmers.
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
11 of 45
1 Session
RDBMS Concepts
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
1 of 45
1 Session
RDBMS Concepts
The popular relational DBMSs are Oracle, Sybase, DB2, Microsoft SQL Server, and so on.
This model represents the database as a collection of relations. In this model's terminology, a row
is called a tuple, a column, an attribute, and the table is called a relation. The list of values
applicable to a particular field is called domain. It is possible for several attributes to have the
same domain. The number of attributes of a relation is called degree of the relation. The number
of tuples determines the cardinality of the relation.
In order to understand the relational model, consider tables 1.3 and 1.4.
Roll Number Student Name 1 Sam Reiner 2 John Parkinson 3 Jenny Smith 4 Lisa Hayes 5
Penny Walker 6 Peter Jordan 7 Joe Wong
Table 1.: Students Table
Roll Number Marks Obtained 1 34 2 87 3 45 4 90 5 36 6 65 7 89
Table 1.4: Marks Table
The Students table displays the Roll Number and the Student Name, and the Marks table displays
the Roll Number and Marks obtained by the students. Now, two steps need to be carried out for
students who have scored above 50. First, locate the roll numbers of those who have scored
above 50 from the Marks table. Second, their names have to be located in the Students table by
matching the roll number. The result will be as shown in table 1.5.
Roll Number Student Name Marks Obtained 2 John 87 4 Lisa 90 6 Peter 65
7 Joe 89
Table 1.5: Displaying Student Names and Marks
14 of 45
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
15 of 45
1 Session
RDBMS Concepts
Figure 1.5 shows two tables related to one another through a common key (data value) in a
relational database.
Figure 1.5: Relationship between Tables
Thus, a relational database is a database structured on the relational model. The basic
characteristic of a relational model is that in a relational model, data is stored in relations. To
understand relations, consider the following example.
The Capitals table shown in table 1.6 displays a list of countries and their capitals, and the
Currency table shown in table 1.7 displays the countries and the local currencies used by them.
Country Capital Greece Athens Italy Rome USA Washington China Beijing Japan Tokyo
Australia Sydney France Paris
Table 1.: Capitals
1 of 45
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
1 of 45
1 Session
RDBMS Concepts
The tables 1.8, 1.9, 1.10, and 1.11 are used to illustrate this scenario. These tables depict tuples
and attributes in the form of rows and columns. Various terms related to these tables are given in
table 1.12.
Cust_No Cust_Name Phone No 002 David Gordon 0231-5466356 003 Prince Fernandes 0221-
5762382 003 Charles Yale 0321-8734723 002 Ryan Ford 0241-2343444 005 Bruce Smith 0241-
8472198
Table 1.: Customer
Item_No Description Price HW1 Power Supply 4000 HW2 Keyboard 2000 HW3 Mouse 800
SW1 Office Suite 15000 SW2 Payroll Software 8000
Table 1.: Items
Ord_No Item_No Qty 101 HW3 50 101 SW1 150 102 HW2 10 103 HW3 50 104 HW2 25 104
HW3 100 105 SW1 100
Table 1.10 Order_Details
Ord_No Ord_Date Cust_No 101 02-08-12 002 102 11-08-12 003 103 21-08-12 003 104 28-08-
12 002 105 30-08-12 005
Table 1.11 Order_August
1 of 45
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
1 of 45
1 Session
RDBMS Concepts
Administering these resources is the responsibility of the Database Administrator. DBA is
responsible for authorizing access to the database, for coordinating and monitoring its use and
for acquiring software and hardware resources as needed. DBA is accountable for problems such
as breach of security or poor system response time.
→
Database Designer
Database Designers are responsible for identifying the data to be stored in the database and for
choosing appropriate structures to represent and store this data. It is the responsibility of database
designers to communicate with all prospective database users, in order to understand their
requirements, and to come up with a design that meets the requirements.
→
System Analysts and Application Programmers
System Analysts determine the requirements of end users, and develop specifications for pre-
determined transactions that meet these requirements. Application Programmers implement these
specifications as programs; then, they test, debug, document, and maintain these pre-determined
transactions.
In addition to those who design, use, and administer a database, others are associated with the
design, development, and operation of the DBMS software and system environment.
→
DBMS Designers and Implementers
These people design and implement the DBMS modules and interfaces as a software package. A
DBMS is a complex software system that consists of many components or modules, including
modules for implementing the catalog, query language, interface processors, data access, and
security. A DBMS must interface with other system software such as the operating system and
compilers for various programming languages.
→
End User
The end user invokes an application to interact with the system, or writes a query for easy
retrieval, modification, or deletion of data.
1.7.1 Enfity
An entity is a person, place, thing, object, event, or even a concept, which can be distinctly
identified. For example, the entities in a university are students, faculty members, and courses.
Each entity has certain characteristics known as attributes. For example, the student entity might
include attributes such as student number, name, and grade. Each attribute should be named
appropriately.
0 of 45
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
1 of 45
1
RDBMS Concepts
Session
1
RDBMS Concepts
V 1.0 © Aptech Limited
of 45
1 Session
RDBMS Concepts
1.9.1 Answers
1. C
2. D
3. B
4. B
5. C
4 of 45
Summary
→
A database is a collection of related data stored in the form of a table.
→
A data model describes a container for storing data and the process of storing and retrieving data
from that container.
→
A DBMS is a collection of programs that enables the user to store, modify, and extract
information from a database.
→
A Relational Database Management System (RDBMS) is a suite of software programs for
creating, maintaining, modifying, and manipulating a relational database.
→
A relational database is divided into logical units called tables. These logical units are
interrelated to each other within the database.
→
The main components of an RDBMS are entities and tables.
→
In an RDBMS, a relation is given more importance, whereas, in case of a DBMS, entities are
given more importance and there is no relation established among these entities.
V 1.0 © Aptech Limited
5 of 45
“
“
The is the foundation education of
of every its youth state
Session - Entity-Relationship (E-R)
Model and Normalization
Welcome to the Session, Entity-Relationship (E-R) Model and Normalization.
This session talks about Data Modeling, the E-R model, its components, symbols,
diagrams, relationships, Data Normalization, and Relational Operators.
In this Session, you will learn to:
→
Define and describe data modeling
→
Identify and describe the components of the E-R model
→
Identify the relationships that can be formed between entities
→
Explain E-R diagrams and their use
→
Describe an E-R diagram, the symbols used for drawing, and show the various relationships
→
Describe the various Normal Forms
→
Outline the uses of different Relational Operators
Session
Entity-Relationship (E-R) Model and Normalization
2.1 Introducfion
A data model is a group of conceptual tools that describes data, its relationships, and semantics.
It also consists of the consistency constraints that the data adheres to. The Entity-Relationship,
Relational, Network, and Hierarchical models are examples of data models. The development of
every database begins with the basic step of analyzing its data in order to determine the data
model that would best represent it. Once this step is completed, the data model is applied to the
data.
Session
Entity-Relationship (E-R) Model and Normalization
V 1.0 © Aptech Limited
of 45
Session
Entity-Relationship (E-R) Model and Normalization
The attributes of a car would be registration_number, model, manufacturer, color, price, owner,
and so on.
→
Entity Set
An entity set is the collection of similar entities. For example, the employees of an organization
collectively form an entity set called employee entity set.
→
Relationship Set
A collection of similar relationships between two or more entity sets is called a relationship set.
For example, employees work in a particular department. The set of all 'work in' relations that
exists between the employees and the department is called the 'work in' relationship set.
The various E-R model components can be seen in figure 2.3.
Figure .: Components of the E-R Model
Relationships associate one or more entities and can be of three types. They are as follows:
→
Self-relationships
Relationships between entities of the same entity set are called self-relationships. For example, a
manager and his team member, both belong to the employee entity set. The team member works
for the manager. Thus, the relation, 'works for', exists between two different employee entities of
the same employee entity set.
0 of 45
Strong →
entity sets
Entity sets that have enough attributes to establish a primary key are called strong entity sets.
Consider the scenario of an educational institution where at the end of each semester, students
are required to complete and submit a set of assignments. The teacher keeps track of the
assignments submitted by the students. Now, an assignment and a student can be considered as
two separate entities. The assignment entity is described by the attributes assignment_number
and subject. The student entity is described by roll_number, name, and semester. The assignment
entities can be grouped to form an assignment entity set and the student entities can be grouped
to form a student entity set. The entity sets are associated by the relation 'submitted by'. This
relation is depicted in figure 2.11.
Figure .11: Assignment Student Relation
The attributes, assignment_number and subject, are not enough to identify an assignment entity
uniquely. The roll_number attribute alone is enough to uniquely identify any student entity.
Therefore, roll_number is a primary key for the student entity set. The assignment entity set is a
weak entity set since it lacks a primary key. The student entity set is a strong entity set due to the
presence of the roll_number attribute.
Session
2.4 Normalizafion
Initially, all databases are characterized by large number of columns and records. This approach
has certain drawbacks. Consider the following details of the employees in a department. Table
2.3 consists of the employee details as well as the details of the project they are working on.
Emp_no Project_id Project_name Emp_name Grade Salary 142 113, 124 BLUE STAR,
MAGNUM John A 20,000 168 113 BLUE STAR James B 15,000 263 113 BLUE STAR
Andrew C 10,000 109 124 MAGNUM Bob C 10,000
Table .: Department Employee Details
→
Repetition anomaly
The data such as Project_id, Project_name, Grade, and Salary repeat many times. This repetition
hampers both, performance during retrieval of data and the storage capacity. This repetition of
data is called the repetition anomaly.
Session
2.4.4 Denormalizafion
By normalizing a database, redundancy is reduced. This, in turn, reduces the storage
requirements for the database and ensures data integrity. However, it has some drawbacks. They
are as follows:
→
Complex join queries may have to be written often to combine the data in multiple tables.
→
Joins may practically involve more than three tables depending on the need for information.
Session
→
→
→
2.6.1 Answers
1. A
2. B
3. C
4. D
5. D
5 of 45
Summary
→
Data modeling is the process of applying an appropriate data model to the data at hand.
→
E-R model views the real-world as a set of basic objects and relationships among them.
→
Entity, attributes, entity set, relationships, and relationship sets form the five basic components
of E-R model.
→
Mapping cardinalities express the number of entities that an entity is associated with.
→
The process of removing redundant data from the tables of a relational database is called
normalization.
→
Relational Algebra consists of a collection of operators that help retrieve data from the relational
databases.
→
SELECT, PRODUCT, UNION, and DIVIDE are some of the relational algebra operators.
V 1.0 © Aptech Limited
5 of 45
“
“
life's Learning most how important
to learn skill.
is
Session - Introduction to SQL
Server 2012
Welcome to the Session, Introduction to SQL Server 2012.
This session explains the basic architecture of SQL Server 2012 and lists the
versions and editions of SQL Server. It also explains the role and structure of SQL
Server along with the new features added in SQL Server 2012. Finally, the session
explains the process to connect to SQL Server instances, create and organize script
files, and execute Transact-SQL queries.
In this Session, you will learn to:
→
Describe the basic architecture of SQL Server 2012
→
List the various versions and editions of SQL Server
→
Explain the role and structure of SQL Server databases
→
List the new features of SQL Server 2012
→
List the process of connecting to SQL Server Instances
→
Explain script file creation and organization
→
Explain the process to execute Transact-SQL queries
Session
5 of 45
3.1 Introducfion
SQL Server is an RDBMS developed by Microsoft. It provides an enterprise-level data
management platform for an organization. SQL Server includes numerous features and tools that
make it an outstanding database and data analysis platform. It is also targeted for large-scale
Online Transactional Processing (OLTP), data warehousing, and e-commerce applications.
SQL Server 2012 is the new version of SQL Server and was launched by Microsoft on March 6,
2012. One of the major features of this version of SQL Server is that it is available on the cloud
platform. Using SQL Server 2012 not only helps an organization to store and manage huge
amount of information, but also to protect and utilize this data at different locations as required.
Session
Session
Session
Session
Session
Session
3.10.1 Answers
1. B
2. A
3. C
4. C
5. A
0 of 45
Summary
→
The basic architecture of SQL Server 2012 includes tools, services, and instances.
→
The three editions of SQL Server are Enterprise, Standard, and Business Intelligence.
→
The structure of SQL Database includes databases, security, server objects, replications,
AlwaysOn High Availability, Management, Integration Services Catalogs, and so on.
→
SSMS is used to connect to SQL Server Instances. SSMS is a tool used for developing, querying,
and managing the databases.
→
The script files should be stored in .sql format in SQL Server 2012.
→
The queries typed in Transact-SQL and saved as .sql files can be executed directly into the
SSMS query window.
V 1.0 © Aptech Limited
1 of 45
“
“
To avoid say nothing, criticism, be
nothing.
do nothing,
4 Session -
Welcome to the Session, SQL Azure.
This session explains SQL Azure and its benefits. It also lists the differences
between SQL Azure and on-premises SQL Server. Finally, the session explains the
process to connect SQL Azure with SSMS.
In this Session, you will learn to:
→
Explain SQL Azure
→
List the benefits of SQL Azure
→
State the differences between SQL Azure and on-premises SQL Server
→
List the steps to connect SQL Azure with SSMS
SQL Azure
4 Session
SQL Azure
4.1 Introducfion
Cloud computing is a technology trend, that involves the delivery of software, platforms, and
infrastructure as services through the Internet or networks. Windows Azure is a key offering in
Microsoft's suite of cloud computing products and services. The database functions of
Microsoft's cloud platform are provided by Windows Azure SQL Database, which is commonly
known as SQL Azure.
SQL Azure can be used to store and manage data using queries and other functions that are
similar to SQL Server 2012. The data on SQL Azure does not have the constraint of being
location-specific. This means that the data stored in SQL Azure can be viewed and edited from
any location, as the entire data is stored on cloud storage platform.
Session
4
SQL Azure
V 1.0 © Aptech Limited
5 of 45
4 Session
SQL Azure
SQL Azure Data Sync helps to synchronize data on the local SQL Server with the data on SQL
Azure as shown in figure 4.3.
Figure 4.: Data Sync
Data Sync also has data management capabilities that help to share data easily between different
SQL databases. Data Sync is not only used for synchronizing on-premises to SQL Azure, but
also to synchronize one SQL Azure account to another.
Session
4
SQL Azure
V 1.0 © Aptech Limited
of 45
4 Session
SQL Azure
Session
4
SQL Azure
Click Connect. The connection to the Database is successfully established as shown in figure 4.5.
V 1.0 © Aptech Limited
of 45
4 Session
SQL Azure
Session
4
SQL Azure
V 1.0 © Aptech Limited
1 of 45
Session
of 45
→
→
→
→
→
→
→
4
SQL Azure
V 1.0 © Aptech Limited
Summary
Microsoft SQL Azure is a cloud based relational database service that leverages existing SQL
Server technologies.
SQL Azure enables users to perform relational queries, search operations, and synchronize data
with mobile users and remote back offices.
SQL Azure can store and retrieve both structured and unstructured data.
Applications retrieve data from SQL Azure through a protocol known as Tabular Data Stream
(TDS).
The three core objects in the SQL Azure operation model are account, server, and database.
SQL Azure Data Sync helps to synchronize data on the local SQL Server with the data on SQL
Azure.
Users can connect to SQL Azure using SSMS.
1.
Session
4
SQL Azure
V 1.0 © Aptech Limited
Try It Yourself
List out some organizational scenarios where using SQL Azure database would be more
advantageous than using on-premises SQL Server database.
of 45
“
Practice is the best of all
instructors
“
5
Welcome to the Session, Transact-SQL.
This session explains Transact-SQL and the different categories of Transact-SQL
statements. It also explains the various data types and elements supported by
Transact-SQL. Finally, the session explains set theory, predicate logic, and the
logical order of operators in the SELECT statement.
In this Session, you will learn to:
Explain Transact-SQL
List the different categories of Transact-SQL statements
Explain the various data types supported by Transact-SQL
Explain Transact-SQL language elements
Explain sets and predicate logic
Describe the logical order of operators in the SELECT statement
Session - Transact-SQL
→
→
→
→
→
→
5 Session
Transact-SQL
5.1 Introducfion
SQL is the universal language used in the database world. Most modern RDBMS products use
some type of SQL dialect as their primary query language. SQL can be used to create or destroy
objects, such as tables, on the database server and to do things with those objects, such as put
data into them or query for data. Transact-SQL is Microsoft's implementation of the standard
SQL. Usually referred to as T-SQL, this language implements a standardized way to
communicate to the database. The Transact-SQL language is an enhancement to SQL, the
American National Standards Institute (ANSI) standard relational database language. It provides
a comprehensive language that supports defining tables, inserting, deleting, updating, and
accessing the data in the table.
5.2 Transact-SQL
Transact-SQL is a powerful language offering features such as data types, temporary objects, and
extended stored procedures. Scrollable cursors, conditional processing, transaction control, and
exception and error-handling are also some of the features which are supported by Transact-
SQL.
The Transact-SQL language in SQL Server 2012 provides improved performance, increased
functionality, and enhanced features. Enhancements include scalar functions, paging, sequences,
meta-data discovery, and better error handling support.
Code Snippet 1 shows the Transact-SQL statement, SELECT, which is used to retrieve all
records of employees with 'Design Engineer' as the JobTitle from the Employee table.
Code Snippet 1:
SELECT LoginID
FROM Employee
WHERE JobTitle = 'Design Engineer'
Figure 5.1 shows the result that retrieves all records of employees with 'Design Engineer' as the
JobTitle from the Employee table.
Figure 5.1: Output of SELECT Statement
Transact-SQL includes many syntax elements that are used by or that influence most statements.
These elements include data types, predicates, functions, variables, expressions, control-of-flow,
comments, and batch separators.
of 45
Session
5
Transact-SQL
V 1.0 © Aptech Limited
of 45
5 Session
Transact-SQL
5
Transact-SQL
V 1.0 © Aptech Limited
of 45
5 Session
Transact-SQL
Alias data types can be created using the CREATE TYPE statement. The syntax for the
CREATE TYPE statement is as follows: Syntax:
CREATE TYPE [ schema_name. ] type_name { FROM base_type [ ( precision [ , scale ] ) ] [ NULL |
NOT NULL ] } [ ; ]
where,
schema_name: identifies the name of the schema in which the alias data type is being created. A
schema is a collection of objects such as tables, views, and so forth in a database.
type_name: identifies the name of the alias type being created.
base_type: identifies the name of the system-defined data type based on which the alias data type
is being created.
precision and scale: specify the precision and scale for numeric data.
NULL | NOT NULL: specifies whether the data type can hold a null value or not.
Code Snippet 2 shows how to create an alias data type using CREATE TYPE statement.
Code Snippet 2:
CREATE TYPE usertype FROM varchar(20) NOT NULL
In the code, the built-in data type varchar is stored as a new data type named usertype by using
the CREATE TYPE statement.
→
User-defined types
These are created using programming languages supported by the .NET Framework. 5.5
Transact-SQL Language Elements
The Transact-SQL language elements are used in SQL Server 2012 for working on the data that
is entered in SQL Server database. The Transact-SQL language elements includes predicates,
operators, functions, variables, expressions, control-of-flow, errors, and transactions, comments,
and batch separators. 5.5.1 Predicates and Operators
Predicates are used to evaluate whether an expression is TRUE, FALSE, or UNKNOWN. Some
of the predicates available in Transact-SQL are as follows:
→
IN - Determines whether a specified value matches any value in a subquery or a list.
→
BETWEEN - Specifies a range of values to test.
→
LIKE - Used to match characters against a specified pattern.
→
CONTAINS - Searches for precise or less precise matches to single words and phrases, words
within a certain distance of one another, or weighted matches.
0 of 45
Session
5
Transact-SQL
V 1.0 © Aptech Limited
1 of 45
5 Session
Transact-SQL
Code Snippet 3 shows execution of operators according to precedence. Code Snippet 3:
DECLARE @Number int;
SET @Number = 2 + 2 * (4 + (5 - 3))
SELECT @Number
Here, the steps to arrive at the result are as follows:
1.
2 + 2 * (4 + (5 – 3))
2.
2 + 2 * (4 + 2)
3.
2+2*6
4.
2 + 12
5.
14
Hence, the code will display 14.
5.5.2 Funcfions
A function is a set of Transact-SQL statements that is used to perform some task. Transact-SQL
includes a large number of functions. These functions can be useful when data is calculated or
manipulated. In SQL, functions work on the data, or group of data, to return a required value.
They can be used in a SELECT list, or anywhere in an expression. The four types of functions in
SQL Server 2012 are as follows:
→
Rowset functions - In Transact-SQL, the rowset function is used to return an object that can be
used in place of a table reference. For example, OPENDATASOURCE, OPENQUERY,
OPENROWSET, and OPENXML are rowset functions.
→
Aggregate functions - Transact-SQL provides aggregate functions to assist with the
summarization of large volumes of data. For example, SUM, MIN, MAX, AVG, COUNT,
COUNTBIG, and so on are aggregate functions.
→
Ranking functions - Many tasks, such as creating arrays, generating sequential numbers, finding
ranks, and so on can be implemented in an easier and faster way by using ranking functions. For
example, RANK, DENSE _ RANK, NTILE, and ROW _ NUMBER are ranking functions.
→
Scalar functions - In scalar functions, the input is a single value and the output received is also a
single value.
of 45
5.5.3 Variables
A variable is an object that can hold a data value. In Transact-SQL, variables can be classified
into local and global variables.
In Transact-SQL, local variables are created and used for temporary storage while SQL
statements are executed. Data can be passed to SQL statements using local variables. The name
of a local variable must be prefixed with '@' sign.
Global variables are in-built variables that are defined and maintained by the system. Global
variables in SQL Server are prefixed with two '@' signs. The value of any of these variables can
be retrieved with a simple SELECT query.
Session
5
Transact-SQL
V 1.0 © Aptech Limited
of 45
4 of 45
Session
5.5.4 Expressions
An expression is a combination of identifiers, values, and operators that SQL Server can evaluate
in order to obtain a result. Expressions can be used in several different places when accessing or
changing data.
Code Snippet 4 shows an expression that operates on a column to add an integer to the results of
the YEAR function on a datetime column.
Code Snippet 4:
SELECT SalesOrderID, CustomerID, SalesPersonID, TerritoryID,YEAR(OrderDate)
AS CurrentYear, YEAR(OrderDate) + 1 AS NextYear
FROM Sales.SalesOrderHeader
Figure 5.2 shows the results of the expression.
Figure 5.: Expression Result
5
Transact-SQL
V 1.0 © Aptech Limited
Table 5.6 shows some of the commonly used control-of-flow statements in Transact-SQL.
Control-of-Flow Statement
Description
IF. . .ELSE Provides branching control based on a logical test. WHILE Repeats a statement or a
block of statements as long as the
condition is true. BEGIN. . .END Defines the scope of a block of
Transact-SQL statements. TRY. . . CATCH Defines the structure for exception and error
handling. BEGIN TRANSACTION Marks a block of statements as part of an explicit
transaction.
Table 5.: Control-of-Flow Statements
5.5.6 Comments
Comments are descriptive text strings, also known as remarks, in program code that will be
ignored by the compiler. Comments can be included inside the source code of a single statement,
a batch, or a stored procedure. Comments explain the purpose of the program, special execution
conditions, and provide revision history information. Microsoft SQL Server supports two types
of commenting styles:
→
- - (double hyphens)
A complete line of code or a part of a code can be marked as a comment, if two hyphens (- -) are
placed at the beginning. The remainder of the line becomes a comment.
Code Snippet 5 displays the use of this style of comment.
Code Snippet 5:
USE AdventureWorks2012
-- HumanResources.Employee table contains the details of an employee. -- This statement retrieves all the
rows of the table -- HumanResources.Employee.
SELECT * FROM HumanResources.Employee
→
/* ... */ (forward slash-asterisk character pairs)
These comment characters can be used on the same line as code to be executed, on lines by
themselves, or even within executable code. Everything in the line beginning from the open
comment pair (/*) to the close comment pair (*/) is considered part of the comment. For a
multiple-line comment, the open-comment character pair (/*) must begin the comment, and the
close-comment character pair (*/) must end the comment.
Session
5
Transact-SQL
V 1.0 © Aptech Limited
5 of 45
5 Session
Transact-SQL
Code Snippet 6 displays the use of this style of comment.
Code Snippet 6:
USE AdventureWorks2012
/* HumanResources.Employee table contains the details of an employee.
This statement retrieves all the rows of the table HumanResources.Employee. */
SELECT * FROM HumanResources.Employee
Session
5
Transact-SQL
V 1.0 © Aptech Limited
of 45
5 Session
Transact-SQL
The following is the syntax of the SELECT statement.
Syntax:
SELECT <select list>
FROM <table source>
WHERE <search condition>
GROUP BY <group by list>
HAVING <search condition>
ORDER BY <order by list>
Table 5.8 explains the elements of the SELECT statement.
Element Description SELECT <select list> Defines the columns to be returned
FROM <table source> Defines the table to be queried WHERE <search condition> Filters the
rows by using predicates GROUP BY <group by list> Arranges the rows by groups HAVING
<search condition> Filters the groups using predicates ORDER BY <order by list> Sorts the
output
Table 5.: Elements of SELECT Statement
Code Snippet 8 shows a SELECT statement.
Code Snippet 8:
SELECT SalesPersonID, YEAR(OrderDate) AS OrderYear
FROM Sales.SalesOrderHeader
WHERE CustomerID = 30084
GROUP BY SalesPersonID, YEAR(OrderDate)
HAVING COUNT(*) > 1
ORDER BY SalesPersonID, OrderYear;
In the example, the order in which SQL Server will execute the SELECT statement is as follows:
1.
First, the FROM clause is evaluated to define the source table that will be queried.
2.
Next, the WHERE clause is evaluated to filter the rows in the source table. This filtering is
defined by the predicate mentioned in the WHERE clause.
3.
After this, the GROUP BY clause is evaluated. This clause arranges the filtered values received
from the WHERE clause.
of 45
Session
5
Transact-SQL
Figure 5.: SELECT Statement Result
V 1.0 © Aptech Limited
of 45
5 Session
Transact-SQL
5.8.1 Answers
1. A
2. C
3. B
4. D
5. B
6. C
10 of 45
Summary
→
Transact-SQL is a powerful language which offers features such as data types, temporary
objects, and extended stored procedures.
→
SQL Server supports three types of Transact-SQL statements, namely, DDL, DML, and DCL.
→
A data type is an attribute defining the type of data that an object can contain.
→
Sets and Predicate Logic are the two mathematical fundamentals that are used in SQL Server
2012.
→
Set theory is a mathematical foundation used in relational database model, where a set is a
collection of distinct objects considered as a whole.
→
Predicate logic is a mathematical framework that consists of logical tests that gives a result.
V 1.0 © Aptech Limited
10 of 45
104 of 45
Session
1.
5
Transact-SQL
V 1.0 © Aptech Limited
Try It Yourself
Use the Query Editor to execute a query. Ensure that a connection to a new server instance is
established. Then, in the AdventureWorks2012 database, execute a query to select the columns
namely, ProductID, Name, and ProductNumber from Production.Product table, and Product ID
and ModifiedDate from Production.ProductDocument table.
Welcome to the Session, Creating and Managing Databases.
This session describes system and user defined databases. It also lists the key
features of the AdventureWorks2012 database. Finally, the session describes types
of database modification.
In this Session, you will learn to:
Describe system and user-defined databases
List the key features of the AdventureWorks2012 sample database
Describe adding of filegroups and transaction logs
Describe the procedure to create a database
List and describe types of database modifications
Describe the procedure to drop a database
Describe database snapshots
Session -
Creating and Managing Databases
→
→
→
→
→
→
→
Session
Creating and Managing Databases
6.1 Introducfion
A database is a collection of data stored in data files on a disk or some removable medium. A
database consists of data files to hold actual data.
An SQL Server database is made up of a collection of tables that stores sets of specific structured
data. A table includes a set of rows (also called as records or tuples) and columns (also called as
attributes). Each column in the table is intended to store a specific type of information, for
example, dates, names, currency amounts, and numbers.
A user can install multiple instances of SQL Server on a computer. Each instance of SQL Server
can include multiple databases. Within a database, there are various object ownership groups
called schemas. Within each schema, there are database objects such as tables, views, and stored
procedures. Some objects such as certificates and asymmetric keys are contained within the
database, but are not contained within a schema.
SQL Server databases are stored as files in the file system. These files are grouped into file
groups. When people gain access to an instance of SQL Server, they are identified as a login.
When people gain access to a database, they are identified as a database user.
A user who has access to a database can be given permission to access the objects in the
database. Though permissions can be granted to individual users, it is recommended to create
database roles, add the database users to the roles, and then, grant access permission to the roles.
Granting permissions to roles instead of users makes it easier to keep permissions consistent and
understandable as the number of users grow and continually change.
SQL Server 2012 supports three kinds of databases, which are as follows:
→
System Databases
→
User-defined Databases
→
Sample Databases
Session
Session
Session
Session
Creating and Managing Databases
V 1.0 © Aptech Limited
11 of 45
Session
Creating and Managing Databases
→
Analysis Services
→
Integration Services
→
Notification Services
→
Reporting Services
→
Replication Facilities
→
A set of integrated samples for two multiple feature-based samples: HRResume and Storefront.
The sample database consists of these parts:
→
AdventureWorks2012: Sample OLTP database
→
AdventureWorks2012DW: Sample Data warehouse
→
AdventureWorks2012AS: Sample Analysis Services database
6.4.2 Filegroups
In SQL Server, data files are used to store database files. The data files are further subdivided
into filegroups for the sake of performance. Each filegroup is used to group related files that
together store a database object. Every database has a primary filegroup by default. This
filegroup contains the primary data file. The primary file group and data files are created
automatically with default property values at the time of creation of the database. User-defined
filegroups can then be created to group data files together for administrative, data allocation, and
placement purposes.
For example, three files named Customer_Data1.ndf, Customer_Data2.ndf, and
Customer_Data3.ndf, can be created on three disk drives respectively. These can then be
assigned to the filegroup Customer_fgroup1. A table can then be created specifically on the
filegroup Customer_fgroup1. Queries for data from the table will be spread across the three disk
drives thereby, improving performance.
Table 6.3 shows the filegroups that are supported by SQL Server 2012.
Filegroup Description Primary The filegroup that consists of the primary file. All system
tables are placed
inside the primary filegroup. User-defined Any filegroup that is created by the user at the time of
creating or modifying
databases.
Table .: Filegroups in SQL Server 01
Adding Filegroups to an existing database
Filegroups can be created when the database is created for the first time or can be created later
when more files are added to the database. However, files cannot be moved to a different
filegroup after the files have been added to the database.
114 of 45
Session
Creating and Managing Databases
V 1.0 © Aptech Limited
115 of 45
Session
11 of 45
LOG ON
( NAME = 'SalesDB_log', FILENAME = 'C:\Program Files\Microsoft SQL Server\
MSSQL11.MSSQLSERVER\MSSQL\DATA\SalesDB_log.ldf' , SIZE = 2048KB , MAXSIZE = 2048GB
, FILEGROWTH = 10%)
COLLATE SQL_Latin1_General_CP1_CI_AS
Figure 6.5 shows the file groups when creating SalesDB database.
Figure .5: A Filegroup Added When Creating SalesDB Database
The following is the syntax to add a filegroup to an existing database.
Syntax:
ALTER DATABASE database_name
{ <add_or_modify_files>
| <add_or_modify_filegroups>
| <set_database_options>
Session
Session
5.
6.
Session
Creating and Managing Databases
To change the collation of the database, select the Options page, and then, select a collation from
the list as shown in figure 6.9.
Figure .: Collation List
V 1.0 © Aptech Limited
1 of 45
Session
14 of 45
8.
9.
Session
Session
Expand Databases, right-click the database to delete, and then, click Delete, as shown in figure
6.12.
Session
Creating and Managing Databases
V 1.0 © Aptech Limited
1 of 45
Session
10 of 45
5.
Session
Summary
→
An SQL Server database is made up of a collection of tables that stores sets of specific structured
data.
→
SQL Server 2012 supports three kinds of databases:
•
System databases
•
User-defined databases
•
Sample Databases
→
SQL Server uses system databases to support different parts of the DBMS.
→
A fictitious company, Adventure Works Cycles is created as a scenario and the
AdventureWorks2012 database is designed for this company.
→
The SQL Server data files are used to store database files, which are further subdivided into
filegroups for the sake of performance.
→
Objects are assigned to the default filegroup when they are created in the database. The
PRIMARY filegroup is the default filegroup.
→
A database snapshot is a read-only, static view of a SQL Server database.
1 of 45
1.
→
→
→
Session
Try It Yourself
Create a database named UnitedAir using Transact-SQL statements with the following
properties:
Primary filegroup with files, UnitedAir1 _ dat and UnitedAir2 _ dat. The size, maximum size,
and file growth should be 5, 10, and 15% respectively.
A filegroup named UnitedAirGroup1 with the files UnitedAirGrp1F1 and UnitedAirGrp1F2.
A filegroup with UnitedAirGroup2 with the files UnitedAirGrp2F1 and UnitedAirGrp2F2.
1 of 45
“
“
Woe to him than who they teaches
can learn
men faster
Welcome to the Session, Creating Tables.
This session explores the various data types provided by SQL Server 2012 and
describes how to use them. The techniques for creation, modification, and removal
of tables and columns are also discussed.
In this Session, you will learn to:
List SQL Server 2012 data types
Describe the procedure to create, modify, and drop tables in an SQL Server database
Describe the procedure to add, modify, and drop columns in a table
Session
Creating Tables
V 1.0 © Aptech Limited
1 of 45
Session
Creating Tables
The syntax for ALTER TABLE statement is as follows:
Syntax:
ALTER TABLE [[database_name. [schema_name].| schema_name.]table_name
ALTER COLUMN ([<column_name>] [data_type] Null/Not Null,);
| ADD ([<column_name>] [data_type] Null/Not Null,);
| DROP COLUMN ([<column_name>];
where,
ALTER COLUMN: specifies that the particular column is to be changed or modified.
ADD: specifies that one or more column definitions are to be added.
DROP COLUMN ([<column_name>]: specifies that column_name is to be removed from the
table.
Code Snippet 3 demonstrates altering the Customer_id column. Code Snippet 3:
USE [CUST_DB]
ALTER TABLE [dbo].[Customer_1]
ALTER Column [Customer_id number] [numeric](12, 0) NOT NULL;
Code Snippet 4 demonstrates adding the Contact_number column.
Code Snippet 4:
USE [CUST_DB]
ALTER TABLE [dbo].[Table_1]
ADD [Contact_number] [numeric](12, 0) NOT NULL;
Code Snippet 5 demonstrates dropping the Contact_number column.
Code Snippet 5:
USE [CUST_DB]
ALTER TABLE [dbo].[Table_1]
DROP COLUMN [Contact_name];
Before attempting to drop columns, however, it is important to ensure that the columns can be
dropped. Under certain conditions, columns cannot be dropped, such as, if they are used in a
CHECK, FOREIGN KEY, UNIQUE, or PRIMARY KEY constraint, associated with a
DEFAULT definition, and so forth.
140 of 45
Session
Creating Tables
V 1.0 © Aptech Limited
141 of 45
Session
14 of 45
Creating Tables
Code Snippet 7 demonstrates adding a new row to the Table_2 table.
Code Snippet 7:
USE [CUST_DB]
INSERT INTO [dbo].[Table_2] VALUES (101, 'Richard Parker', 'Richy')
GO
The outcome of this will be that one row with the given data is inserted into the table.
UPDATE Statement - The UPDATE statement modifies the data in the table. The syntax for
UPDATE statement is as follows:
Syntax:
UPDATE <Table_Name>
SET <Column_Name = Value>
[WHERE <Search condition>]
where,
<Table_Name>: is the name of the table where records are to be updated.
<Column_Name>: is the name of the column in the table in which record is to be updated.
<Value>: specifies the new value for the modified column.
<Search condition>: specifies the condition to be met for the rows to be deleted.
Code Snippet 8 demonstrates the use of the UPDATE statement to modify the value in column
Contact_number.
Code Snippet 8:
USE [CUST_DB]
UPDATE [dbo].[Table_2] SET Contact_number = 5432679 WHERE Contact_name LIKE 'Richy'
GO
Figure 7.1 shows the output of UPDATE statement.
V 1.0 © Aptech Limited
Figure .1: Output of UPDATE Statement
DELETE →
Statement - The DELETE statement removes rows from a table. The syntax for
DELETE statement is as follows:
Syntax:
DELETE FROM <Table_Name>
[WHERE <Search condition>]
where,
<Table_Name>: is the name of the table from which the records are to be deleted.
The WHERE clause is used to specify the condition. If WHERE clause is not included in the
DELETE statement, all the records in the table will be deleted.
Code Snippet 9 demonstrates how to delete a row from the Customer_2 table whose
Contact_number value is 5432679.
Code Snippet 9:
USE [CUST_DB]
DELETE FROM [dbo].[Customer_2] WHERE Contact_number = 5432679
GO
Session
Creating Tables
V 1.0 © Aptech Limited
14 of 45
Session
Creating Tables
In Code Snippet 10, the CREATE TABLE statement uses the NULL and NOT NULL keywords
with column definitions. Code Snippet 10:
USE [CUST_DB]
CREATE TABLE StoreDetails ( StoreID int NOT NULL, Name varchar(40) NULL)
GO
The result of the code is that the StoreDetails table is created with StoreID and Name columns
added to the table.
Creating Tables
V 1.0 © Aptech Limited
145 of 45
Session
Creating Tables
→
Columns defined with IDENTITY property cannot have their values updated.
→
The values can be explicitly inserted into the identity column of a table only if the IDENTITY _
INSERT option is set ON. When IDENTITY _ INSERT is ON, INSERT statements must supply
a value.
The advantage of identifier columns is that SQL Server can automatically provide key values,
thus reducing costs and improving performance. Using identifier columns simplifies
programming and keeps primary key values short.
Once the IDENTITY property has been set, retrieving the value of the identifier column can be
done by using the IDENTITYCOL keyword with the table name in a SELECT statement. To
know if a table has an IDENTITY column, the OBJECTPROPERTY() function can be used. To
retrieve the name of the IDENTITY column in a table, the COLUMNPROPERTY function is
used.
The syntax for IDENTITY property is as follows: Syntax:
CREATE TABLE <table_name> (column_name data_type [ IDENTITY [(seed_value,
increment_value)]] NOT NULL )
where,
seed_value: is the seed value from which to start generating identity values.
increment_value: is the increment value by which to increase each time.
Code Snippet 13 demonstrates the use of IDENTITY property. HRContactPhone is created as a
table with two columns in the schema Person that is available in the CUST_DB database. The
Person_ID column is an identity column. The seed value is 500, and the increment value is 1.
Code Snippet 13:
USE [CUST_DB]
GO
CREATE TABLE HRContactPhone ( Person_ID int IDENTITY(500,1) NOT NULL, MobileNumber
bigint NOT NULL )
GO
14 of 45
Session
Creating Tables
V 1.0 © Aptech Limited
14 of 45
Session
Creating Tables
Code Snippet 15:
USE [CUST_DB]
CREATE TABLE EMP_CellularPhone( Person_ID uniqueidentifier DEFAULT NEWID() NOT NULL,
PersonName varchar(60) NOT NULL)
GO
Code Snippet 16 adds a value to PersonName column.
Code Snippet 16:
USE [CUST_DB]
INSERT INTO EMP_CellularPhone(PersonName) VALUES ('William Smith')
SELECT * FROM EMP_CellularPhone
GO
Figure 7.4 shows the output where a unique identifier is displayed against a specific
PersonName.
Figure .4: Unique Identifier
7.4 Constraints
One of the important functions of SQL Server is to maintain and enforce data integrity. There are
a number of means to achieve this but one of the commonly used and preferred methods is to use
constraints. A constraint is a property assigned to a column or set of columns in a table to
prevent certain types of inconsistent data values from being entered. Constraints are used to
apply business logic rules and enforce data integrity.
Constraints can be created when a table is created, as part of the table definition by using the
CREATE TABLE statement or can be added at a later stage using the ALTER TABLE
statement. Constraints can be categorized as column constraints and table constraints. A column
constraint is specified as part of a column definition and applies only to that column. A table
constraint can apply to more than one column in a table and is declared independently from a
column definition. Table constraints must be used when more than one column is included in a
constraint.
SQL Server supports the following types of constraints:
→
PRIMARY KEY
→
UNIQUE
14 of 45
Session
Creating Tables
V 1.0 © Aptech Limited
14 of 45
Session
150 of 45
7.4.2 UNIQUE
A UNIQUE constraint is used to ensure that only unique values are entered in a column or set of
columns. It allows developers to make sure that no duplicate values are entered. Primary keys are
implicitly unique. Unique key constraints enforce entity integrity because once the constraints
are applied; no two rows in the table can have the same value for the columns. UNIQUE
constraints allow null values.
A single table can have more than one UNIQUE constraint.
The syntax to create UNIQUE constraint is as follows:
Syntax:
CREATE TABLE <table_name> ([column_list
] <column_name> <data_type> UNIQUE [
column_list])
Creating Tables
V 1.0 © Aptech Limited
Code Snippet 19 demonstrates how to make the MobileNumber and LandlineNumber columns as
unique.
Code Snippet 19:
USE [CUST_DB]
GO
CREATE TABLE EMP_ContactPhone(Person_ID int PRIMARY KEY, MobileNumber bigint
UNIQUE,ServiceProvider varchar(30),LandlineNumber bigint UNIQUE)
Code Snippet 20 demonstrates how to insert a row into the table.
Code Snippet 20:
USE [CUST_DB]
INSERT INTO EMP_ContactPhone values (111, 983345674, 'Hutch', NULL)
INSERT INTO EMP_ContactPhone values (112, 983345674, 'Airtel', NULL)
GO
Though a value of NULL has been given for the LandlineNumber columns, which are defined as
UNIQUE, the command will execute successfully because UNIQUE constraints check only for
the uniqueness of values but do not prevent null entries. The first statement shown in Code
Snippet 20 is executed successfully but the next INSERT statement will fail even though the
primary key value is different because the value for MobileNumber is a duplicate as shown in
figure 7.7. This is because the column MobileNumber is defined to be unique and disallows
duplicate values.
Figure .: Output Error Message for Value Duplicate MobileNumber
The output of Code Snippet 20 is shown in figure 7.8.
Session
Creating Tables
Figure .: Output of the Executed UNIQUE Constraint
V 1.0 © Aptech Limited
151 of 45
Session
15 of 45
Creating Tables
V 1.0 © Aptech Limited
7.4.4 CHECK
A CHECK constraint limits the values that can be placed in a column. Check constraints enforce
integrity of data. For example, a CHECK constraint can be given to check if the value being
entered into VoterAge is greater than or equal to 18. If the data being entered for the column
does not satisfy the condition, then, insertion will fail.
A CHECK constraint operates by specifying a search condition, which can evaluate to TRUE,
FALSE, or unknown. Values that evaluate to FALSE are rejected. Multiple CHECK constraints
can be specified for a single column. A single CHECK constraint can also be applied to multiple
columns by creating it at the table level.
Code Snippet 23 demonstrates creating a CHECK constraint to ensure that the Amount value
will always be non-zero. A NULL value can, however, be added into Amount column if the
value of Amount is not known.
Code Snippet 23:
USE [CUST_DB]
CREATE TABLE EMP_PhoneExpenses ( Expense_ID int PRIMARY KEY, MobileNumber bigint
FOREIGN KEY REFERENCES EMP_ContactPhone (MobileNumber), Amount bigint CHECK (Amount
>10))
GO
Once a CHECK constraint has been defined, if an INSERT statement is written with data that
violates the constraint, it will fail as shown in Code Snippet 24.
Code Snippet 24:
USE [CUST_DB]
INSERT INTO dbo.EMP_PhoneExpenses values (101, 983345674, 9)
GO
The error message of Code Snippet 24 that appears when the Amount constraint is less than 10 is
shown in figure 7.10.
Session
Creating Tables
Figure .10: Output Error Message of CHECK Constraint
V 1.0 © Aptech Limited
15 of 45
Session
Creating Tables
Session
Creating Tables
V 1.0 © Aptech Limited
155 of 45
Session
Creating Tables
7.5.1 Answers
1. D
2. A
3. B
4. B
5. A
15 of 45
Summary
→
A data type is an attribute that specifies the storage capacity of an object and the type of data it
can hold, such as numeric data, character data, monetary data, and so on.
→
Most tables have a primary key, made up of one or more columns of the table that identifies
records uniquely.
→
The nullability feature of a column determines whether rows in the table can contain a null value
for that column.
→
A DEFAULT definition for a column can be created at the time of table creation or added at a
later stage to an existing table.
→
The IDENTITY property of SQL Server is used to create identifier columns that can contain
auto-generated sequential values to uniquely identify each row within a table.
→
Constraints are used to apply business logic rules and enforce data integrity.
→
A UNIQUE constraint is used to ensure that only unique values are entered in a column or set of
columns.
→
A foreign key in a table is a column that points to a primary key column in another table.
→
1.
a.
Creating Tables
V 1.0 © Aptech Limited
Try It Yourself
Saint Clara Insurance (SCI) services is a leading Insurance company based in New York, USA.
SCI Services wanted a faster, more accurate, and less expensive way to handle insurance claims
adjusting for its insurance company customers. With an ever-increasing customer base, they
decided to create a Web-based application that will be used not only by employees who work on
field, but will also be used by the administrators in the head office.
SCI handles approximately 650 claims per month, but that can soar to 15000 or more when a
hurricane or some other disaster strikes. Officers can use the software on the device type of their
choice: Tablet PCs or laptops in the field, or desktop PCs back in their offices. The use of
Microsoft SQL Server 2005 as the software's database enables to receive and update all the
necessary information regarding a customer or claimer.
With thousands of customers expected every month, data integrity of the data in the database is
very important. You need to perform the following tasks:
Create a database called SaintClaraServices to store the details of the company. Create a table
CustomerHeader with the details given in table 7.2.
Field Name Data Type Description ClientID int Stores client id. This column is the Primary
Key FirstName char Stores first name of the client LastName char Stores last name of the client
MiddleName char Stores middle name of the client Gender char Stores gender of the client
DateOfBirth datetime Stores date of birth of the client Address varchar(max) Stores address of
the client MaritalStatus char Stores marital status of the client Age int Stores age of the client
Employment char Stores occupation of the client CompanyName varchar(max) Stores the
company name CompanyAddress varchar(max) Stores the company address
Table .: CustomerHeader Table
Session
b.
c.
Creating Tables
V 1.0 © Aptech Limited
Try It Yourself
Create a table CustomerDetails with the specifications given in table 7.3.
Field Name Data Type Description ClientID int Stores client id. This column is the Primary
Key FatherName char Stores the name of the client's father MotherName char Stores the name of
the client's mother Amount money Stores the principal amount Period int Stores period for
insurance Plan char Stores plan for insurance Premium money Stores premium NomineeName
char Stores nominee name Date datetime Stores the date on which insurance is made
Table .: CustomerDetails Table
Add a foreign key to CustomerDetails table.
15 of 45
“
“
Real lies generosity in giving all
towards to the present
the future
Session - Accessing
Data
Welcome to the Session, Accessing Data.
This session describes SELECT statement. It also explains the expressions and the
various clauses used with SELECT statement. Finally, the session introduces the
new xml data type and describes how to work with XML data in SQL Server 2012
tables. A brief look at the XQuery language, which is used to query XML data, is
also discussed in the session.
In this Session, you will learn to:
→
Describe the SELECT statement, its syntax, and use
→
Explain the various clauses used with SELECT
→
State the use of ORDER BY clause
→
Describe working with typed and untyped XML
→
Explain the procedure to create, use, and view XML schemas
→
Explain use of XQuery to access XML data
Session
Accessing Data
8.1 Introducfion
The SELECT statement is a core command used to access data in SQL Server 2012. XML
allows developers to develop their own set of tags and makes it possible for other programs to
understand these tags. XML is the preferred means for developers to store, format, and manage
data on the Web.
Session
Accessing Data
Figure .: Displaying All Columns
V 1.0 © Aptech Limited
1 of 45
Session
Accessing Data
Session
Accessing Data
V 1.0 © Aptech Limited
15 of 45
Session
Accessing Data
Code Snippet 5 demonstrates how to display 'ChangedDate' as the heading for ModifiedDate
column in the dbo.Individual table, the SELECT statement.
Code Snippet 5:
USE CUST_DB
SELECT ModifiedDate as 'ChangedDate' FROM dbo.Individual
GO
The output displays'ChangedDate' as the heading for ModifiedDate column in the dbo.Individual
table. Figure 8.5 shows the original heading and the changed heading.
Figure .5: Column Heading Modified to ChangedDate
Session
Accessing Data
V 1.0 © Aptech Limited
1 of 45
Session
Accessing Data
The SELECT statement has various clauses associated with it. In this section, each clause is
discussed in detail.
Session
Accessing Data
V 1.0 © Aptech Limited
1 of 45
Session
Accessing Data
Operator Description BETWEEN Between a range LIKE Search for an ordered pattern IN
Within a range
Table .1: Operators
Code Snippet 9 demonstrates the equal to operator with WHERE clause to display data with
EndDate 6/30/2007 12:00:00 AM.
Code Snippet 9:
USE AdventureWorks2012
SELECT * FROM Production.ProductCostHistory WHERE EndDate = '6/30/2007 12:00:00 AM'
GO
Code Snippet 9 will return all records from the table Production.ProductCostHistory which has
the end date as '6/30/2007 12:00:00 AM'.
The output SELECT with WHERE clause is shown in figure 8.8.
Figure .: SELECT with WHERE clause
All queries in SQL use single quotes to enclose the text values. For example, consider the
following query, which retrieves all the records from Person.Address table having Bothell as
city.
10 of 45
Session
Accessing Data
V 1.0 © Aptech Limited
11 of 45
Accessing Data
Figure .10: Output of Where Clause with < Operator
WHERE clause can also be used with wildcard characters as shown in table 8.2. All wildcard
characters are used along with LIKE keyword to make the query accurate and specific.
Wildcard Description Example _ It will display a single
character
V 1.0 © Aptech Limited
SELECT * FROM Person. Contact WHERE Suffix LIKE 'Jr_' % It will display a string of any
length The output of the query is shown in figure 8.10.
SELECT * FROM Person. Contact WHERE LastName LIKE 'B%' [ ] It will display a single character
SELECT * FROM Sales. within the brackets
the range enclosed in
CurrencyRate ToCurrencyCode 'C[AN][DY]'
WHERE
LIKE
[^] It will display any single
SELECT * FROM Sales. character enclosed in not the within
brackets
the range
CurrencyRate ToCurrencyCode
'A[^R][^S]' Session
WHERE
LIKE
Table .: Wildcard Characters WHERE clause also uses
logical operators such as AND, OR, and NOT. These operators are used with search conditions
in WHERE clauses.
AND operator joins two or more conditions and returns TRUE only when both the conditions are
TRUE. So, it returns all the rows from the tables where both the conditions that are listed are
true.
1 of 45
Code Snippet 12 demonstrates AND operator.
Code Snippet 12:
USE AdventureWorks2012
SELECT * FROM Sales.CustomerAddress WHERE AddressID > 900 AND AddressTypeID = 5
GO
OR operator returns TRUE and displays all the rows if it satisfies any one of the conditions.
Code Snippet 13 demonstrates OR operator.
Code Snippet 13:
USE AdventureWorks2012
SELECT * FROM Sales.CustomerAddress WHERE AddressID < 900 OR AddressTypeID = 5
GO
The query in Code Snippet 13 will display all the rows whose AddressID is less than 900 or
whose AddressTypeID is equal to five.
The NOT operator negates the search condition. Code Snippet 14 demonstrates NOT operator.
Code Snippet 14:
USE AdventureWorks2012
SELECT * FROM Sales.CustomerAddress WHERE NOT AddressTypeID = 5
GO
Code Snippet 14 will display all the records whose AddressTypeID is not equal to 5. Multiple
logical operators in a single SELECT statement can be used. When more than one logical
operator is used, NOT is evaluated first, then AND, and finally OR.
Session
Accessing Data
V 1.0 © Aptech Limited
1 of 45
Session
Accessing Data
The following is the syntax for GROUP BY clause.
Syntax:
SELECT <column_name1>..<column_nameN> FROM <table_name> GROUP BY <column _name>
where,
column_name1: is the name of the column according to which the resultset should be grouped.
For example, consider that if the total number of resource hours has to be found for each work
order, the query in Code Snippet 15 would retrieve the resultset.
Code Snippet 15:
USE AdventureWorks2012
SELECT WorkOrderID,SUM(ActualResourceHrs) FROM Production.WorkOrderRouting GROUP BY
WorkOrderID
GO
The output is shown in figure 8.11.
Figure .11: GROUP BY Clause
The GROUP BY clause can be used with different clauses.
Session
Code Snippet 16 demonstrates the use of CTE in INSERT statement.
Code Snippet 16:
USE CUST_DB
CREATE TABLE NewEmployees (EmployeeID smallint,FirstName char(10), LastName char(10),
Department varchar(50), HiredDate datetime, Salary money );
INSERT INTO NewEmployees
VALUES(11,'Kevin','Blaine', 'Research', '2012-07-31', 54000);
WITH EmployeeTemp (EmployeeID,FirstName,LastName,Department,
HiredDate,Salary)
AS
(
SELECT * FROM NewEmployees
)
SELECT * FROM EmployeeTemp
The statement in Code Snippet 16 inserts a new row for the NewEmployees table and transfers
the temporary resultset to EmployeeTemp as shown in figure 8.12.
Figure .1: Transferring Temporary Result to EmployeeTemp
OUTPUT clause in INSERT and UPDATE statements
The OUTPUT clause returns information about rows affected by an INSERT statement and an
UPDATE statement.
Accessing Data
V 1.0 © Aptech Limited
15 of 45
Session
Accessing Data
Code Snippet 17 demonstrates how to use UPDATE statement with an INSERT statement.
Code Snippet 17:
USE CUST_DB;
GO
CREATE TABLE dbo.table_3
(
id INT,
employee VARCHAR(32)
)
go
INSERT INTO dbo.table_3 VALUES
(1, 'Matt')
,(2, 'Joseph')
,(3, 'Renny')
,(4, 'Daisy');
GO
DECLARE @updatedTable TABLE
(
id INT, olddata_employee VARCHAR(32), newdata_employee VARCHAR(32)
);
UPDATE dbo.table_3
Set employee= UPPER(employee)
OUTPUT
inserted.id,
deleted.employee,
inserted.employee
INTO @updatedTable
SELECT * FROM @updatedTable
1 of 45
Session
Accessing Data
V 1.0 © Aptech Limited
1 of 45
Session
Accessing Data
The xml data type is used to store XML documents and fragments in an SQL Server database.
An XML fragment is an XML instance with the top-level element missing from its structure.
The following is the syntax to create a table with columns of type xml.
Syntax:
CREATE TABLE <table_name> ( [ column_list,] <column_name> xml [, column_list])
Code Snippet 20 creates a new table named PhoneBilling with one of the columns belonging to
xml data type.
Code Snippet 20:
USE AdventureWorks2012
CREATE TABLE Person.PhoneBilling (Bill_ID int PRIMARY KEY, MobileNumber bigint UNIQUE,
CallDetails xml)
GO
A column of type xml can be added to a table at the time of creation or after its creation. The xml
data type columns support DEFAULT values as well as the NOT NULL constraint.
Data can be inserted into the xml column in the Person.PhoneBilling
tableasshowninCodeSnippet table as shown in Code Snippet 21. Code Snippet 21:
USE AdventureWorks2012
INSERT INTO Person.PhoneBilling VALUES (100,9833276605,
'<Info><Call>Local</Call><Time>45 minutes</Time><Charges>200</Charges></ Info>')
SELECT CallDetails FROM Person.PhoneBilling
GO
The output is shown in figure 8.16.
Figure .1: XML Data in Columns
The DECLARE statement is used to create variables of type xml.
10 of 45
Session
Accessing Data
V 1.0 © Aptech Limited
11 of 45
Session
Accessing Data
<xsd:attribute name="country" type="xsd:string" />
<xsd:attribute name="score" type="xsd:string" />
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
</xsd:element>
</xsd:schema>'
GO
The CREATE XML SCHEMA COLLECTION statement creates a collection of schemas, any of
which can be used to validate typed XML data with the name of the collection. This example
shows a new schema called CricketSchemaCollection being added to the SampleDB database.
Once a schema is registered, the schema can be used in new instances of the xml data type.
Code Snippet 24 creates a table with an xml type column and specifies a schema for the column.
Code Snippet 24:
USE SampleDB
CREATE TABLE CricketTeam ( TeamID int identity not null, TeamInfo xml(CricketSchem aCollection)
)
GO
To create new rows with the typed XML data, the INSERT statement can be used as shown in
Code Snippet 25.
Code Snippet 25:
USE SampleDB
INSERT INTO CricketTeam (TeamInfo) VALUES ('<MatchDetails><Team country="Australia"
score="355"></Team><Team country="Zimbabwe" score="200"></Team><Team country="England"
score="475"></Team></ MatchDetails>')
GO
1 of 45
V 1.0 © Aptech Limited
A typed XML variable can also be created by specifying the schema collection name. For
instance, in Code Snippet 26, a variable team is declared as a typed XML variable with schema
name as CricketSchemaCollection. The SET statement is used to assign the variable as an XML
fragment.
Code Snippet 26:
USE SampleDB
DECLARE @team xml(CricketSchemaCollection)
SET @team = '<MatchDetails><Team country="Australia"></Team></MatchDetails>'
SELECT @team
GO
8.5.3 XQuery
After XML data has been stored using the xml data type, it can be queried and retrieved using a
language named XQuery. XML Query or XQuery is a new query language, which combines
syntax that is familiar to developers who work with the relational database, and XPath language,
that is used to select individual sections or collections of elements from an XML document.
XQuery can be query structured or semi-structured XML data. To query an XML instance stored
in a variable or column of xml type, xml data type methods are used. For example, a variable of
xml type is declared and queried by using methods of the xml data type. Developers need to
query XML documents, and this involves transforming XML documents in the required format.
XQuery makes it possible to perform complex queries against an XML data source over the
Web.
Some of the xml data type methods used with XQuery are described as follows:
→
exist()
This method is used to determine if one or more specified nodes are present in the XML
document. It returns 1 if the XQuery expression returned at least one node, 0 if the Xquery
expression evaluated to an empty result, and NULL if the xml data type instance against which
the query was executed is NULL.
Code Snippet 27 demonstrates the use of exist() method. It is assumed that many records have
been inserted into the table.
Code Snippet 27:
USE SampleDB
SELECT TeamID FROM CricketTeam WHERE TeamInfo.exist('(/MatchDetails/ Team)') = 1
GO
Session
Accessing Data
V 1.0 © Aptech Limited
1 of 45
Session
14 of 45
→
→
Accessing Data
This will return only those TeamID values where the Team element has been specified in the
TeamInfo. The output is shown in figure 8.17.
Figure .1: exist() Method
query()
The query() method can be used to retrieve either the entire contents of an XML document or a
selected section of the XML document. Code Snippet 28 shows the use of query() method.
Code Snippet 28:
USE SampleDB
SELECT TeamInfo.query('/MatchDetails/Team') AS Info FROM CricketTeam
GO
The output is shown in figure 8.18.
Figure .1: query() Method
value()
The value() method can be used to extract scalar values from an xml data type. Code Snippet 29
demonstrates this method.
Code Snippet 29:
USE SampleDB
SELECT TeamInfo.value('(/MatchDetails/Team/@score)[1]', 'varchar(20)') AS Score FROM
CricketTeam where TeamID=1
GO
V 1.0 © Aptech Limited
Session
Accessing Data
The output of the command is shown in figure 8.19.
Figure .1: value() Method
V 1.0 © Aptech Limited
15 of 45
Accessing Data
(B) Session
(C)
INSERT INTO dbo.table_
INSERT INTO dbo.table_ 5(Employee_role,
Summary)
5(Employee_role, Summary) VALUES VALUES
('Research', 'This a very
('Research', 'This a very long long non-unicode
string')
non-unicode string')
SELECT *FROM dbo.table_5
SELECT *FROM dbo.table_5
UPDATE dbo.table_5 SET Summary
(D)
dbo.table_5 SET Summary('n .WRITE('n incredibly',
6,5)
incredibly', 6,5)
WHERE Employee_role LIKE
WHERE Employee_role LIKE 'Research'
'Research'
SELECT *FROM dbo.table_5
SELECT *FROM dbo.table_5
1 of 45
Session
Accessing Data
4.
Which of the following clause with the SELECT statement is used to specify tables or retrieves
the records?
(A) WHERE (C) .VALUE
(B) FROM (D) .WRITE
5.
________ is used to improve the efficiency of queries on XML documents that are stored in an
XML column.
(A) XML indexing (C) XML querying
(B) XML import (D) XML export
V 1.0 © Aptech Limited
1 of 45
Session
Accessing Data
8.6.1 Answers
1. D
2. A
3. B
4. B
5. A
1 of 45
Summary
→
The SELECT statement retrieves rows and columns from tables.
→
SELECT statement allows the users to specify different expressions in order to view the resultset
in an ordered manner.
→
A SELECT statement can contain mathematical expressions by applying operators to one or
more columns.
→
The keyword DISTINCT prevents the retrieval of duplicate records.
→
XML allows developers to develop their own set of tags and makes it possible for other
programs to understand these tags.
→
A typed XML instance is an XML instance which has a schema associated with it.
→
XML data can be queried and retrieved using XQuery language.
V 1.0 © Aptech Limited
1 of 45
Session
10 of 45
Accessing Data
V 1.0 © Aptech Limited
Try It Yourself
Transcorp 1.
United Inc. is an import export company in USA. The database of the company is
created in SQL Server 2012. Transcorp has around 3000 employees worldwide. The details of
the employees such as Employee Code, Employee Name, Employee Department, Date of
Joining, and so on are stored in EMP _ Details table.
As the database administrator of Transcorp, you have to perform the following tasks:
→
Retrieve data of the employees who has joined the company before the year 2012 and after 2010.
→
Edit the name of a female employee Julia Drek to Julia Dean using the .WRITE property.
→
Get the data of all the employees who are from Houston.
Session - Advanced Queries and
Joins
Welcome to the Session, Advanced Queries and Joins.
This session explains the various techniques to group and aggregate data and
describes the concept of subqueries, table expressions, joins, and explores various
set operators. The session also covers pivoting and grouping set operations.
In this Session, you will learn to:
→
Explain grouping and aggregating data
→
Describe subqueries
→
Describe table expressions
→
Explain joins
→
Describe various types of joins
→
Explain the use of various set operators to combine data
→
Describe pivoting and grouping set operations
Session
Advanced Queries and Joins
9.1 Introducfion
SQL Server 2012 includes several powerful query features that help you to retrieve data
efficiently and quickly. Data can be grouped and/or aggregated together in order to present
summarized information. Using the concept of subqueries, a resultset of a SELECT can be used
as criteria for another SELECT statement or query. Joins help you to combine column data from
two or more tables based on a logical relationship between the tables. On the other hand, set
operators such as UNION and INTERSECT help you to combine row data from two or more
tables. The PIVOT and UNPIVOT operators are used to transform the orientation of data from
column-oriented to row-oriented and vice versa. The GROUPING SET subclause of the GROUP
BY clause helps to specify multiple groupings in a single query.
Session
Advanced Queries and Joins
V 1.0 © Aptech Limited
15 of 45
Session
1 of 45
Session
Session
Session
To view a visual representation of the spatial data, you can click the Spatial results tab in the
output window. This will display the output as shown in figure 9.15.
Figure .15: Viewing Spatial Results
Envelope Aggregate
It returns a bounding area for a given set of geometry or geography objects.
The Envelope Aggregate exhibits different behaviors for geography and geometry types. Based
on the type of object it is applied to, it returns different results. For the geometry type, the result
is a 'traditional' rectangular polygon, which closely bounds the selected input objects. For the
geography type, the result is a circular object, which loosely bounds the selected input objects.
Furthermore, the circular object is defined using the new CurvePolygon feature. The following is
the syntax of EnvelopeAggregate.
Syntax:
EnvelopeAggregate (geometry_operand or geography_operand)
where,
geometry_operand: is a geometry type table column comprising the set of geometry objects.
geography_operand: is a geography type table column comprising the set of geography objects.
Code Snippet 14 returns a bounding box for a set of objects in a table variable column. Code
Snippet 14:
SELECT Geography::EnvelopeAggregate(SpatialLocation)
AS Location
FROM Person.Address
WHERE City = 'London'
Session
The output of the code will be as shown in figure 9.17.
Figure .1: Using CollectionAggregate
Convex Hull Aggregate
It returns a convex hull polygon, which encloses one or more spatial objects for a given set of
geometry/geography objects. The following is the syntax of ConvexHullAggregate.
Syntax:
ConvexHullAggregate (geometry_operand or geography_operand)
where,
geometry_operand: is a geometry type table column comprising the set of geometry objects.
geography_operand: is a geography type table column comprising the set of geography objects.
Code Snippet 16 demonstrates the use of ConvexHullAggregate. Code Snippet 16:
SELECT Geography::ConvexHullAggregate(SpatialLocation)
AS Location
FROM Person.Address
WHERE City = 'London'
9.6 Subqueries
You can use a SELECT statement or a query to return records that will be used as criteria for
another SELECT statement or query. The outer query is called parent query and the inner query
is called a subquery. The purpose of a subquery is to return results to the outer query. In other
words, the inner query statement should return the column or columns used in the criteria of the
outer query statement.
The simplest form of a subquery is one that returns just one column. The parent query can use
the results of this subquery using an = sign.
The syntax for the most basic form of a subquery using just one column with an = sign is shown.
Syntax:
SELECT <ColumnName> FROM <table>
WHERE <ColumnName> = ( SELECT <ColumnName> FROM <Table> WHERE <ColumnName> =
<Condition> ) )
In a subquery, the innermost SELECT statement is executed first and its result is passed as
criteria to the outer SELECT statement.
Consider a scenario where it is required to determine the due date and ship date of the most
recent orders.
0 of 45
Session
Session
9.7 Joins
Joins are used to retrieve data from two or more tables based on a logical relationship between
tables. A join typically specifies foreign key relationship between the tables. It defines the
manner in which two tables are related in a query by:
→
Specifying the column from each table to be used for the join. A typical join specifies a foreign
key from one table and its associated key in the other table.
→
Specifying a logical operator such as =, <> to be used in comparing values from the columns.
Session
Session
Session
In Code Snippet 24, the left outer join is constructed between the tables Sales.Customer and
Sales.SalesOrderHeader. The tables are joined on the basis of customer ids. In this case, all
records from the left table, Sales.Customer and only matching records from the right table,
Sales.SalesOrderHeader, are returned. Figure 9.24 shows the output.
Figure .4: Output of Left Outer Join
As shown in the output, some records show the due dates and ship dates as NULL. This is
because for some customers, no order is placed, hence, their records will show the dates as
NULL.
Right Outer Join
The right outer join retrieves all the records from the second table in the join regardless of
whether there is matching data in the first table or not. The following is the syntax of a right
outer join.
Syntax:
SELECT <ColumnList>
FROM Left_Table_Name
AS
Table_A AS Table_Alias_A
RIGHT OUTER JOIN
Table_B AS Table_Alias_B
ON
Table_Alias_A.<CommonColumn> = Table_Alias_B.<CommonColumn>
9.7.3 Self-Join
A self-join is used to find records in a table that are related to other records in the same table. A
table is joined to itself in a self-join.
Consider that an Employee table in a database named Sterling has a column named mgr_id to
denote information for managers whom employees are reporting to. Assume that the table has
appropriate records inserted in it.
A manager is also an employee. This means that the mgr_id in the table is the emp_id of an
employee.
1 of 45
Session
Session
Session
Session
Advanced Queries and Joins
V 1.0 © Aptech Limited
5 of 45
Session
Advanced Queries and Joins
The following is the syntax of the EXCEPT operator.
Syntax:
Query_statement1
EXCEPT
Query_statement2
where,
Query_Statement1 and Query_Statement2 are SELECT statements.
The two rules that apply to INTERSECT operator are also applicable for EXCEPT operator.
Code Snippet 33 demonstrates the EXCEPT operator. Code Snippet 33:
SELECT Product.ProductId FROM Production.Product
EXCEPT
SELECT ProductId FROM Sales.SalesOrderDetail If the order of the two tables in this example
is interchanged, only those rows are returned from Production.Product table which do not match
with the rows present in Sales.SalesOrderDetail. Thus, in simple terms, EXCEPT operator
selects all the records from the first table except those which match with the second table. Hence,
when you are using EXCEPT operator, the order of the two tables in the queries is important.
Whereas, with the INTERSECT operator, it does not matter which table is specified first.
Session
Advanced Queries and Joins
V 1.0 © Aptech Limited
of 45
Session
Advanced Queries and Joins
The output of this will be a table containing all columns of the table_source except the
pivot_column and value_column. These columns of the table_source, excluding the
pivot_column and value_column, are called the grouping columns of the pivot operator.
In simpler terms, to use the PIVOT operator, you need to supply three elements to the operator:
→
Grouping: In the FROM clause, the input columns must be provided. The PIVOT operator uses
those columns to determine which column(s) to use for grouping the data for aggregation.
→
Spreading: Here, a comma-separated list of values that occur in the source data is provided that
will be used as the column headings for the pivoted data.
→
Aggregation: An aggregation function, such as SUM, to be performed on the grouped rows.
Consider an example to understand the PIVOT operator. Code Snippet 34 is shown without the
PIVOT operator and demonstrates a simple GROUP BY aggregation. As the number of records
would be huge, the resultset is limited to 5 by specifying TOP 5. Code Snippet 34:
SELECT TOP 5 SUM(SalesYTD) AS TotalSalesYTD, Name
FROM Sales.SalesTerritory
GROUP BY Name
Figure 9.31 shows the output.
Figure .1: Grouping without PIVOT
The top 5 year to date sales along with territory names grouped by territory names are displayed.
Now, the same query is rewritten in Code Snippet 35 using a PIVOT so that the data is
transformed from a row-based orientation to a column-based orientation. Code Snippet 35:
-- Pivot table with one row and six columns
SELECT TOP 5 'TotalSalesYTD' AS GrandTotal,
[Northwest], [Northeast], [Central], [Southwest],[Southeast]
of 45
Session
Session
9.11.1 Answers
1. C
2. B
3. B
4. B
5. B
6. A
7. A
4 of 45
Summary
→
The GROUP BY clause and aggregate functions enabled to group and/or aggregate data together
in order to present summarized information.
→
A subquery allows the resultset of one SELECT statement to be used as criteria for another
SELECT statement.
→
Joins help you to combine column data from two or more tables based on a logical relationship
between the tables.
→
Set operators such as UNION and INTERSECT help you to combine row data from two or more
tables.
→
The PIVOT and UNPIVOT operators help to change the orientation of data from column-
oriented to row-oriented and vice versa.
→
The GROUPING SET subclause of the GROUP BY clause helps to specify multiple groupings
in a single query.
V 1.0 © Aptech Limited
5 of 45
Session
of 45
1.
2.
3.
4.
5.
6.
7.
8.
Try It Yourself
Write a query to display the employee names and their departments from the
AdventureWorks2012 database.
Using the tables Sales.SalesPerson and Sales.SalesTerritory, retrieve the IDs of all the sales
persons who operate in Canada.
Using the tables Sales.SalesPerson and Sales.SalesTerritory, retrieve the IDs of all the sales
persons who operate in Northwest or Northeast.
Compare the bonus values of salespersons in the Sales.SalesPerson table to find out the sales
persons earning more bonuses. Display the SalesPersonID and bonus values in descending order.
(Hint: Use a self-join and ORDER BY ...DESC).
Retrieve all the values of SalesPersonID from Sales.SalesPerson table, but leave out those
values, which are present in the Sales.Store table. (Hint: Use EXCEPT operator).
Combine all the SalesPersonIDs of the tables Sales.SalesPerson and Sales.Store.
Retrieve all the sales person IDs and territory IDs from Sales.SalesPerson table regardless of
whether they have matching records in the Sales.SalesTerritory table. (Hint: Use a left outer
join).
Retrieve a distinct set of Territory IDs that are present in both Sales.SalesPerson and
Sales.SalesTerritory tables. (Hint: Use INTERSECT operator).
10
Using Views, Stored Session
Procedures,
-
and Querying Metadata
Welcome to the Session, Using Views, Stored Procedures, and Querying Metadata.
This session explains about views and describes creating, altering, and dropping
views. The session also describes stored procedures in detail. The session
concludes with an explanation of the techniques to query metadata.
In this Session, you will learn to:
→
Define views
→
Describe the technique to create, alter, and drop views
→
Define stored procedures
→
Explain the types of stored procedures
→
Describe the procedure to create, alter, and execute stored procedures
→
Describe nested stored procedures
→
Describe querying SQL Server metadata
•
System Catalog views and functions
•
Querying Dynamic Management Objects
10 Session
Using Views, Stored Procedures, and Querying Metadata
10.1 Introducfion
An SQL Server database has two main categories of objects: those that store data and those that
access, manipulate, or provide access to data. Views and stored procedures belong to this latter
category.
10.2 Views
A view is a virtual table that is made up of selected columns from one or more tables. The tables
from which the view is created are referred to as base tables. These base tables can be from
different databases. A view can also include columns from other views created in the same or a
different database. A view can have a maximum of 1024 columns.
The data inside the view comes from the base tables that are referenced in the view definition.
The rows and columns of views are created dynamically when the view is referenced.
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
The following syntax is used to create a view with the JOIN keyword.
Syntax:
CREATE VIEW <view_name>
AS
SELECT * FROM table_name1
JOIN table_name2
ON table_name1.column_name = table_name2.column_name
where,
view_name: specifies the name of the view.
table_name1: specifies the name of first table.
JOIN: specifies that two tables are joined using JOIN keyword.
table_name2: specifies the name of the second table.
Code Snippet 3 creates a view named vwPersonDetails with specific columns from the Person
and Employee tables. The JOIN and ON keywords join the two tables based on
BusinessEntityID column.
Code Snippet 3:
CREATE VIEW vwPersonDetails
AS
SELECT
p.Title
,p.[FirstName]
,p.[MiddleName]
,p.[LastName]
,e.[JobTitle]
FROM [HumanResources].[Employee] e
INNER JOIN [Person].[Person] p
ON p.[BusinessEntityID] = e.[BusinessEntityID]
GO
This view will contain the columns Title, FirstName, MiddleName, and LastName from the
Person table and JobTitle from the Employee table. Once the view is created, you can retrieve
records from it, and manipulate and modify records as well.
40 of 45
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
41 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
When this view is queried with a SELECT statement, the output will be as shown in figure 10.3.
Figure 10.: Using COALESCE Function in a View
10.2.3 Guidelines and Restricfions on Views A view can be created using the CREATE VIEW
command. Before creating a view, the following guidelines and restrictions should be
considered:
→
A view is created only in the current database. The base tables and views from which the view is
created can be from other databases or servers.
→
View names must be unique and cannot be the same as the table names in the schema.
→
A view cannot be created on temporary tables.
→
A view cannot have a full-text index.
→
A view cannot contain the DEFAULT definition.
→
The CREATE VIEW statement can include the ORDER BY clause only if the TOP keyword is
used.
→
Views cannot reference more than 1024 columns.
→
The CREATE VIEW statement cannot include the INTO keyword.
→
The CREATE VIEW statement cannot be combined with other Transact-SQL statements in a
single batch.
If a view contains columns that have values derived from an expression, such columns have to be
given alias names. Also, if a view contains similarly-named columns from different tables, to
distinguish these columns, alias names must be specified.
4 of 45
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
4 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
The value for the column is provided automatically if:
→
The column has an IDENTITY property.
→
The column has a default value specified.
→
The column has a timestamp data type.
→
The column takes null values.
→
The column is a computed column.
While using the INSERT statement on a view, if any rules are violated, the record is not inserted.
In the following example, when data is inserted through the view, the insertion does not take
place as the view is created from two base tables.
First, create a table Employee_Personal_Details as shown in Code Snippet 7.
Code Snippet 7:
CREATE TABLE Employee_Personal_Details
(
EmpID int NOT NULL,
FirstName varchar(30) NOT NULL,
LastName varchar(30) NOT NULL,
Address varchar(30)
)
Then, create a table Employee_Salary_Details as shown in Code Snippet 8.
Code Snippet 8:
CREATE TABLE Employee_Salary_Details
(
EmpID
int NOT NULL,
Designation varchar(30),
Salary int NOT NULL
)
44 of 45
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
45 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
Code Snippet 11 creates a view vwEmpDetails using Employee_Personal_Details table. The
Employee_Personal_Details table contains a column named LastName that does not allow null
values to be inserted.
Code Snippet 11:
CREATE VIEW vwEmpDetails
AS
SELECT FirstName, Address
FROM Employee_Personal_Details
GO
Code Snippet 12 attempts to insert values into the vwEmpDetails view.
Code Snippet 12:
INSERT INTO vwEmpDetails VALUES ('Jack','NYC')
This insert is not allowed as the view does not contain the LastName column from the base table
and that column does not allow null values.
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
Figure 10.5: Updated Table
4 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
Large value data types include varchar(max), nvarchar(max), and varbinary(max). To update
data having large value data types, the .WRITE clause is used. The .WRITE clause specifies that
a section of the value in a column is to be modified. The .WRITE clause cannot be used to
update a NULL value in a column. Also, it cannot be used to set a column value to NULL.
Syntax:
column_name .WRITE (expression, @Offset, @Length)
where,
column_name: specifies the name of the large value data-type column.
Expression: specifies the value that is copied to the column.
@Offset: specifies the starting point in the value of the column at which the expression is
written.
@Length: specifies the length of the section in the column.
@Offset and @Length are specified in bytes for varbinary and varchar data types and in
characters for the nvarchar data type.
Assume that the table Product_Details is modified to include a column Description having data
type nvarchar(max).
A view is created based on this table, having the columns ProductName, Description, and Rate as
shown in Code Snippet 16.
Code Snippet 16:
CREATE VIEW vwProduct_Details
AS
SELECT
ProductName,
Description,
Rate FROM Product_Details
Code Snippet 17 uses the UPDATE statement on the view vwProduct_Details. The .WRITE
clause is used to change the value of Internal in the Description column to External.
Code Snippet 17:
UPDATE vwProduct_Details
SET Description .WRITE(N'Ex',0,2)
WHERE ProductName='Portable Hard Drive'
As a result of the code, all the rows in the view that had 'Portable Hard Drive' as product name
will be updated with External instead of Internal in the Description column.
4 of 45
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
4 of 45
50 of 45
Session
Figure 10.7 depicts the logic of deleting from views.
Figure 10.: Deleting from Views
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
Code Snippet 19 alters the view, vwProductInfo to include the ReOrderPoint column.
Code Snippet 19:
ALTER VIEW vwProductInfo AS
SELECT ProductID, ProductNumber, Name, SafetyStockLevel, ReOrderPoint
FROM Production.Product;
GO
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
51 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
Code Snippet 21 displays information about the view, vwProductPrice.
Code Snippet 21:
EXEC sp_helptext vwProductPrice
The execution of the code will display the definition about the view as shown in figure 10.8.
Figure 10.: Using sp_helptext to Display View Definitions
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
5 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
The UPDATE statement fails to execute as it violates the view definition, which specifies that
SafetyStockLevel must be less than or equal to 1000. Thus, no rows are affected in the view
vwProductInfo.
Note - Any updates performed on the base tables are not verified against the view, even if
CHECK OPTION is specified. 10.9 SCHEMABINDING Opfion
A view can be bound to the schema of the base table using the SCHEMABINDING option. This
option can be used with CREATE VIEW or ALTER VIEW statements. When
SCHEMABINDING option is specified, the base table or tables cannot be modified that would
affect the view definition. The view definition must be first modified or deleted to remove
dependencies on the table that is to be modified.
While using the SCHEMABINDING option in a view, you must specify the schema name along
with the object name in the SELECT statement.
The following syntax is used to create a view with the SCHEMABINDING option.
Syntax:
CREATE VIEW <view_name> WITH SCHEMABINDING
AS <select_statement>
where,
view_name: specifies the name of the view.
WITH SCHEMABINDING: specifies that the view must be bound to a schema.
select_statement: Specifies the SELECT statement that defines the view.
Code Snippet 25 creates a view vwNewProductInfo with SCHEMABINDING option to bind the
view to the Production schema, which is the schema of the table Product.
Code Snippet 25:
CREATE VIEW vwNewProductInfo
WITH SCHEMABINDING AS
SELECT ProductID, ProductNumber, Name, SafetyStockLevel
FROM Production.Product;
GO
54 of 45
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
55 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
Code Snippet 29 uses the ALTER TABLE statement to add a column Age to the table
Customers.
Code Snippet 29:
ALTER TABLE Customers ADD Age int
Code Snippet 30 executes the SELECT query on the view.
Code Snippet 30:
SELECT * FROM vwCustomers
The updated column Age is not seen in the view.
To resolve this, the sp_refreshview stored procedure must be executed on the view vwCustomers
as shown in Code Snippet 31.
Code Snippet 31:
EXEC sp_refreshview 'vwCustomers'
When a SELECT query is run again on the view, the column Age is seen in the output. This is
because the sp_refreshview procedure refreshes the metadata for the view vwCustomers.
Tables that are schema-bound to a view cannot be dropped unless the view is dropped or
changed such that it no longer has schema binding. If the view is not dropped or changed and
you attempt to drop the table, the Database Engine returns an error message.
Also, when an ALTER TABLE statement affects the view definition of a schema-bound view,
the ALTER TABLE statement fails.
Consider the schema-bound view that was created in Code Snippet 25. It is dependent on the
Production.Product table.
Code Snippet 32 tries to modify the data type of ProductID column in the Production.Product
table from int to varchar(7).
Code Snippet 32:
ALTER TABLE Production.Product ALTER COLUMN ProductID varchar(7)
The Database Engine returns an error message as the table is schema-bound to the
vwNewProductInfo view and hence, cannot be altered such that it violates the view definition of
the view. 10.11 Stored Procedures
A stored procedure is a group of Transact-SQL statements that act as a single block of code that
performs a specific task. This block of code is identified by an assigned name and is stored in the
database in a compiled form. A stored procedure may also be a reference to a .NET Framework
Common Language Runtime (CLR) method.
Stored procedures are useful when repetitive tasks have to be performed. This eliminates the
need for repetitively typing out multiple Transact-SQL statements and then repetitively
compiling them.
5 of 45
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
5 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
→
Extended Stored Procedures
Extended stored procedures help SQL Server in interacting with the operating system. Extended
stored procedures are not resident objects of SQL Server. They are procedures that are
implemented as dynamic-link libraries (DLL) executed outside the SQL Server environment.
The application interacting with SQL Server calls the DLL at run-time. The DLL is dynamically
loaded and run by SQL Server. SQL Server allots space to run the extended stored procedures.
Extended stored procedures use the 'xp' prefix. Tasks that are complicated or cannot be executed
using Transact-SQL statements are performed using extended stored procedures.
→
System Stored Procedures
System stored procedures are commonly used for interacting with system tables and performing
administrative tasks such as updating system tables. The system stored procedures are prefixed
with 'sp_'. These procedures are located in the Resource database. These procedures can be seen
in the sys schema of every system and user-defined database. System stored procedures allow
GRANT, DENY, and REVOKE permissions.
A system stored procedure is a set of pre-compiled Transact-SQL statements executed as a single
unit. System procedures are used in database administrative and informational activities. These
procedures provide easy access to the metadata information about database objects such as
system tables, user-defined tables, views, and indexes.
System stored procedures logically appear in the sys schema of system and user-defined
databases. When referencing a system stored procedure, the sys schema identifier is used. The
system stored procedures are stored physically in the hidden Resource database and have the sp_
prefix. System stored procedures are owned by the database administrator.
Note - System tables are created by default at the time of creating a new database. These tables
store the metadata information about user-defined objects such as tables and views. Users cannot
access or update the system tables using system stored procedures except through permissions
granted by a database administrator. 10.11.2 Classificafion of System Stored Procedures
System stored procedures can be classified into different categories depending on the tasks they
perform. Some of the important categories are as follows:
→
Catalog Stored Procedures
All information about tables in the user database is stored in a set of tables called the system
catalog. Information from the system catalog can be accessed using catalog procedures. For
example, the sp_tables catalog stored procedure displays the list of all the tables in the current
database.
→
Security Stored Procedures
Security stored procedures are used to manage the security of the database. For example, the
sp_changedbowner security stored procedure is used to change the owner of the current database.
5 of 45
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
5 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
1 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
The output is shown in figure 10.10.
Figure 10.10: Output of a Simple Stored Procedure
Session
→
10
Using Views, Stored Procedures, and Querying Metadata
Output Parameters
Stored procedures occasionally need to return output back to the calling program. This transfer
of data from the stored procedure to the calling program is performed using output parameters.
Output parameters are defined at the time of creation of the procedure. To specify an output
parameter, the OUTPUT keyword is used while declaring the parameter. Also, the calling
statement has to have a variable specified with the OUTPUT keyword to accept the output from
the called procedure.
The following syntax is used to pass output parameters in a stored procedure and then, execute
the stored procedure with the OUTPUT parameter specified.
Syntax:
EXECUTE <procedure_name> <parameters>
Code Snippet 37 creates a stored procedure, uspGetTotalSales with input parameter @territory to
accept the name of a territory and output parameter @sum to display the sum of sales year to
date in that territory.
Code Snippet 37:
CREATE PROCEDURE uspGetTotalSales
@territory varchar(40), @sum int OUTPUT
AS
SELECT @sum= SUM(B.SalesYTD)
FROM Sales.SalesPerson A
JOIN Sales.SalesTerritory B
ON A.TerritoryID = B.TerritoryID
WHERE B.Name = @territory
Code Snippet 38 declares a variable sumsales to accept the output of the procedure
uspGetTotalSales.
Code Snippet 38:
DECLARE @sumsales money;
EXEC uspGetTotalSales 'Northwest', @sum = @sum OUTPUT;
PRINT 'The year-to-date sales figure for this territory is ' + convert(varchar(100),@sumsales);
GO
The code passes Northwest as the input to the uspGetTotalSales stored procedure and accepts the
output in the variable sumsales. The output is printed using the PRINT command.
V 1.0 © Aptech Limited
OUTPUT parameters have the following characteristics:
•
The parameter cannot be of text and image data type.
•
The calling statement must contain a variable to receive the return value.
•
The variable can be used in subsequent Transact-SQL statements in the batch or the calling
procedure.
•
Output parameters can be cursor placeholders.
The OUTPUT clause returns information from each row on which the INSERT, UPDATE, and
DELETE statements have been executed. This clause is useful to retrieve the value of an identity
or computed column after an INSERT or UPDATE operation.
Session
10
Using Views, Stored Procedures, and Querying Metadata
Figure 10.1: Specify Values for Template Parameters Dialog Box
V 1.0 © Aptech Limited
5 of 45
of 45
Session
7.
8.
9.
10.
11.
12.
10
Using Views, Stored Procedures, and Querying Metadata
In the Specify Values for Template Parameters dialog box, enter the following values for the
parameters as shown in table 10.2.
Parameter Value
Author Your name Create Date Today's date Description Returns year to sales data for a territory
Procedure_Name uspGetTotals @Param1 @territory @Datatype_For_Param1 varchar(50)
Default_Value_For_Param1 NULL @Param2 @Datatype_For_Param2
Default_Value_For_Param2
Table 10.: Parameter Values
After entering these details, click OK.
In the Query Editor, replace the SELECT statement with the following statement:
SELECT BusinessEntityID, B.SalesYTD, B.SalesLastYear
FROM Sales.SalesPerson A
JOIN Sales.SalesTerritory B
ON A.TerritoryID = B.TerritoryID
WHERE B.Name = @territory;
To test the syntax, on the Query menu, click Parse. If an error message is returned, compare the
statements with the information and correct as needed.
To create the procedure, from the Query menu, click Execute. The procedure is created as an
object in the database.
To see the procedure listed in Object Explorer, right-click Stored Procedures and select Refresh.
V 1.0 © Aptech Limited
10 Session
Using Views, Stored Procedures, and Querying Metadata
The procedure name will be displayed in the Object Explorer tree as shown in figure 10.13.
Figure 10.1: Stored Procedure Seen in Object Explorer
13.
To run the procedure, in Object Explorer, right-click the stored procedure name uspGetTotals
and select Execute Stored Procedure.
14.
In the Execute Procedure window, enter Northwest as the value for the parameter @territory.
Note - In SQL Server 2012, a stored procedure can be up to 250 MB in size. In other words, the
bytes in source text of a stored procedure cannot exceed 250 MB.
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
1 of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
There are over 230 different system views and these are automatically inserted into the user
created database. These views are grouped into several different schemas.
→
System Catalog Views
These contain information about the catalog in a SQL Server system. A catalog is similar to an
inventory of objects. These views contain a wide range of metadata. In earlier versions of SQL
Server, users were required to query a large number of system tables, system views, and system
functions. In SQL Server 2012, all user-accessible catalog metadata can easily be found by
querying just the catalog views.
Code Snippet 45 retrieves a list of user tables and attributes from the system catalog view
sys.tables.
Code Snippet 45:
SELECT name, object_id, type, type_desc
FROM sys.tables;
→
Information Schema Views
Users can query information schema views to return system metadata. These views are useful to
third-party tools that may not be specific for SQL Server. Information schema views provide an
internal, system table-independent view of the SQL Server metadata. Information schema views
enable applications to work correctly although significant changes have been made to the
underlying system tables.
The following points in table 10.3 will help to decide whether one should query SQL Server-
specific system views or information schema views:
Information Schema Views SQL Server System Views
They are stored in their own schema,
They appear in the sys schema.
INFORMATION_SCHEMA. They use standard terminology instead of SQL
They adhere to SQL Server Server terms.
For example, they use catalog instead
terminology. of database and domain
instead of user-defined data type. They may not expose all the metadata available to SQL
Server's own catalog views. For example, sys.columns includes attributes for the identity
property and computed column property, while INFORMATION_SCHEMA.columns does not.
V 1.0 © Aptech Limited
They can expose all the metadata available to SQL Server's catalog views.
Table 10.: Information schema views and SQL Server-specific system views
of 45
Code Snippet 46 retrieves data from the INFORMATION_SCHEMA.TABLES view in the
AdventureWorks2012 database: Code Snippet 46:
SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE
FROM INFORMATION_SCHEMA.TABLES;
→
System Metadata Functions
In addition to views, SQL Server provides a number of built-in functions that return metadata to
a query. These include scalar functions and table-valued functions, which can return information
about system settings, session options, and a wide range of objects.
SQL Server metadata functions come in a variety of formats. Some appear similar to standard
scalar functions, such as ERROR_NUMBER(). Others use special prefixes, such as
@@VERSION or $PARTITION. Table 10.4 shows some common system metadata functions.
Function Name Description Example OBJECT_ID(<object_name>) Returns the object
ID of a
database object.
OBJECT_ID('Sales. Customer') OBJECT_NAME(<object_id>) Returns the name corresponding
to an object ID.
OBJECT_ NAME(197575742)
@@ERROR Returns 0 if the last statement succeeded; otherwise returns the error number.
@@ERROR
SERVERPROPERTY(<property >) Returns the value of the specified server property.
SERVERPROPERTY('Collat ion')
Table 10.4: Common System Metadata Functions
Code Snippet 47 uses a SELECT statement to query a system metadata function. Code Snippet
47:
SELECT SERVERPROPERTY('EDITION') AS EditionName;
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
of 45
4 of 45
Session
Both DMVs and DMFs return data in tabular format but the difference is that while a DMF
normally accepts at least one parameter, a DMV does not accept parameters. SQL Server 2012
provides nearly 200 dynamic management objects. In order to query DMVs, it is required to
have VIEW SERVER STATE or VIEW DATABASE STATE permission, depending on the
scope of the DMV.
10
Using Views, Stored Procedures, and Querying Metadata
Figure 10.15: Querying the sys.dm_exec_sessions DMV
V 1.0 © Aptech Limited
10.18 Check Your Progress
1.
Which of these statements about views are true?
a. Views enable you to see and manipulate selected parts of a table.
b. Only columns from a table can be selected for a view, rows cannot be.
c. System views display information about the system or the machine.
d. Views have a maximum of 1024 columns.
e. When data in a view is changed, it is not reflected in the underlying table.
(A) a, c, d, e (C) a, b, d
(B) a, c (D) All of the above
2.
You are creating a view Supplier _ View with FirstName, LastName, and City columns from the
Supplier _ Details table. Which of the following code is violating the definition of a view?
(A)
CREATE VIEW Supplier_ View
AS
SELECT FirstName, LastName, City FROM Supplier_Details
WHERE City IN('New York', 'Boston', 'Orlando')
CREATE VIEW Supplier_View
AS
SELECT FirstName, LastName, City FROM Supplier_Details
ORDER BY FirstName
(B)
(C)
CREATE VIEW Supplier_ View
AS
SELECT TOP 100 FirstName, LastName, City FROM Supplier_Details
WHERE FirstName LIKE 'A%' ORDER BY FirstName
CREATE VIEW Supplier_View
AS (D)
SELECT TOP 100 FirstName, LastName, City FROM Supplier_Details
Session
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
5 of 45
of 45
Session
3.
4.
10
Using Views, Stored Procedures, and Querying Metadata
Which of these statements about CHECK OPTION and SCHEMABINDING options are true?
a. The CHECK OPTION ensures entity integrity.
b. The SCHEMABINDING option binds the view to the schema of the base table.
c.
When a row is modified, the WITH CHECK OPTION makes sure that the data remains visible
through the view.
d.
SCHEMABINDING option ensures the base table cannot be modified in a way that would affect
the view definition.
e. SCHEMABINDING option cannot be used with ALTER VIEW statements.
(A) a, b, c (C) b, c, d
(B) b, c (D) c, d, e
You want to create a view Account _ Details with the SCHEMABINDING option. Which of the
following code will achieve this objective?
CREATE VIEW Account_Details
AS
(A)
SELECT AccNo, City
FROM dbo.Customer_Details
WITH SCHEMABINDING
V 1.0 © Aptech Limited
CREATE VIEW Account_Details
WITH SCHEMABINDING
AS
SELECT AccNo, City
FROM dbo.Customer_Details
(B)
(C)
CREATE VIEW Account_Details
SCHEMABINDING
AS
SELECT AccNo, City
FROM Customer_Details
CREATE VIEW Account_Details
WITH SCHEMABINDING
(D)
AS
SELECT AccNo, City
FROM Customer_Details
10 Session
Using Views, Stored Procedures, and Querying Metadata
5.
A table Item _ Details is created with ItemCode, ItemName, Price, and Quantity columns. The
ItemCode column is defined as the PRIMARY KEY, ItemName is defined with UNIQUE and
NOT NULL constraints, Price is defined with the NOT NULL constraint, and Quantity is
defined with the NOT NULL constraint and having a default value specified. Which of the
following views created using columns from the Item _ Details table can be used to insert
records in the table?
CREATE VIEW ItemDetails
CREATE VIEW ItemDetails
AS
AS (A)
SELECT ItemCode,
(C)
SELECT ItemName, Price, ItemName, Price
Quantity
FROM Item_Details
FROM Item_Details CREATE VIEW ItemDetails
AS (B)
SELECT ItemCode, Price, Quantity
FROM Item_Details
6.
V 1.0 © Aptech Limited
CREATE VIEW ItemDetails
AS
SELECT ItemCode, ItemName, Quantity
FROM Item_Details
Which of these statements about stored procedures are true?
a.
(D)
A stored procedure is a group of Transact-SQL statements that act as a block of code used to
perform a particular task.
b. All system stored procedures are identified by the 'xp_' prefix.
c.
A distributed stored procedure is used in the management of distributed queries.
d.
Database Mail and SQL mail procedures are used to perform e-mail operations within SQL
Server.
e.
User-defined stored procedures are also known as custom stored procedures.
(A) a, d (C) a, c, d, e
(B) b, c, e (D) d
of 45
10 Session
Using Views, Stored Procedures, and Querying Metadata
10.18.1 Answers
1. B
2. C
3. C
4. B
5. A
6. C
of 45
Summary
→
A view is a virtual table that is made up of selected columns from one or more tables and is
created using the CREATE VIEW command in SQL Server.
→
Users can manipulate the data in views, such as inserting into views, modifying the data in
views, and deleting from views.
→
A stored procedure is a group of Transact-SQL statements that act as a single block of code that
performs a specific task.
→
SQL Server supports various types of stored procedures, such as User-Defined Stored
Procedures, Extended Stored Procedures, and System Stored Procedures.
→
System stored procedures can be classified into different categories such as Catalog Stored
Procedures, Security Stored Procedures, and Cursor Stored Procedures.
→
Input and output parameters can be used with stored procedures to pass and receive data from
stored procedures.
→
The properties of an object such as a table or a view are stored in special system tables and are
referred to as metadata.
→
DMVs and DMFs are dynamic management objects that return server and database state
information. DMVs and DMFs are collectively referred to as dynamic management objects.
V 1.0 © Aptech Limited
of 45
0 of 45
Session
1.
2.
3.
4.
5.
6.
10
Using Views, Stored Procedures, and Querying Metadata
V 1.0 © Aptech Limited
Try It Yourself
In SQL Server 2012 Management Studio, locate the extended stored procedures defined under
the master database and execute the following procedures in a query window:
sys.xp_readerrorlog
sys.xp_getnetname
sys.xp_fixeddrives
ShoezUnlimited is a trendy shoe store based in Miami. It stocks various kinds of footwear in its
store and sells them for profits. ShoezUnlimited maintains the details of all products in an SQL
Server 2012 database. The management wants their developer to make use of stored procedures
for commonly performed tasks. Assuming that you are the developer, perform the following
tasks:
Create the Shoes table having structure as shown in table 10.6 in the database, ShoezUnlimited.
Field Name Data Type Key Field Description ProductCode varchar(5) Primary Key Product
Code that uniquely identifies
each shoe BrandName varchar(30) Brand name of the shoe Category varchar(30) Category of the
shoe, such as for example, sports shoe, casual wear, party wear, and so forth UnitPrice money
Price of the shoe in dollars QtyOnHand int Quantity available
Table 10.: Shoes Table
Add at least 5 records to the table. Ensure that the value of the column QtyOnHand is more than
20 for each of the shoes.
Write statements to create a stored procedure named PriceIncrease that will increment the
unitprice of all shoes by 10 dollars.
Write statements to create a stored procedure QtyOnHand that will decrease the quantity on hand
of specified brands by 25. The brand name should be supplied as input.
Execute the stored procedures PriceIncrease and QtyOnHand.
11
Welcome to the Session, Indexes.
This session explains indexes and their performance. It also explains different
types of indexes. Finally, the session identifies and describes the procedure to
query performance data using indexes.
In this Session, you will learn to:
Define and explain indexes
Describe the performance of indexes
Explain clustered indexes
Explain nonclustered indexes
Explain partitioning of data
Explain the steps to display query performance data using indexes
Session -
→
→
→
→
→
→
Indexes
11 Session
Indexes
11.1 Introducfion
SQL Server 2012 makes use of indexes to find data when a query is processed. The SQL Server
engine uses an index in the similar way as a student uses a book index. For example, consider
that you need to find all references to INSERT statements in an SQL book. The immediate
approach taken will be to scan each page of the book beginning from the starting page. You mark
each time the word INSERT is found, until the end of the book is reached. This approach is time
consuming and laborious. The second way is to use the index in the back of the book to find the
page numbers for each occurrence of the INSERT statements. The second way produces the
same results as the first, but by tremendously saving time.
When SQL Server has not defined any index for searching, then the process is similar to the first
way in the example; the SQL engine needs to visit every row in a table. In database terminology,
this behavior is called table scan, or just scan.
A table scan is not always troublesome, but it is sometimes unavoidable. However, as a table
grows up to thousands and millions of rows and beyond, scans become slower and more
expensive. In such cases, indexes are strongly recommended.
Creating or removing indexes from a database schema will not affect an application's code.
Indexes operate in the backend with support of the database engine. Moreover, creating an
appropriate index can significantly increase the performance of an application.
Session
11
Indexes
V 1.0 © Aptech Limited
of 45
11 Session
Indexes
→
Secondary Data Files
Secondary data files are optional in a database and can be created to segregate database objects
such as tables, views, and procedures. The recommended file extension for secondary data files
is .ndf.
→
Log Files
Log files contain information about modifications carried out in the database. This information is
useful in recovery of data in contingencies such as sudden power failure or the need to shift the
database to a different server. There is at least one log file for each database. The recommended
file extension for log files is .ldf.
11.1.4 Indexes
In a table, records are stored in the order in which they are entered. Their storage in the database
is unsorted. When data is to be retrieved from such tables, the entire table needs to be scanned.
This slows down the query retrieval process. To speed up query retrieval, indexes need to be
created.
4 of 45
Session
11
Indexes
V 1.0 © Aptech Limited
5 of 45
Session
of 45
11.1.5 Scenario
In a telephone directory, where a large amount of data is stored and is frequently accessed, the
storage of data is done in an alphabetical order. If such data were unsorted, it would be nearly
impossible to search for a specific telephone number.
Similarly, in a database table having a large number of records that are frequently accessed, the
data is to be sorted for fast retrieval. When an index is created on the table, the index either
physically or logically sorts the records. Thus, searching for a specific record becomes faster and
there is less strain on system resources.
11
Indexes
V 1.0 © Aptech Limited
Hence, retrieval will be faster and there will be less strain on system resources.
Figure 11.: Accessing Data Group-wise
Session
11
Indexes
V 1.0 © Aptech Limited
Figure 11.: Index Architecture
of 45
11 Session
Indexes
11.2.1 B-Tree
In SQL Server, all indexes are structured in the form of B-Trees. A B-Tree structure can be
visualized as an inverted tree with the root right at the top, splitting into branches and then, into
leaves right at the bottom as shown in figure 11.8.
Figure 11.: B-Tree
In a B-Tree structure, there is a single root node at the top. This node then branches out into the
next level, known as the first intermediate level. The nodes at the first intermediate level can
branch out further. This branching can continue into multiple intermediate levels and then,
finally the leaf level. The nodes at the leaf level are known as the leaf nodes.
Note - A B-Tree index traverses from top to bottom by using pointers.
Session
11
Indexes
V 1.0 © Aptech Limited
of 45
11 Session
Indexes
Session
11
Indexes
V 1.0 © Aptech Limited
1 of 45
11 Session
Indexes
Code Snippet 2 creates a clustered index, IX_CustID on the CustID column in Customer_Details
table.
Code Snippet :
USE CUST_DB
CREATE CLUSTERED INDEX IX_CustID ON Customer_Details(CustID)
GO
Note - Before you create a clustered index, you need to make sure the free space in your system
is at least 1.2 times the amount of data in the table.
Session
11
Indexes
V 1.0 © Aptech Limited
of 45
11 Session
Indexes
Figure 11.14 shows a nonclustered index structure.
Figure 11.14: Nonclustered Index Structure
Nonclustered indexes are useful when you require multiple ways to search data. Some facts and
guidelines to be considered before creating a nonclustered index are as follows:
→
When a clustered index is re-created or the DROP _ EXISTING option is used, SQL Server
rebuilds the existing nonclustered indexes.
→
A table can have up to 999 nonclustered indexes.
→
Create clustered index before creating a nonclustered index.
The following syntax creates a nonclustered index.
Syntax:
CREATE NONCLUSTERED INDEX <index_name> ON <table_name> (column_name)
where,
NONCLUSTERED: specifies that a nonclustered index is created.
4 of 45
Session
11
Indexes
V 1.0 © Aptech Limited
5 of 45
11 Session
Indexes
For example, if there is a table with ten columns (C1 to C10), the data of all the ten columns
from each row gets stored together contiguously on the same page as shown in figure 11.15.
Figure 11.15: A B-Tree Index
When column store index is created, the data is stored column-wise, which means data of each
individual column from each rows is stored together on same page.
of 45
Session
11
Indexes
V 1.0 © Aptech Limited
of 45
11 Session
Indexes
(
[ProductKey],
[OrderDateKey],
[DueDateKey],
[ShipDateKey],
[CustomerKey],
[EmployeeKey],
[PromotionKey],
[CurrencyKey],
[SalesTerritoryKey],
[SalesOrderNumber],
[SalesOrderLineNumber],
[RevisionNumber],
[OrderQuantity],
[UnitPrice],
[ExtendedAmount],
[UnitPriceDiscountPct],
[DiscountAmount],
[ProductStandardCost],
[TotalProductCost],
[SalesAmount],
[TaxAmt],
[Freight],
[CarrierTrackingNumber],
[CustomerPONumber],
[OrderDate],
[DueDate],
[ShipDate]
);
Note - COLUMNSTORE INDEX works only on enterprise edition of SQL Server 2012.
of 45
V 1.0 © Aptech Limited
11.2.10 Dropping an Index
On dropping a clustered index, the rows in the leaf level of the clustered index are copied to a
heap. All the nonclustered indexes on the table should then point to the heap in which the data is
stored. This is done by rebuilding nonclustered indexes when the clustered index is dropped.
Thus, dropping the clustered index is a time-consuming process. Therefore, while dropping all
indexes on a table, you must first drop the nonclustered indexes first and then, the clustered
index.
SQL Server 2012 can drop the clustered index and move the heap (unordered table) into another
filegroup or a partition scheme using the MOVE TO option.
→
This option is not valid for nonclustered indexes.
→
The partition scheme or filegroup specified in the MOVE TO clause must already exist.
→
The table will be located in the same partition scheme or filegroup of the dropped clustered
index.
The following is the syntax to drop a clustered index.
Syntax:
DROP INDEX <index_name> ON <table_name>
[ WITH ( MOVE TO { <partition_scheme_name> ( <column_name> )
| <filegroup_name>
| 'default'
})
]
where,
index_name: specifies the name of the index.
partition_scheme_name: specifies the name of the partition scheme.
filegroup_name: specifies the name of the filegroup to store the partitions.
default: specifies the default location to store the resulting table.
Code Snippet 5 drops the index IX_SuppID created on the SuppID column of the
Supplier_Details table.
Code Snippet 5:
DROP INDEX IX_SuppID ON Supplier_Details
WITH (MOVE TO 'default')
Session
11
Indexes
V 1.0 © Aptech Limited
of 45
11
Indexes
The data in the resulting Supplier_Details table is moved to the default location.
Code Snippet 6 drops the index IX_SuppID created on the SuppID column of the
Supplier_Details table.
Code Snippet 6:
DROP INDEX IX_SuppID ON Supplier_Details
WITH (MOVE TO FGCountry)
The data in the resulting Supplier_Details table is moved to the FGCountry filegroup.
Session
11
Indexes
V 1.0 © Aptech Limited
01 of 45
Session
0 of 45
11
Indexes
Secondary XML indexes can only be created on columns that already have a primary XML
index.
Code Snippet 8 demonstrates how to create a secondary XML index on the CatalogDescription
column in the Production.ProductModel table.
Code Snippet 8:
USE AdventureWorks2012;
CREATE XML INDEX IXML_ProductModel_CatalogDescription_Path
ON Production.ProductModel (CatalogDescription)
USING XML INDEX PXML_ProductModel_CatalogDescription FOR PATH ;
GO
Selective XML Indexes (SXI) – This is a new type of XML index introduced by SQL Server
2012. The features of this new index is to improve querying performance over the data stored as
XML in SQL Server, allows faster indexing of large XML data workloads, and improves
scalability by reducing storage costs of the index. The following is the syntax to create selective
XML index.
Syntax:
CREATE SELECTIVE XML INDEX index_name ON <table_name> (column_name)
The following is an XML document in a table of approximately 500,000 rows.
<book>
<created>2004-03-01</created>
<authors>Various</authors>
<subjects>
<subject>English wit and humor -- Periodicals</subject>
<subject>AP</subject>
</subjects>
<title>Punch, or the London Charivari, Volume 156, April 2, 1919</ title>
<id>etext11617</id>
</book>
V 1.0 © Aptech Limited
Code Snippet 9 demonstrates how to create a Selective XML index on the BookDetails column
in the BooksBilling table.
Code Snippet 9:
USE CUST_DB
CREATE SELECTIVE XML INDEX SXI_index
ON BooksBilling(BookDetails)
FOR
(
pathTitle = '/book/title/text()' AS XQUERY 'xs:string',
pathAuthors = '/book/authors' AS XQUERY 'node()',
pathId = '/book/id' AS SQL NVARCHAR(100)
)
GO
Note - SELECTIVE XML INDEX will work only in enterprise edition of SQL Server 2012.
Session
11
Indexes
V 1.0 © Aptech Limited
0 of 45
11 Session
Indexes
Code Snippet 11 removes the primary XML index PXML_DocumentStore created on the
XMLDocument table.
Code Snippet 11:
DROP INDEX PXML_DocumentStore ON XMLDocument
Session
11
Indexes
V 1.0 © Aptech Limited
05 of 45
Session
0 of 45
Column Name Data Type Description index_id int Contains the id of the index to which the
partition belongs. partition_number int Contains the partition number within the index or heap.
hobt_id bigint Contains the id of the data heap or B-Tree that contains the
rows for the partition. rows bigint States the approximate number of rows in the partition.
Table 11.: Columns of the sys.partitions View and Data Types
11
Indexes
Figure 11.0: The Index_id Column
V 1.0 © Aptech Limited
11.5 Finding Rows
SQL Server uses catalog views to find rows when an index is not created on a table. It uses the
sys.indexes view to find the IAM page. This IAM page contains a list of all pages of a specific
table through which SQL Server can read all data pages.
When the sys.indexes view is used, the query optimizer checks all rows in a table and extracts
only those rows that are referenced in the query as shown in figure 11.21. This scan generates
many I/O operations and utilizes many resources.
Figure 11.1: Finding Rows without Indexes
Code Snippet 12 demonstrates how to create a table Employee_Details without an index.
Code Snippet 12:
USE CUST_DB
CREATE TABLE Employee_Details
(
EmpID int not null,
FirstName varchar(20) not null,
LastName varchar(20) not null,
DateofBirth datetime not null,
Gender varchar(6) not null,
Session
11
Indexes
V 1.0 © Aptech Limited
0 of 45
Session
0 of 45
11
Indexes
Figure 11.: Finding Rows with Nonclustered Index
V 1.0 © Aptech Limited
Code Snippet 13 demonstrates how to create a nonclustered index IX_EmployeeCity on the City
column of the Employee_Details table.
Code Snippet 13:
USE CUST_DB
CREATE NONCLUSTERED INDEX IX_EmployeeCity ON Employee_Details(City);
GO
Assume that multiple records are inserted in the table, Employee_Details. The SELECT
statement is used to search for records of employees from city, Boston as shown in Code Snippet
14.
Code Snippet 14:
USE CUST_DB
SELECT EmpID,FirstName,LastName,City FROM Employee_Details WHERE City='Boston'
GO
Since there is a nonclustered index associated with City column, SQL Server will use the
IX_EmployeeCity index to extract the records as shown in figure 11.23.
Figure 11.: The IX_EmployeeCity Index
Note - In a table having a nonclustered index, there is no specific storage order of the data. Data
is retrieved directly from its physical location.
Session
11
Indexes
V 1.0 © Aptech Limited
0 of 45
Session
10 of 45
Figure 11.24 shows the process of finding rows with clustered index.
Figure 11.4: Finding Rows with Clustered Index
Code Snippet 15 demonstrates how to create a clustered index IX_EmployeeID on the EmpID
column of the Employee_Details table.
Code Snippet 15:
USE CUST_DB
CREATE UNIQUE CLUSTERED INDEX IX_EmployeeID ON Employee_Details(EmpID);
GO
Assume that multiple records are inserted in the table, Employee_Details. The SELECT
statement is used to search for records of employees having EmpID between 102 and 105 as
shown in Code Snippet 16.
Code Snippet 16:
USE CUST_DB
SELECT EmpID,FirstName,LastName,City FROM Employee_Details WHERE EmpID >= 102 AND
EmpID <= 105;
GO
11
Indexes
V 1.0 © Aptech Limited
Since there is a clustered index associated with the EmpID column, SQL Server will use the
IX_EmployeeID index to extract the records as shown in figure 11.25.
Figure 11.5: The IX_EmployeeID Index
Session
11
Indexes
V 1.0 © Aptech Limited
Figure 11.: Creating Unique Indexes
11 of 45
Session
1 of 45
11
Indexes
V 1.0 © Aptech Limited
Code Snippet 18 creates a computed column Area whose values are calculated from the values
entered in the Length and Breadth fields.
Code Snippet 18:
USE SampleDB
CREATE TABLE Calc_Area(Length int, Breadth int, Area AS Length*Breadth)
GO
Note - A computed column cannot be used as a part of any PRIMARY KEY, UNIQUE KEY,
FOREIGN KEY, or CHECK constraint definition.
Session
11
Indexes
V 1.0 © Aptech Limited
1 of 45
11 Session
Indexes
Code Snippet 19 creates an index IX_Area on the computed column Area.
Code Snippet 19:
USE SampleDB
CREATE INDEX IX_Area ON Calc_Area(Area);
GO 11.6 Cursors
A database object that is used to retrieve data as one row at a time, from a resultset is called as
cursors. Cursors are used instead of the Transact-SQL commands that operate on all the rows at
one time in the resultset. Cursors are used when records in a database table need to be updated
one row at a time.
Types of Cursors
→
Static Cursors – These cursors help to populate the resultset when the cursor is created and the
query result is cached. This is the slowest of all the cursors. This cursor can move/scroll in both
backward and forward directions. Also, the static cursor cannot be updated or deleted.
→
Dynamic Cursors – These cursors allow you to view the procedures of insertion, updation, and
deletion when the cursor is open. This is one of the most sensitive cursor and is scrollable.
→
Forward Only Cursors - These cursors also support updation and deletion of data. This is the
fastest cursor though it does not support backward scrolling. The three types of forward cursors
are FORWARD _ ONLY KEYSET, FORWARD _ ONLY STATIC, and FAST _ FORWARD.
→
Keyset Driven Cursors - These cursors create a set of unique identifiers as keys in a keyset that
are used to control the cursor. This is also a sensitive cursor that can update and delete data. The
keyset is dependent on all the rows that qualify the SELECT statement at the time of opening the
cursor.
The following is the syntax to declare a cursor.
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
14 of 45
Session
11
Indexes
V 1.0 © Aptech Limited
15 of 45
11 Session
Indexes
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Derek',12000,'Ho usten')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'David',25000,'Te xas')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Alan',22000,'New York')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Mathew',22000,'l as Vegas')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Joseph',28000,'C hicago')
GO
SELECT * FROM Employee
Figure 11.29 shows the output of the code.
Figure 11.: Employee Table Created in SampleDB Database
Code Snippet 21 demonstrates how to declare a cursor on Employee table. Code Snippet 21:
USE SampleDB
SET NOCOUNT ON
DECLARE @Id int
DECLARE @name varchar(50)
DECLARE @salary int
/* A cursor is declared by defining the SQL statement that returns a resultset.*/
DECLARE cur_emp CURSOR
1 of 45
Session
11
Indexes
V 1.0 © Aptech Limited
Figure 11.0: Cursor Created on Employee Table
1 of 45
11 Session
Indexes
In the code, the details are retrieved one row at a time. This procedure will help in retrieving
large databases sequentially.
First, a cursor is declared by defining the SQL statement that returns a resultset. Then, it is
opened and populated by executing the SQL statement defined by the cursor. Rows are then
fetched from the cursor one by one or in a block to perform data manipulation.
The cursor is then closed and finally, the cursor definition is deleted and all the system resources
associated with the cursor are released.
1 of 45
Session
11
Indexes
V 1.0 © Aptech Limited
1 of 45
Session
0 of 45
5.
11
Indexes
A clustered index can be created on a table using a column without ________________ values.
(A) similar (C) transparent
(B) duplicate (D) any
V 1.0 © Aptech Limited
11.7.1 Answers
1. D
2. A
3. C
4. D
5. B
Session
11
Indexes
V 1.0 © Aptech Limited
1 of 45
Session
of 45
→
→
→
→
→
→
→
→
11
Indexes
V 1.0 © Aptech Limited
Summary
Indexes increase the speed of the querying process by providing quick access to rows or columns
in a data table.
SQL Server 2012 stores data in storage units known as data pages.
All input and output operations in a database are performed at the page level.
SQL Server uses catalog views to find rows when an index is not created on a table.
A clustered index causes records to be physically stored in a sorted or sequential order.
A nonclustered index is defined on a table that has data either in a clustered structure or a heap.
XML indexes can speed up queries on tables that have XML data.
Column Store Index enhances performance of data warehouse queries extensively.
1.
→
→
→
→
→
Session
11
Indexes
V 1.0 © Aptech Limited
Try It Yourself
Houston State Library is one of the renowned libraries in Houston, Texas. The library has a stock
of around 10, 00000 books of different genres. The library issues books to the students of the
college nearby. With the inflow of students coming to the library growing exponentially,
Houston State Library has decided to automate the entire process of issuing books to the
students. The library has increased the quantity of each book by 10 copies, depending upon the
demand made by the students.
Create a database named HoustonStateLibrary to store the details of books in the Library.
Create a table named BooksMaster to store the details of the books in the library as shown in
table 11.3.
Field Name Data Type Key Field Description BookCode varchar(50) Primary Key Stores book
code of the book
Title varchar(max) Stores the book title ISBN varchar(50) Stores the ISBN of the book Author
char(30) Stores author name of the book Price money Stores price of the book Publisher char(30)
Stores publisher name of the book NumPages numeric(10,0) Stores number of pages in the book
Table 11.: BooksMaster Table
Create a clustered index named IX _ Title on the Title column in the BooksMaster table.
Create a table BooksMaster1 having field names BookCode, Title, and Book Details. Specify the
data type for BookDetails as xml. Create an XML document with details of ISBN, Author, Price,
Publisher, and NumPages.
The library wants to retrieve the publisher name of the company which prints a specific author's
book. Create a primary XML index PXML _ Books on the BookCode column of the
BooksMaster table.
of 45
“ A wise man learns from the
mistakes “ of others, a fool by his
own
1 Session -
Welcome to the Session, Triggers.
This session explains the triggers and different types of triggers. The session also
describes the procedure to create and alter DML triggers, nested triggers, update
functions, handling multiple rows in a session, and performance implication of
triggers.
In this Session, you will learn to:
→
Explain triggers
→
Explain the different types of triggers
→
Explain the procedure to create DML triggers
→
Explain the procedure to alter DML triggers
→
Describe nested triggers
→
Describe update functions
→
Explain the handling of multiple rows in a session
→
Explain the performance implication of triggers
Triggers
1 Session
Triggers
12.1 Introducfion
A trigger is a stored procedure that is executed when an attempt is made to modify data in a table
protected by the trigger. Unlike standard system stored procedures, triggers cannot be executed
directly, nor do they pass or receive parameters. Triggers are defined on specific tables and these
tables are referred to as trigger tables.
If a trigger is defined on the INSERT, UPDATE, or DELETE action on a table, it fires
automatically when these actions are attempted. This automatic execution of the trigger cannot
be circumvented. In SQL Server 2012, triggers are created using the CREATE TRIGGER
statement. Figure 12.1 displays an example of triggers.
Figure 1.1: Triggers
Session
1
Triggers
V 1.0 © Aptech Limited
of 45
1
Triggers
→
Logon Triggers
Logon triggers execute stored procedures when a session is established with a LOGON event.
These triggers are invoked after the login authentication is complete and before the actual session
is established. Logon triggers control server sessions by restricting invalid logins or limiting the
number of sessions.
Session
1
Triggers
V 1.0 © Aptech Limited
of 45
1 Session
Triggers
If the record is valid, the INSERT trigger inserts the row in the trigger table otherwise, it displays
an error message.
An INSERT trigger is created using the INSERT keyword in the CREATE TRIGGER and
ALTER TRIGGER statements.
The following is the syntax for creating an INSERT trigger.
Syntax:
CREATE TRIGGER [schema_name.] trigger_name
ON [schema_name.] table_name
[WITH ENCRYPTION]
{FOR INSERT}
AS
[IF UPDATE (column_name)...]
[{AND | OR} UPDATE (column_name)...]
<sql_statements>
where,
schema_name: specifies the name of the schema to which the table/trigger belongs.
trigger_name: specifies the name of the trigger.
table_name: specifies the table on which the DML trigger is created.
WITH ENCRYPTION: encrypts the text of the CREATE TRIGGER statement.
FOR: specifies that the DML trigger executes after the modification operations are complete.
INSERT: specifies that this DML trigger will be invoked by insert operations.
UPDATE: Returns a Boolean value that indicates whether an INSERT or UPDATE attempt was
made on a specified column.
column_name: Is the name of the column to test for the UPDATE action.
AND: Combines two Boolean expressions and returns TRUE when both expressions are TRUE.
OR: Combines two Boolean expressions and returns TRUE if at least one expression is TRUE.
sql_statement: specifies the SQL statements that are executed in the DML trigger.
0 of 45
Session
1
Triggers
V 1.0 © Aptech Limited
1 of 45
1 Session
Triggers
An UPDATE trigger is created using the UPDATE keyword in the CREATE TRIGGER and
ALTER TRIGGER statements. The following is the syntax for creating an UPDATE trigger at
the table-level.
Syntax:
CREATE TRIGGER [schema_name.] trigger_name
ON [schema_name.] table_name
[WITH ENCRYPTION]
{FOR UPDATE}
AS
[IF UPDATE (column_name)...]
[{AND | OR} UPDATE (column_name)...]
<sql_statements>
where,
FOR UPDATE: specifies that this DML trigger will be invoked after the update operations.
Code Snippet 3 creates an UPDATE trigger at the table level on the EmployeeDetails table.
When a record is modified, the UPDATE trigger is activated. It checks whether the date of birth
is greater than today's date. It displays an error message for invalid values and rolls back the
modification operation using the ROLLBACK TRANSACTION statement. Code Snippet 3:
CREATE TRIGGER CheckBirthDate
ON EmployeeDetails
FOR UPDATE
AS
IF (SELECT BirthDate From inserted) > getDate()
BEGIN
PRINT 'Date of birth cannot be greater than today's date'
ROLLBACK
END
of 45
Session
1
Triggers
V 1.0 © Aptech Limited
of 45
1 Session
Triggers
Code Snippet 6 updates a record where the value in the EmployeeID column is being modified.
This causes the update trigger to fire. The update trigger displays an error message and rolls back
the transaction. Code Snippet 6:
UPDATE EmployeeDetails
SET EmployeeID='E12'
WHERE EmployeeID='E04'
Session
1
Triggers
V 1.0 © Aptech Limited
5 of 45
1 Session
Triggers
Figure 12.3 displays the types of AFTER triggers.
Figure 1.: AFTER Triggers
The following is the syntax for creating an AFTER trigger. Syntax:
CREATE TRIGGER <trigger_name>
ON <table_name>
[WITH ENCRYPTION]
{ FOR | AFTER }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
AS <sql_statement>
where,
FOR | AFTER: specifies that the DML trigger executes after the modification operations are
complete.
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }: specifies the operations that invoke the DML
trigger.
of 45
Session
1
Triggers
V 1.0 © Aptech Limited
of 45
1 Session
Triggers
Figure 12.4 displays an example of INSTEAD OF triggers.
Figure 1.4: INSTEAD OF Triggers
In the example shown in figure 12.4, an INSTEAD OF DELETE trigger on the Account_Types
table is created. If any record in the Account_Types table is deleted, the corresponding records in
the Customer_Details table will also be removed. Thus, instead of working only on one table,
here, the trigger ensures that the delete operation is performed on both the tables.
Note - Users cannot create INSTEAD OF triggers for delete or update operations on tables that
have the ON DELETE cascade and ON UPDATE cascade options selected.
The following is the syntax for creating an INSTEAD OF trigger.
Syntax:
CREATE TRIGGER <trigger_name>
ON { <table_name> | <view_name> }
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
AS <sql_statement>
where,
view_name: specifies the view on which the DML trigger is created.
of 45
Session
1
Triggers
V 1.0 © Aptech Limited
of 45
Session
40 of 45
1
Triggers
Figure 1.5: Using INSTEAD OF Triggers with Views
V 1.0 © Aptech Limited
Code Snippet 12 creates a table named Employee_Personal_Details. Code Snippet 12:
CREATE TABLE Employee_Personal_Details
(
EmpID int NOT NULL,
FirstName varchar(30) NOT NULL,
LastName varchar(30) NOT NULL,
Address varchar(30)
)
Code Snippet 13 creates a table named Employee_Salary_Details. Code Snippet 13:
CREATE TABLE Employee_Salary_Details
(
EmpID int NOT NULL,
Designation varchar(30),
Salary int NOT NULL
)
Code Snippet 14 creates a view Employee_Details_View using columns from the
Employee_Personal_Details and Employee_Salary_Details tables by joining the two tables on
the EmpID column. Code Snippet 14:
CREATE VIEW Employee_Details_View
AS
SELECT e1.EmpID, FirstName, LastName, Designation, Salary
FROM Employee_Personal_Details e1
JOIN Employee_Salary_Details e2
ON e1.EmpID = e2.EmpID
Session
1
Triggers
V 1.0 © Aptech Limited
41 of 45
1 Session
Triggers
Code Snippet 15 creates an INSTEAD OF DELETE trigger Delete_Employees on the view
Employee_Details_View. When a row is deleted from the view, the trigger is activated. It deletes
the corresponding records from the base tables of the view, namely, Employee_Personal_Details
and Employee_Salary_Details. Code Snippet 15:
CREATE TRIGGER Delete_Employees
ON Employee_Details_View
INSTEAD OF DELETE
AS
BEGIN
DELETE FROM Employee_Salary_Details WHERE EmpID IN
(SELECT EmpID FROM deleted)
DELETE FROM Employee_Personal_Details WHERE EmpID IN
(SELECT EmpID FROM deleted)
Code Snippet 16 deletes a row from the view Employee_Details_View where EmpID='2'. Code
Snippet 16:
DELETE FROM Employee_Details _View WHERE EmpID='3'
Session
1
Triggers
V 1.0 © Aptech Limited
4 of 45
1 Session
Triggers
Figure 12.7 displays the execution order of DML Triggers.
Figure 1.: Execution Order of DML Triggers
The following is the syntax for specifying execution order of multiple AFTER DML triggers.
Syntax:
sp_settriggerorder [ @triggername = ] '[ triggerschema. ] triggername'
, [ @order = ] 'value'
, [ @stmttype = ] 'statement_type'
where,
[ triggerschema.] triggername: is the name of the DML or DDL trigger and the schema to which
it belongs and whose order needs to be specified.
44 of 45
Session
1
Triggers
V 1.0 © Aptech Limited
45 of 45
1 Session
Triggers
If the user wants to modify any of these parameters for a DML trigger, a user can do so in any
one of two ways:
→
Drop and re-create the trigger with the new parameters.
→
Change the parameters using the ALTER TRIGGER statement.
If the object referencing a DML trigger is renamed, the trigger must be modified to reflect the
change in object name.
Note - A DML trigger can be encrypted to hide its definition.
Figure 1.: Modifying DML Triggers
The following is the syntax for modifying a DML trigger. Syntax:
ALTER TRIGGER <trigger_name>
ON { <table_name> | <view_name> }
[WITH ENCRYPTION]
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
AS <sql_statement>
where,
WITH ENCRYPTION: specifies that the DML trigger definitions are not displayed.
FOR | AFTER: specifies that the DML trigger executes after the modification operations are
complete.
INSTEAD OF: specifies that the DML trigger executes in place of the modification operations.
4 of 45
Session
1
Triggers
V 1.0 © Aptech Limited
4 of 45
1 Session
Triggers
Figure 12.9 depicts the concept of dropped DML triggers.
Figure 1.: Dropping DML Triggers
Note - When the DML trigger is deleted from the table, the information about the trigger is also
removed from the catalog views.
The following is the syntax for dropping DML triggers. Syntax:
DROP TRIGGER <DML_trigger_name> [ ,...n ]
where,
DML_trigger_name: specifies the name of the DML trigger to be dropped.
[ ,...n ]: specifies that multiple DML triggers can be dropped.
Code Snippet 20 drops the CheckEmployeeID trigger created on the EmployeeDetails table.
Code Snippet 20:
DROP TRIGGER CheckEmployeeID
Session
1
Triggers
V 1.0 © Aptech Limited
4 of 45
1 Session
Triggers
Code Snippet 21 creates a DDL trigger for dropping and altering a table. Code Snippet 21:
CREATE TRIGGER Secure
ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
PRINT 'You must disable Trigger "Secure" to drop or alter tables!'
ROLLBACK;
In this code, the DDL trigger is created for DROP TABLE and ALTER TABLE statements.
Session
1
Triggers
V 1.0 © Aptech Limited
51 of 45
1 Session
Triggers
Code Snippet 22 creates an AFTER DELETE trigger named Employee_Deletion on the
Employee_Personal_Details table. Code Snippet 22:
CREATE TRIGGER Employee_Deletion
ON Employee_Personal_Details
AFTER DELETE
AS
BEGIN
PRINT 'Deletion will affect Employee_Salary_Details table'
DELETE FROM Employee_Salary_Details WHERE EmpID IN
(SELECT EmpID FROM deleted)
END
When a record is deleted from the Employee_Personal_Details table, the Employee_Deletion
trigger is activated and a message is displayed. Also, the record of the employee is deleted from
the Employee_Salary_Details table.
Code Snippet 23 creates an AFTER DELETE trigger Deletion_Confirmation on the
Employee_Salary_Details table. Code Snippet 23:
CREATE TRIGGER Deletion_Confirmation
ON Employee_Salary_Details
AFTER DELETE
AS
BEGIN
PRINT 'Employee details successfully deleted from Employee_Salary_Details table'
END
DELETE FROM Employee_Personal_Details WHERE EmpID=1
When a record is deleted from the Employee_Salary_Details table, the Deletion_Confirmation
trigger is activated. This trigger prints the confirmation message of the record being deleted.
Thus, the Employee_Deletion and the Deletion_Confirmation triggers are seen to be nested.
5 of 45
Session
1
Triggers
V 1.0 © Aptech Limited
5 of 45
1 Session
Triggers
Code Snippet 25 stores a running total for a single-row insert. Code Snippet 25:
USE AdventureWorks2012;
GO
CREATE TRIGGER PODetails
ON Purchasing.PurchaseOrderDetail
AFTER INSERT AS
UPDATE PurchaseOrderHeader
SET SubTotal = SubTotal + LineTotal
FROM inserted
WHERE PurchaseOrderHeader.PurchaseOrderID = inserted.PurchaseOrderID;
In this code, the subtotal is calculated and stored for a single-row insert operation.
Code Snippet 26 stores a running total for a multi-row or single-row insert. Code Snippet 26:
USE AdventureWorks2012;
GO
CREATE TRIGGER PODetailsMultiple
ON Purchasing.PurchaseOrderDetail
AFTER INSERT AS
UPDATE Purchasing.PurchaseOrderHeader
SET SubTotal = SubTotal +
(SELECT SUM(LineTotal)
FROM inserted
WHERE PurchaseOrderHeader.PurchaseOrderID
= inserted.PurchaseOrderID)
WHERE PurchaseOrderHeader.PurchaseOrderID IN
(SELECT PurchaseOrderID FROM inserted);
In this code, the subtotal is calculated and stored for a multi-row or single-row insert operation.
54 of 45
Session
1
Triggers
V 1.0 © Aptech Limited
55 of 45
1
Triggers
a. Session
d.
Executes when users replace an existing record with a new value.
1. INSERT
b.
Executes on completion of the modification operations.
2. UPDATE
c.
Executes in place of the modification operations.
3. DELETE
d.
Executes table.
when users add a record on a
4. AFTER
e.
Executes when users remove a record from a table.
5. INSTEAD OF
(A) a-1, b-4, c-2, d-3, e-5 (C) a-2, b-4, c-3, d-5, e-1
(B) a-2, b-4, c-5, d-1, e-3 (D) a-1, b-2, c-3, d-4, e-5
5 of 45
1 Session
Triggers
3.
Which of these statements about DML triggers in SQL Server 2012 are true?
a.
DML triggers can perform multiple actions for each modification statement.
V 1.0 © Aptech Limited
UPDATE triggers do not use the Deleted table to update records in a table.
b.
4.
5.
c.
The Inserted and Deleted tables are created by SQL Server 2012 when a new table is created in
the database.
Deleted triggers do not use the Inserted table to delete records from a table.
(A) a, b (C) a, d
(B) c, d (D) b, d
Which of these statements about the working with DML triggers of SQL Server 2012 are true?
a.
d.
Each triggering action cannot have multiple AFTER triggers.
DML trigger definition can be modified by dropping and recreating the trigger.
b.
c.
Two triggering actions on a table can have the same first and last triggers.
d.
DML trigger definition can be viewed using the sp_helptext stored procedure.
(A) a, c (C) b, d
(B) b, c (D) c, d
________________ triggers can be used to perform the functions such as storing the backup of
the rows that are affected by the previous actions.
(A) Nested (C) DDL
(B) DML (D) INSTEAD OF
5 of 45
1 Session
Triggers
12.14.1 Answers
1. A
2. B
3. C
4. D
5. A
5 of 45
Summary
→
A trigger is a stored procedure that is executed when an attempt is made to modify data in a table
that is protected by the trigger.
→
Logon triggers execute stored procedures when a session is established with a LOGON event.
→
DML triggers are executed when DML events occur in tables or views.
→
The INSERT trigger is executed when a new record is inserted in a table.
→
The UPDATE trigger copies the original record in the Deleted table and the new record into the
Inserted table when a record is updated.
→
The DELETE trigger can be created to restrict a user from deleting a particular record in a table.
→
The AFTER trigger is executed on completion of INSERT, UPDATE, or DELETE operations.
V 1.0 © Aptech Limited
5 of 45
Session
0 of 45
1
Triggers
V 1.0 © Aptech Limited
Try It Yourself
Galaxy 1.
Airlines is a newly launched airline service that operates flights to and from various cities
all over Europe. The company maintains the data pertaining to day-to-day transactions regarding
flight services in SQL Server 2012 databases. To enable efficient and faster performance, Galaxy
Airlines has decided to incorporate use of triggers in their database applications. The detailed list
of operations to be performed are listed as follows:
a.
Create the following tables in GalaxyAirlines database. Table 12.2 lists the Flight table.
Field Name Data Type Key Field Description Aircraft_code varchar(10) Primary key Stores
aircraft code Type varchar(6) Describes the type of aircraft Source varchar(20) Stores the name
of the city from
where the aircraft will depart
Destination varchar(20) Stores the name of the city where
the aircraft will arrive Dep_time
varchar(10) Stores departure time Journey_hrs int Stores journey hours
Table 1.: Flight Table
Table 12.3 lists the Flight_Details table.
Field Name Data Type Key Field Description Class_Code varchar(10) Primary key Stores the
class, whether first,
business or economy Aircraft_code
varchar(10) Foreign key Stores aircraft code Fare money Stores the fare amount Seats int Stores
total number of seats on
the flight
Table 1.: Flight_Details Table
b.
Write statements to create a trigger trgCheckSeats that will activate whenever a new row is being
inserted into the Flight_Details table. The maximum limit of seats that a flight can contain is 150.
The trigger should check for the value of seats being inserted. If it is more than 150, the INSERT
operation is not allowed to succeed.
Session
c.
d.
e.
1
Triggers
V 1.0 © Aptech Limited
Try It Yourself
Insert at least five records in each table.
Write statements to create a trigger UpdateValid that will activate whenever a row is being
updated in the Flight_Details table. The trigger should determine if the Seats column is present in
the list of columns being updated. If yes, the UPDATE operation should not succeed because the
Seats column is defined as a constant and cannot be changed.
Write statements to create a DDL trigger ProhibitDelete that will activate whenever a user is
trying to delete a table from the Galaxy Airlines database. The trigger must not allow a user to
perform deletes and must display a message "You are not allowed to delete tables in this
database".
1 of 45
“
“
Democritus shadows said, of
words actions
are but the
1 Session - Programming Transact-
SQL
Welcome to the Session, Programming Transact-SQL.
This session introduces programming with Transact-SQL and describes various
Transact-SQL programming elements. The session also describes program flow
statements, Transact-SQL functions, and so on. The session further explains the
procedure to create and alter user-defined functions, and create windows using the
OVER and window functions.
In this Session, you will learn to:
→
Describe an overview of Transact-SQL programming
→
Describe the Transact-SQL programming elements
→
Describe program flow statements
→
Describe various Transact-SQL functions
→
Explain the procedure to create and alter user-defined functions (UDFs)
→
Explain creation of windows with OVER
→
Describe window functions
1 Session
Programming Transact-SQL
13.1 Introducfion
Transact-SQL programming is a procedural language extension to SQL. Transact-SQL
programming is extended by adding the subroutines and programming structures similar to high-
level languages. Like high-level languages, Transact-SQL programming also has rules and
syntax that control and enable programming statements to work together. Users can control the
flow of programs by using conditional statements such as IF and loops such as WHILE.
Session
1
Programming Transact-SQL
V 1.0 © Aptech Limited
5 of 45
1 Session
Programming Transact-SQL
AS
SELECT ProductNumber, Name
FROM Product;
GO
SELECT *
FROM dbo.vProduct;
GO
In this code snippet, a view is created in a batch. The CREATE VIEW is the only statement in
the batch, the GO commands are essential to separate the CREATE VIEW statement from the
SELECT and USE statements. This was a simple example to demonstrate the use of a batch. In
the real-world, a large number of statements may be used within a single batch. It is also possible
to combine two or more batches within a transaction.
Code Snippet 2 shows an example of this.
Code Snippet 2:
BEGIN TRANSACTION
GO
USE AdventureWorks2012;
GO
CREATE TABLE Company
(
Id_Num int IDENTITY(100, 5),
Company_Name nvarchar(100)
)
GO
INSERT Company (Company_Name)
VALUES (N'A Bike Store')
INSERT Company (Company_Name)
VALUES (N'Progressive Sports')
INSERT Company (Company_Name)
VALUES (N'Modular Cycle Systems')
INSERT Company (Company_Name)
VALUES (N'Advanced Bike Components')
of 45
1
Programming Transact-SQL
V 1.0 © Aptech Limited
of 45
Session
of 45
1
Programming Transact-SQL
where,
@local_variable: specifies the name of the variables and begins with @ sign.
data_type: specifies the data type. A variable cannot be of image, text, or ntext data type.
=value: Assigns an inline value to a variable. The value can be an expression or a constant value.
The value should match with the variable declaration type or it should be implicitly converted to
that type.
Code Snippet 3 uses a local variable to retrieve contact information for the last names starting
with Man.
Code Snippet 3:
USE AdventureWorks2012;
GO
DECLARE @find varchar(30) = 'Man%';
SELECT p.LastName, p.FirstName, ph.PhoneNumber
FROM Person.Person AS p
JOIN Person.PersonPhone AS ph ON p.BusinessEntityID = ph.BusinessEntityID
WHERE LastName LIKE @find;
In this code snippet, a local variable named @find is used to store the search criteria, which will
be then, used to retrieve the contact information. Here, the criteria include all last names
beginning with Man. Figure 13.1 displays the output.
Figure 1.1: Contact Information
SET
The SET statement sets the local variable created by the DECLARE statement to the specified
value.
V 1.0 © Aptech Limited
1 Session
Programming Transact-SQL
The following is the basic syntax to set a local variable.
Syntax:
SET
{ @local_variable = { expression}
}
|
{ @local_variable
{+= | -= | *= | /= | %= | &= | ^= | |= } expression
}
where,
@local_variable: specifies the name of the variable and begins with @ sign.
=: Assigns the value on the right-hand side to the variable on the left-hand side.
{= | += | -= | *= | /= | %= | &= | ^= | |= }: specifies the compound assignment operators. They are
as follows:
+= Add and then, assign
-= Subtract and then, assign
*= Multiply and then, assign
/= Divide and then, assign
%= Modulo and then, assign
&= Bitwise AND and then, assign
^= Bitwise XOR and then, assign
|= Bitwise OR and then, assign
expression: specifies any valid expression which can even include a scalar subquery.
Code Snippet 4 demonstrates the use of SET to assign a string value to a variable.
Code Snippet 4:
DECLARE @myvar char(20);
SET @myvar = 'This is a test';
In this code snippet, the @myvar variable is assigned a string value.
→
SELECT
The SELECT statement indicates that the specified local variable that was created using
DECLARE should be set to the given expression.
V 1.0 © Aptech Limited
of 45
1 Session
Programming Transact-SQL
The following is the syntax of the SELECT statement.
Syntax:
SELECT { @local_variable { = | += | -= | *= | /= | %= | &= | ^= | |= } expression } [ ,...n ] [ ; ]
where,
@local_variable: specifies the local variable to which a value will be assigned.
=: Assigns the value on the right-hand side to the variable on the left-hand side.
{= | += | -= | *= | /= | %= | &= | ^= | |= }: specifies the compound assignment operators.
expression: specifies any valid expression which can even include a scalar subquery.
Code Snippet 5 shows how to use SELECT to return a single value.
Code Snippet 5:
USE AdventureWorks2012 ;
GO
DECLARE @var1 nvarchar(30);
SELECT @var1 = 'Unnamed Company';
SELECT @var1 = Name
FROM Sales.Store
WHERE BusinessEntityID = 10;
SELECT @var1 AS 'Company Name';
In this code snippet, the variable @var1 is assigned Unnamed Company as its value.
The query against the Store table will return zero rows as the value specified for the
BusinessEntityID does not exist in the table. The variable will then, retain the Unnamed
Company value and will be displayed with the heading Company Name. Figure 13.2 displays the
output.
0 of 45
13.3 Synonyms
Synonyms are database objects that serve the following purposes:
→
They offer another name for a different database object, also called as the base object, which
may exist on a remote or local server.
→
They present a layer of abstraction that guards a client application from the modifications made
to the location and the name of the base object.
For example, consider that the Department table of AdventureWorks2012 is located on the first
server named Server1. To reference this table from the second server, Server2, a client
application would have to use the four-part name
Server1.AdventureWorks2012.Person.Department. If the location of the table was modified, for
example, to another server, the client application would have to be rectified to reflect that
change. To address both these issues, users can create a synonym, DeptEmpTable, on Server2 for
the Department table on Server1. Now, the client application only has to use the single name,
DeptEmpTable, to refer to the Employee table.
Similarly, if the location of the Department table changes, users have to modify the synonym,
DeptEmpTable, to point to the new location of the Department table. Since there is no ALTER
SYNONYM statement, you first have to drop the synonym, DeptEmpTable, and then, re-create
the synonym with the same name, but point the synonym to the new location of Department.
Note - A synonym is a part of schema, and similar to other schema objects, the synonym name
must be unique.
Table 13.1 lists the database objects for which the users can create synonyms.
Database Objects Extended stored procedure SQL table-valued function SQL stored
procedure
Session
1
Programming Transact-SQL
V 1.0 © Aptech Limited
1 of 45
1 Session
Programming Transact-SQL
Database Objects Table(User-defined) Replication-filter-procedure SQL scalar
function SQL inline-tabled-valued function View
Table 1.1: Database Objects
→
Synonyms and Schemas
Suppose users want to create a synonym and have a default schema that is not owned by them. In
such a case, they can qualify the synonym name with the schema name that they actually own.
Consider for example that a user owns a schema Resources, but Materials is the user's default
schema. If this user wants to create a synonym, he/she must prefix the name of the synonym with
the schema Resources.
→
Granting Permissions on Synonyms
Only members of the roles db_owner or db_ddladmin or synonym owners are allowed to grant
permissions on a synonym. Users can deny, grant, or revoke all or any of the permissions on a
synonym. Table 13.2 displays the list of permissions that are applied on a synonym.
Permissions DELETE INSERT TAKE OWNERSHIP VIEW DEFINITION CONTROL
EXECUTE SELECT UPDATE
Table 1.: Permissions
→
Working with Synonyms
Users can work with synonyms in SQL Server 2012 using either Transact-SQL or SSMS.
To create a synonym using SSMS, perform the following steps:
1.
In Object Explorer, expand the database where you want to create a new synonym.
of 45
1
Programming Transact-SQL
Select the Synonyms folder, right-click it and then, click New Synonym... as shown in figure
13.3.
V 1.0 © Aptech Limited
Figure 1.: Creating a New Synonym
of 45
Session
4 of 45
3.
In the New Synonym dialog box, provide the information as shown in figure 13.4.
Figure 1.4: Adding Details in the New Synonym Dialog Box
where,
Synonym name: is the new name for the object. Here, Emp is the name.
Synonym schema: is the new name for the schema object. Here, the same schema name
HumanResources is used for the synonym and the object type.
Server name: is the name of the server to be connected. Here, the server name is specified as
10.2.110.140.
Database name: is the database name to connect the object. Here, AdventureWorks2012 is the
database name.
Schema: is the schema that owns the object.
1
Programming Transact-SQL
V 1.0 © Aptech Limited
1 Session
Programming Transact-SQL
Object type and Object name: is the object type and name respectively. Here, the object type
selected is view and the object name that refers the synonym is vEmployeeDepartmentHistory.
To create a synonym using Transact-SQL, perform the following steps:
1.
Connect to the Database Engine.
2.
Click New Query in the Standard bar.
3.
Write the query to create the synonym in the query window.
The following is the syntax to create a synonym.
Syntax:
CREATE SYNONYM [ schema_name_1. ] synonym_name FOR <object>
<object> :: =
{
[ server_name.[ database_name ] . [ schema_name_2 ].| database_name . [ schema_name_2 ].|
schema_name_2. ] object_name
}
where,
schema_name_1: states that the schema in which the synonym is created.
synonym_name: specifies the new synonym name.
server_name: specifies the server name where the base object is located.
database_name: specifies the database name where the base object is located.
schema_name_2: specifies the schema name of the base object.
object_name: specifies the base object name, which is referenced by the synonym.
Code Snippet 6 creates a synonym from an existing table.
Code Snippet 6:
USE tempdb;
GO
CREATE SYNONYM MyAddressType
FOR AdventureWorks2012.Person.AddressType;
GO
In this code snippet, a synonym is created from an existing table present in the
AdventureWorks2012 database.
V 1.0 © Aptech Limited
5 of 45
1 Session
Programming Transact-SQL
4.
Click Execute on the toolbar to complete creation of the synonym.
1
Programming Transact-SQL
where,
Boolean_expression: specifies the expression that returns TRUE or FALSE value.
{ sql_statement| statement_block }: Is any Transact-SQL statement or statement grouping that is
defined by using a statement block. If a statement block is not used, the IF or ELSE condition
can affect the performance of only one Transact-SQL statement. In order to define the statement
block, the BEGIN and END keywords are used.
Code Snippet 8 shows the use of IF...ELSE statements.
Code Snippet 8:
USE AdventureWorks2012
GO
DECLARE @ListPrice money;
SET @ListPrice = (SELECT MAX(p.ListPrice)
FROM Production.Product AS p
JOIN Production.ProductSubcategory AS s
ON p.ProductSubcategoryID = s.ProductSubcategoryID
WHERE s.[Name] = 'Mountain Bikes');
PRINT @ListPrice
IF @ListPrice <3000
PRINT 'All the products in this category can be purchased for an amount less than 3000'
ELSE
PRINT 'The prices for some products in this category exceed 3000'
In this code snippet, the IF...ELSE statement is used to form a conditional statement. First, a
variable @ListPrice is defined and a query is created to return the maximum list price of the
product category Mountain Bikes. Then, this price is compared with a value of 3000 to
determine if products can be purchased for an amount less than 3000. If yes, an appropriate
message is printed using the first PRINT statement. If not, then the second PRINT statement
executes.
WHILE
The WHILE statement specifies a condition for the repetitive execution of the statement block.
The statements are executed repetitively as long as the specified condition is true. The execution
of statements in the WHILE loop can be controlled by using the BREAK and CONTINUE
keywords.
V 1.0 © Aptech Limited
1 Session
Programming Transact-SQL
The following is the syntax for the WHILE statement.
Syntax:
WHILE Boolean_expression
{ sql_statement | statement_block | BREAK | CONTINUE }
where,
Boolean_expression: specifies the expression that returns TRUE or FALSE values.
{sql_statement | statement_block}: Is any Transact-SQL statement that defines the statement
block.
BREAK: Results in an exit from the innermost WHILE loop. Every statement that appears after
the END keyword, that marks the end of the loop, is executed.
CONTINUE: Results in the WHILE loop being restarted. The statements after the CONTINUE
keyword within the body of the loop are not executed.
Code Snippet 9 shows the use of WHILE statement.
Code Snippet 9:
DECLARE @flag int
SET @flag = 10
WHILE (@flag <=95)
BEGIN
IF @flag%2 =0
PRINT @flag
SET @flag = @flag + 1
CONTINUE;
END
GO
Using this code snippet, all the even numbers beginning from 10 until 95 are displayed. This is
achieved using a WHILE loop along with an IF statement.
Similarly, a WHILE loop can also be used with queries and other Transact-SQL statements.
V 1.0 © Aptech Limited
of 45
1 Session
Programming Transact-SQL
→
→
1
Programming Transact-SQL
Therefore, the user-defined functions that create side effects on the database are not
recommended.
Scalar-Valued Functions
A Scalar-Valued Function (SVF) always returns an int, bit, or string value. The data type
returned from and the input parameters of SVF can be of any data type except text, ntext, image,
cursor, and timestamp.
An inline scalar function has a single statement and no function body. A multi-statement scalar
function encloses the function body in a BEGIN...END block.
Table-Valued Functions
Table-valued functions are user-defined functions that return a table. Similar to an inline scalar
function, an inline table-valued function has a single statement and no function body.
Code Snippet 10 shows the creation of a table-valued function.
Code Snippet 10:
USE AdventureWorks2012;
GO
IF OBJECT_ID (N'Sales.ufn_CustDates', N'IF') IS NOT NULL
DROP FUNCTION Sales.ufn_ufn_CustDates;
GO
CREATE FUNCTION Sales.ufn_CustDates ()
RETURNS TABLE
AS
RETURN
(
SELECT A.CustomerID, B.DueDate, B.ShipDate
FROM Sales.Customer A
LEFT OUTER JOIN
Sales.SalesOrderHeader B
ON
A.CustomerID = B.CustomerID AND YEAR(B.DueDate)<2012
);
Here, an inline table-valued function defines a leftouter join between the tables Sales.Customer
and Sales.SalesOrderHeader.
V 1.0 © Aptech Limited
The tables are joined based on customer ids. In this case, all records from the left table and only
matching records from the right table are returned. The resultant table is then returned from the
table-valued function.
The function is invoked as shown in Code Snippet 11.
Code Snippet 11:
SELECT * FROM Sales.ufn_CustDates();
The result will be the outcome of the join represented in a tabular format.
Session
1
Programming Transact-SQL
V 1.0 © Aptech Limited
of 45
1 Session
Programming Transact-SQL
4.
Right-click the function to be modified and then, select Modify. The code for the function
appears in a query editor window.
5.
In the query editor window, make the required changes to the ALTER FUNCTION statement
body.
6.
Click Execute on the toolbar to execute the ALTER FUNCTION statement.
→
Modifying a User-defined function using Transact-SQL
To modify the user-defined function using Transact-SQL, perform the following steps:
•
In the Object Explorer, connect to the Database Engine instance.
•
On the Standard bar, click New Query.
•
Type the ALTER FUNCTION code in the Query Editor.
•
Click Execute on the toolbar to execute the ALTER FUNCTION statement.
Code Snippet 12 demonstrates modifying a table-valued function.
Code Snippet 12:
USE [AdventureWorks2012]
GO
ALTER FUNCTION [dbo].[ufnGetAccountingEndDate]()
RETURNS [datetime]
AS
BEGIN
RETURN DATEADD(millisecond, -2, CONVERT(datetime, '20040701', 112));
END;
13.7 Creafion of Windows with OVER
A window function is a function that applies to a collection of rows. The word 'window' is used
to refer to the collection of rows that the function works on.
In Transact-SQL, the OVER clause is used to define a window within a query resultset. Using
windows and the OVER clause with functions provides several advantages. For instance, they
help to calculate aggregated values. They also enable row numbers in a resultset to be generated
easily.
4 of 45
Session
1
Programming Transact-SQL
Figure 1.5: Partitioning
V 1.0 © Aptech Limited
5 of 45
Session
of 45
1
Programming Transact-SQL
Ordering
The ordering element defines the ordering for calculation in the partition. In a standard SQL
ordering element all functions are supported. Earlier, SQL Server had no support for the ordering
elements with aggregate functions as it only supported partitioning. In SQL Server 2012, there is
a support for the ordering element with aggregate functions. The ordering element has different
meaning to some extent for different function categories. With ranking functions, ordering is
spontaneous.
Code Snippet 14 demonstrates an example of the ordering element.
Code Snippet 14:
SELECT CustomerID, StoreID,
RANK() OVER(ORDER BY StoreID DESC) AS Rnk_All,
RANK() OVER(PARTITION BY PersonID
ORDER BY CustomerID DESC) AS Rnk_Cust
FROM Sales.Customer;
This code snippet makes use of the RANK() function which returns the rank of each row in the
partition of a resultset. The rank of a row is determined by adding 1 to the number of ranks that
come before the specified row. For example, while using descending ordering, the RANK()
function returns one more than the number of rows in the respective partition that has a greater
ordering value than the specified one.
Figure 13.6 displays the output of Code Snippet 14.
Figure 1.: Ordering
Code Snippet 15 displays a query with two RANK calculations and the ORDER BY clause.
Code Snippet 15:
SELECT TerritoryID, Name, SalesYTD,
V 1.0 © Aptech Limited
→
Session
RANK() OVER(ORDER BY SalesYTD DESC) AS Rnk_One,
RANK() OVER(PARTITION BY TerritoryID
ORDER BY SalesYTD DESC) AS Rnk_Two
FROM Sales.SalesTerritory;
This code snippet makes use of the RANK() function which returns the rank of each row in the
partition of a resultset. In general, the rank of a row is determined by adding 1 to the number of
ranks that come before the specified row. Here in this code, the first RANK() function generates
the attribute Rnk_One that depends on the default partitioning, and the second RANK function
generates Rnk_Two that uses explicit partitioning by TerritoryID.
Figure 13.7 displays the partitions defined for a sample of three results of calculations in the
query: one Rnk_One value and two Rnk_Two value.
Figure 1.: Partitioning and Ranking
Framing
Framing is a feature that enables you to specify a further division of rows within a window
partition. This is done by assigning upper and lower boundaries for the window frame that
presents rows to the window function. In simple terms, a frame is similar to a moving window
over the data that starts and ends at specified positions. Window frames can be defined using the
ROW or RANGE subclauses and providing starting and ending boundaries.
Code Snippet 16 displays a query against the ProductInventory, calculating the running total
quantity for each product and location.
Code Snippet 16:
SELECT ProductID, Shelf, Quantity,
SUM(Quantity) OVER(PARTITION BY ProductID
1
Programming Transact-SQL
V 1.0 © Aptech Limited
of 45
1 Session
Programming Transact-SQL
ORDER BY LocationID
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW) AS RunQty
FROM Production.ProductInventory;
In this code snippet, the window function applies the SUM aggregate to the attribute Quantity,
partitions the window by ProductID, orders the partition rows by LocationID, and frames the
partition rows depending on the given ordering between unbounded preceding (no low boundary
point) and the current row. In other words, the result will be the sum of all prior rows in the
frame, including the current row. Figure 13.8 displays the output of Code Snippet 16.
Figure 1.: Framing
1
Programming Transact-SQL
Figure 1.: Ranking Functions
OFFSET functions
The different types of offset functions are as follows:
SWITCHOFFSET
This function returns a DATETIMEOFFSET value that is modified from the stored time zone
offset to a specific new time zone offset.
The following is the syntax for the SWITCHOFFSET function.
Syntax:
SWITCHOFFSET ( DATETIMEOFFSET, time_zone )
where,
DATETIMEOFFSET: is an expression that is resolved to a datetimeoffset(n) value. time_zone:
specifies the character string in the format [+|-]TZH:TZM or a signed integer (of minutes) which
represents the time zone offset, and is assumed to be daylight-saving aware and adjusted.
Code Snippet 18 displays the use of SWITCHOFFSET function.
Code Snippet 18:
CREATE TABLE Test
(
V 1.0 © Aptech Limited
1 Session
Programming Transact-SQL
ColDatetimeoffset datetimeoffset
);
GO
INSERT INTO Test
VALUES ('1998-09-20 7:45:50.71345 -5:00');
GO
SELECT SWITCHOFFSET (ColDatetimeoffset, '-08:00')
FROM Test;
GO
--Returns: 1998-09-20 04:45:50.7134500 -08:00
SELECT ColDatetimeoffset
FROM Test;
Figure 13.10 displays the output of Code Snippet 18.
Figure 1.10: Use of SWITCHOFFSET Function
→
DATETIMEOFFSETFROMPARTS
This function returns a datetimeoffset value for the specified date and time with specified
precision and offset.
V 1.0 © Aptech Limited
1 of 45
1 Session
Programming Transact-SQL
The following is the syntax for DATETIMEOFFSETFROMPARTS.
Syntax:
DATETIMEOFFSETFROMPARTS ( year, month, day, hour,
minute, seconds, fractions, hour_offset,
minute_offset, precision )
where,
year: specifies the integer expression for a year. month: specifies the integer expression for a
month. day: specifies the integer expression for a day. hour: specifies the integer expression for
an hour. minute: specifies the integer expression for a minute. seconds: specifies the integer
expression for a day. fractions: specifies the integer expression for fractions. hour_offset:
specifies the integer expression for the hour portion of the time zone offset. minute_offset:
specifies the integer expression for the minute portion of the time zone offset. precision:
specifies the integer literal precision of the datetimeoffset value to be returned.
Code Snippet 19 displays the use of DATETIMEOFFSETFROMPARTS function. Code Snippet
19:
SELECT DATETIMEOFFSETFROMPARTS ( 2010, 12, 31, 14, 23, 23, 0, 12, 0,
7)
AS Result;
The code displays a datetimeoffset value for the given date and time with the specified precision
and offset. Figure 13.11 displays the output of Code Snippet 19.
Figure 1.11: Use of DATETIMEOFFSETFROMPARTS Function
of 45
Session
SYSDATETIMEOFFSET
These functions returns datetimeoffset(7) value which contains the date and time of the computer
on which the instance of SQL Server is running.
The following is the syntax for SYSDATETIMEOFFSET.
Syntax:
SYSDATETIMEOFFSET ()
Code Snippet 20 displays the different formats used by the date and time functions.
Code Snippet 20:
SELECT SYSDATETIME() AS SYSDATETIME
,SYSDATETIMEOFFSET() AS SYSDATETIMEOFFSET
,SYSUTCDATETIME() AS SYSUTCDATETIME
Figure 13.12 displays the use of SYSDATETIMEOFFSET function.
Figure 1.1: Use of SYSDATETIMEOFFSET Function
Analytic Functions
SQL Server 2012 supports several analytic functions. These functions compute aggregate value
based on a group of rows. Analytic functions compute running totals, moving averages, or top-N
results within a group.
Table 13.7 lists some of the analytic functions.
Function Description
LEAD Provides access to data from a subsequent row in the same
resultset without using a self-join. LAST_VALUE Retrieves the last
value in an ordered set of values. LAG Provides access to data from a previous row in the same
resultset without using a self-join. FIRST_VALUE Retrieves the first
value in an ordered set of values. CUME_DIST Computes the cumulative distribution of a value
in a group of
values. PERCENTILE_ CONT Computes a percentile based on a continuous distribution of the
column value in SQL.
1
Programming Transact-SQL
V 1.0 © Aptech Limited
of 45
1 Session
Programming Transact-SQL
Function Description PERCENTILE_DISC Calculates a particular percentile for sorted
values in an entire
rowset or within distinct partitions of a rowset.
Table 1.: Analytic Functions
Code Snippet 21 demonstrates the use of LEAD() function.
Code Snippet 21:
USE AdventureWorks2012;
GO
SELECT BusinessEntityID, YEAR(QuotaDate) AS QuotaYear, SalesQuota AS NewQuota,
LEAD(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS FutureQuota
FROM Sales.SalesPersonQuotaHistory
WHERE BusinessEntityID = 275 and YEAR(QuotaDate) IN ('2007','2008');
In this code snippet, the LEAD() function is used to return the difference in the sales quotas for a
particular employee over the subsequent years.
Code Snippet 22 demonstrates the use of FIRST_VALUE() function.
Code Snippet 22:
USE AdventureWorks2012;
GO
SELECT Name, ListPrice,
FIRST_VALUE(Name) OVER (ORDER BY ListPrice ASC) AS LessExpensive
FROM Production.Product
WHERE ProductSubcategoryID = 37
In this code snippet, the FIRST_VALUE() function compares products in the product category
37 and returns the product name that is less expensive.
4 of 45
Session
1
Programming Transact-SQL
V 1.0 © Aptech Limited
5 of 45
Session
of 45
4.
1
Programming Transact-SQL
Which of the following code uses a local variable to retrieve contact information for the last
names starting with Per?
(A)
V 1.0 © Aptech Limited USE AdventureWorks2012;
GO
DECLARE @find varchar(30);
DECLARE @find varchar(30) = 'Per%';
SET @find = 'Per%';
SELECT p.LastName, p.FirstName, ph.PhoneNumber
FROM Person.Customer AS p
JOIN Person.Phone AS ph ON p.BusinessEntityID = ph.BusinessEntityID
WHERE LastName LIKE @find;
(B)
USE AdventureWorks2012;
GO
DECLARE find varchar(30);
DECLARE find varchar(30) = 'Per%';
SET find = 'Per%';
SELECT p.LastName, p.FirstName, ph.PhoneNumber
FROM Person.Customer AS p
JOIN Person.Phone AS ph ON p.BusinessEntityID = ph.BusinessEntityID
WHERE LastName LIKE find;
(C)
USE AdventureWorks2012;
GO
@find varchar(30);
@find varchar(30) = 'Per%';
SET @find = 'Per%';
SELECT p.LastName, p.FirstName, ph.PhoneNumber
FROM Person.Customer AS p
JOIN Person.Phone AS ph ON p.BusinessEntityID = ph.BusinessEntityID
WHERE LastName LIKE @find;
1 Session
Programming Transact-SQL
USE AdventureWorks2012;
GO
SET @find varchar(30);
SET @find varchar(30) = 'Per%';
(D)
SET @find = 'Per';
SELECT p.LastName, p.FirstName, ph.PhoneNumber
FROM Person.Customer AS p
JOIN Person.Phone AS ph ON p.BusinessEntityID = ph.BusinessEntityID
WHERE LastName LIKE @find;
5.
Which of the following is not a non-deterministic function?
(A) @@PACK_SENT (C) @@DBTS
(B) @@IOBUSY (D) IDLE
V 1.0 © Aptech Limited
of 45
1 Session
Programming Transact-SQL
13.9.1 Answers
1. A
2. C
3. A
4. A
5. D
of 45
Summary
→
A batch is a collection of one or more Transact-SQL statements that are sent as one unit from an
application to the server.
→
Variables allow users to store data for using as input in other Transact-SQL statements.
→
Synonyms provide a way to have an alias for a database object that may exist on a remote or
local server.
→
Deterministic functions each time return the same result every time they are called with a
definite set of input values and specify the same state of the database.
→
Non-deterministic functions return different results every time they are called with specified set
of input values even though the database that is accessed remains the same.
→
1
Programming Transact-SQL
1.
Zen Technologies is a leading company in textiles located in California. The management of the
company wants to give a loyalty award to all employees completing tenure of five years in the
organization. Using the same Employee table, create a Transact-SQL batch to return
EmployeeID, FirstName, Department, and HireDate of all such employees. Assume that the
management gives a twenty five percent salary increment to everybody completing one year in
the organization. The chairman of the organization wants to participate in a national salary
survey.
Write a batch to determine the total salary paid to a department which employs more than one
employee. The management wants to find out which department has hired the largest number of
employees in the last five years. Hints:
→
Use the DATETIMEOFFSETFROMPARTS function.
V 1.0 © Aptech Limited
Try It Yourself
400 of 45
14 Session -
Welcome to the Session, Transactions.
This session explains the types of transactions and the procedure to implement
these transactions. It also describes the process to control and mark a transaction,
and lists the differences between the implicit and explicit transactions. It also
further explains the isolation levels, scope, different types of locks, and transaction
management.
In this Session, you will learn to:
→
Define and describe transactions
→
Explain the procedure to implement transactions
→
Explain the process of controlling transactions
→
Explain the steps to mark a transaction
→
Distinguish between implicit and explicit transactions
→
Explain isolation levels
→
Explain the scope and different types of locks
→
Explain transaction management
Transactions
14 Session
Transactions
14.1 Introducfion
A transaction is a single unit of work. A transaction is successful only when all data
modifications that are made in a transaction are committed and are saved in the database
permanently. If the transaction is rolled back or cancelled, then it means that the transaction has
encountered errors and there are no changes made to the contents of the database. Hence, a
transaction can be either committed or rolled back.
Session
14
Transactions
V 1.0 © Aptech Limited
40 of 45
Session
404 of 45
14
Transactions
The following is the syntax for the BEGIN TRANSACTION statement.
Syntax:
BEGIN { TRAN | TRANSACTION }
[ { transaction_name | @tran_name_variable }
[ WITH MARK [ 'description' ] ] ] [ ; ]
where,
transaction_name: specifies the name that is assigned to the transaction. It should follow the
rules for identifiers and limit the identifiers that are 32 characters long.
@tran_name_variable: specifies the name of a user-defined variable that contains a valid
transaction name.
WITH MARK['description']: specifies the transaction that is marked in the log. The description
string defines the mark.
Code Snippet 1 shows how to create and begin a transaction. Code Snippet 1:
USE AdventureWorks2012; GO DECLARE @TranName VARCHAR(30); SELECT @TranName =
'FirstTransaction'; BEGIN TRANSACTION @TranName; DELETE FROM
HumanResources.JobCandidate
WHERE JobCandidateID = 13;
In this code snippet, a transaction name is declared using a variable with value FirstTransaction.
A new transaction with this name is then created having a DELETE statement. As the transaction
comprises a single-line statement, it is implicitly committed.
COMMIT TRANSACTION
The COMMIT TRANSACTION statement marks an end of a successful implicit or explicit
transaction. If the @@TRANCOUNT is 1, then, COMMIT TRANSACTION performs all data
modifications performed on the database and becomes a permanent part of the database. Further,
it releases the resources held by the transaction and decrements @@TRANCOUNT by 0. If
@@TRANCOUNT is greater than 1, then the COMMIT TRANSACTION decrements the
@@TRANCOUNT by 1 and keeps the transaction in active state.
V 1.0 © Aptech Limited
14 Session
Transactions
The following is the syntax for the COMMIT TRANSACTION statement.
Syntax:
COMMIT { TRAN | TRANSACTION } [ transaction_name | @tran_name_variable ] ] [ ; ]
where,
transaction_name: specifies the name that is assigned by the previous BEGIN TRANSACTION
statement. It should follow the rules for identifiers and do not allow identifiers that are 32
characters long.
@tran_name_variable: specifies the name of a user-defined variable that contains a valid
transaction name. The variable can be declared as char, varchar, nchar, or nvarchar data type. If
more than 32 characters are passed to the variable, then only 32 characters are used and the
remaining characters will be truncated.
Code Snippet 2 shows how to commit a transaction in the HumanResources.JobCandidate table
of AdventureWorks2012 database. Code Snippet 2:
BEGIN TRANSACTION; GO DELETE FROM HumanResources.JobCandidate WHERE
JobCandidateID = 11; GO COMMIT TRANSACTION; GO
This code snippet defines a transaction that will delete a job candidate record having
JobCandidateID as 11.
→
COMMIT WORK
The COMMIT WORK statement marks the end of a transaction.
The following is the syntax for the COMMIT WORK statement.
Syntax:
COMMIT [ WORK ] [ ; ]
COMMIT TRANSACTION and COMMIT WORK are identical except for the fact that
COMMIT TRANSACTION accepts a user-defined transaction name.
V 1.0 © Aptech Limited
405 of 45
Session
40 of 45
→
→
14
Transactions
Marking a Transaction
Code Snippet 3 shows how to mark a transaction in the HumanResources.JobCandidate table of
AdventureWorks2012 database. Code Snippet 3:
BEGIN TRANSACTION DeleteCandidate
WITH MARK N'Deleting a Job Candidate'; GO DELETE WHERE FROM JobCandidateID
HumanResources.JobCandidate
= 11; GO COMMIT TRANSACTION DeleteCandidate;
In this code snippet, a transaction named DeleteCandidate is created and marked in the log.
ROLLBACK TRANSACTION
This transaction rolls back or cancels an implicit or explicit transaction to the starting point of the
transaction, or to a savepoint in a transaction. A savepoint is a mechanism to roll back some parts
of transactions. The ROLLBACK TRANSACTION is used to delete all data modifications made
from the beginning of the transaction or to a savepoint. It also releases the resources held by the
transaction.
The following is the syntax for the ROLLBACK TRANSACTION statement.
Syntax:
ROLLBACK { TRAN | TRANSACTION }
[ transaction_name | @tran_name_variable | savepoint_name | @savepoint_variable ] [ ; ]
where,
transaction_name: statement. It should confirm specifies the the rules name for identifiers that is
assigned and do not to allow the BEGIN identifiers TRANSACTION that are 32 characters long.
@tran_name_variable: transaction data type.
specifies the name of a user-defined variable that contains a valid name. The
variable can be declared as char, varchar, nchar, or nvarchar
savepoint_name: Use savepoint_name specifies only when the savepoint_name a conditional roll
back from affects a SAVE a TRANSACTION part of a transaction.
statement.
@savepoint_variable: savepoint data type.
name. The variable specifies can be the declared name of as savepoint char, varchar, variable
nchar, that contain or nvarchar a valid
V 1.0 © Aptech Limited
14 Session
Transactions
Consider an example that demonstrates the use of ROLLBACK. Assume that a database named
Sterling has been created. A table named ValueTable is created in this database as shown in
Code Snippet 4. Code Snippet 4:
USE Sterling; GO CREATE TABLE ValueTable ([value] char) GO Code Snippet 5 creates a
transaction that inserts two records into ValueTable. Then, it rolls back is used the to transaction
query the and table, again you inserts will see one that record only a into single ValueTable.
record with value When C a is SELECT displayed. statement This is because the earlier INSERT
operations have been rolled back or cancelled. Code Snippet 5:
BEGIN TRANSACTION
INSERT INTO ValueTable VALUES('A'); INSERT INTO ValueTable VALUES('B'); GO ROLLBACK
TRANSACTION INSERT INTO ValueTable VALUES('C'); SELECT [value] FROM ValueTable;
→
ROLLBACK WORK
This statement rolls back a user-specified transaction to the beginning of the transaction.
The following is the syntax for the ROLLBACK WORK statement.
Syntax:
ROLLBACK [ WORK ] [ ; ]
The keyword WORK is optional and is rarely used.
V 1.0 © Aptech Limited
40 of 45
Session
40 of 45
14
Transactions
Figure 14.1 displays the working of transactions.
Figure 14.1: Working of Transactions
SAVE TRANSACTION
The SAVE TRANSACTION statement sets a savepoint within a transaction. The following is
the syntax for the SAVE TRANSACTION statement.
Syntax:
SAVE { TRAN | TRANSACTION } { savepoint_name | @savepoint_variable } [ ; ]
where,
savepoint_name: specifies the savepoint_name assigned. These names conform to the rules of
identifiers and are restricted to 32 characters.
@savepoint_variable: specifies the name of a user-defined variable that contain a valid savepoint
name. The variable can be declared as char, varchar, nchar, or nvarchar data type. More than 32
characters are allowed to pass to the variables but only the first 32 characters are used.
V 1.0 © Aptech Limited
Code Snippet 6 shows how to use a savepoint transaction. Code Snippet 6:
CREATE PROCEDURE SaveTranExample
@InputCandidateID INT AS
DECLARE @TranCounter INT; SET @TranCounter = @@TRANCOUNT; IF @TranCounter > 0
SAVE TRANSACTION ProcedureSave; ELSE
BEGIN TRANSACTION; DELETE HumanResources.JobCandidate
WHERE JobCandidateID = @InputCandidateID; IF @TranCounter = 0 COMMIT
TRANSACTION;
IF @TranCounter = 1 ROLLBACK TRANSACTION ProcedureSave; GO
In this code snippet, a savepoint transaction is created within a stored procedure. This will then
be used to roll back only the changes made by the stored procedure if an active transaction has
started before the stored procedure executes.
14.4 @@TRANCOUNT
The @@TRANCOUNT system function returns a number of BEGIN TRANSACTION
statements that occur in the current connection. Figure 14.2 displays an example of using
@@TRANCOUNT.
Figure 14.: @@TRANCOUNT
The following is the syntax for the @@TRANCOUNT statement.
Syntax:
@@TRANCOUNT
Session
14
Transactions
V 1.0 © Aptech Limited
40 of 45
14 Session
Transactions
Code Snippet 7 shows the effect that nested BEGIN and COMMIT statements have on the
@@TRANCOUNT variable. Code Snippet 7:
PRINT @@TRANCOUNT BEGIN TRAN
PRINT @@TRANCOUNT BEGIN TRAN
PRINT @@TRANCOUNT COMMIT PRINT @@TRANCOUNT COMMIT PRINT
@@TRANCOUNT This code snippet displays the number of times the BEGIN TRAN and
COMMIT statement execute in the current connection.
Figure 14.3 displays the output of Code Snippet 7.
Figure 14.: Output of Code Snippet Code Snippet 8 shows the
effect that nested BEGIN and ROLLBACK statements have on the @@TRANCOUNT variable.
Code Snippet 8:
PRINT @@TRANCOUNT BEGIN TRAN
PRINT @@TRANCOUNT BEGIN TRAN
PRINT @@TRANCOUNT ROLLBACK PRINT @@TRANCOUNT In this case,
the code snippet displays the number of times the BEGIN and ROLLBACK statements execute
in the current connection.
410 of 45
Session
14
Transactions
V 1.0 © Aptech Limited
411 of 45
14 Session
Transactions
For creating a marked transaction in a set of databases, the following steps are required:
1.
Name the transaction in the BEGIN TRAN statement and use the WITH MARK clause.
2.
Execute an update against all of the databases in the set. Code Snippet 9 shows to update
the ListPrice in the Product table of the AdventureWorks2012 database. Code Snippet 9:
USE AdventureWorks2012 GO BEGIN TRANSACTION ListPriceUpdate
WITH MARK 'UPDATE Product list prices'; GO
UPDATE Production.Product
SET ListPrice = ListPrice * 1.20 WHERE ProductNumber LIKE 'BK-%'; GO
COMMIT TRANSACTION ListPriceUpdate; GO
Code Snippet 10 shows how to restore a transaction log. It assumes that a backup named
AdventureWorksBackups has been created. Code Snippet 10:
USE AdventureWorks2012 GO BEGIN TRANSACTION ListPriceUpdate
WITH MARK 'UPDATE Product list prices'; GO
UPDATE Production.Product
SET ListPrice = ListPrice * 1.20 WHERE ProductNumber LIKE 'BK-%'; GO
COMMIT TRANSACTION ListPriceUpdate; GO
41 of 45
Session
14
Transactions
V 1.0 © Aptech Limited
41 of 45
14 Session
Transactions
Selecting a suitable isolation level is based on the data integrity requirements of the application
as compared to the overheads of each isolation level. The higher isolation level, serializable,
assures that a transaction will recover the same data each time it repeats the read operation. Then,
it does this by performing a level of locking that is expected to influence other users in a multi-
user system. The lower isolation level, read uncommitted, retrieves data that is modified, and is
not committed by other transactions. All concurrency side effects occur in read uncommitted,
however, there is no read versioning or locking, hence, the overhead is minimized.
Table 14.2 lists the concurrency effects that are allowed by the different isolation levels.
Isolation Level Dirty Read NonRepeatable Read Read committed No Yes Read
uncommitted Yes No Snapshot No No Repeatable Read No No Serializable No No
Table 14.: Isolation Levels
Transactions need to execute at an isolation level of at least repeatable read that prevents lost
updates occurring when two transactions each retrieve the same row, and then updates the row
that is dependent on the originally retrieved rows.
Session
14
Transactions
V 1.0 © Aptech Limited
41 of 45
14 Session
Transactions
Transaction log is a critical component of the database and if a system failure occurs, the
transaction log will be required to bring the database to a consistent data. The transaction log
should not be moved or deleted until users understand the consequences of doing it. The
operations supported by the transaction log are as follows:
•
Individual transactions recovery
•
Incomplete transactions recovery when SQL Server starts
•
Transactional replication support
•
Disaster recovery solutions and high availability support
•
Roll back a file, restored database, filegroup, or page forward to the point of failure
→
Truncating a Transaction Log
Truncating a log frees the space in the log file for reusing the transaction log. Truncation of logs
starts automatically after the following events:
•
In a simple recovery model after the checkpoint.
•
In a bulk-logged recovery model or full recovery model, if the checkpoint is occurred ever since
the last backup, truncation occurs after a log backup.
There are factors that delay a log truncation. When the log records remain active for a long time,
transaction log truncation is late and the transaction log fills up. Log truncations are delayed due
to many reasons. Users can also discover if anything prevents the log truncation by querying the
log_reuse_wait_desc and log_reuse_wait columns of the sys.databases catalog view.
Table 14.5 lists the values of some of these columns.
Log_reuse_wait value
Log_reuse_wait desc
Description mode
value 0 NOTHING Specifies that at present, there
are more than one reusable virtual log file. 1 CHECKPOINT Specifies that there is no
checkpoint occurred since the last log truncation, or the head of the log has not moved beyond a
virtual log file. 2 LOG_BACKUP Specifies a log backup that is
required before the transaction log truncates. 3 ACTIVE_BACKUP_OR_RESTORE Specifies
that the data backup or
a restore is in progress.
41 of 45
14.11.1 Answers
1. D
2. B
3. C
4. D
5. B
4 of 45
Summary
→
ROLLBACK with an optional keyword WORK rolls back a user-specified transaction to the
beginning of the transaction.
→
Isolation levels are provided by the transaction to describe the extent to which a single
transaction needs to be isolated from changes made by other transactions.
→
The SQL Server Database Engine locks the resources using different lock modes, which
determine the resources that are accessible to concurrent transactions.
V 1.0 © Aptech Limited
4 of 45
Session
14
Transactions
1.
Zamora Electronics Ltd. employs more than 500 workers in its units. Some of these are at junior
level while some are at senior level depending upon their expertise and years of experience. Each
employee is given annual leave based on the designation. The management at Zamora
Electronics Ltd. is planning to computerize their human resources department and all the data
pertaining to employees will now be stored in an SQL Server 2012 database. The company has
made some changes in the leave policy of the employees and wants to update the same in their
tables. Assume that you are the database administrator and that you are assigned the following
tasks:
•
Create a transaction to update the records in the table as per the new leave policy.
•
Check if the transactions are updated in the appropriate table.
•
Check if the transactions are not updated. Then, ensure that they are rolled back with the
appropriate error messages.
Table 14.6 lists the EmployeeDetails table.
Field Name Data Type Key Field Description Employee_Id varchar(5) Primary Key Stores
employee identification number FirstName varchar(30) Stores first name of the employee
LastName varchar(30) Stores last name of the employee Address varchar(60) Stores address of
the employee PhoneNumber varchar(20) Phone number of the employee, it
could be landline or mobile
Department_Id varchar(4) Stores department id of the
department to which the employee belongs Designation varchar(30) Stores designation or job
role of the
employee Salary money Stores salary of
the employee Join_date datetime Stores date of joining for the employee Performance_Rating int
Stores rating of the employee
Table 14.: EmployeeDetails Table
V 1.0 © Aptech Limited
Try It Yourself
44 of 45
Welcome to the Session, Error Handling.
This session introduces error-handling techniques in SQL Server and describes the
use of TRY-CATCH blocks. Various system functions and statements that can
help display error information are also covered in the session.
At the end of this session, you will be able to:
→
Explain the various types of errors
→
Explain error handling and the implementation
→
Describe the TRY-CATCH block
→
Explain the procedure to display error information
→
Describe the @@ERROR and RAISERROR statements
→
Explain the use of ERROR_STATE, ERROR_SEVERITY, and ERROR_PROCEDURE
→
Explain the use of ERROR_NUMBER, ERROR_MESSAGE, and ERROR_LINE
→
Describe the THROW statement
Session -
Error Handling
15
15 Session
Error Handling
15.1 Introducfion
Error handling in SQL Server has become easy through a number of different techniques. SQL
Server has introduced options that can help you to handle errors efficiently. Often, it is not
possible to capture errors that occur at the user's end. SQL Server provides the TRY...CATCH
statement that helps to handle errors effectively at the back end. There are also a number of
system functions that print error related information, which can help fix errors easily.
Session
15
Error Handling
Figure 15.2 displays an example.
V 1.0 © Aptech Limited
427 of 452
15 Session
Error Handling
Figure 15.3 shows the divide by zero error.
Figure 15.: Divide by Zero Error
Here, the code editor will not show any error before execution because there is no syntax error.
•
Using a stored procedure, or a function, or a trigger that is unavailable
•
Trying to perform an action that an object or a variable cannot handle
•
Attempting to access or use computer memory that is insufficient
Figure 15.4 displays an example that tries to store a value in the variable that does not meet the
specified range. In such a case, an arithmetic overflow error occurs.
428 of 452
15.4 TRY...CATCH
TRY...CATCH statements are used to implement exception handling in Transact-SQL. One or
more Transact-SQL statements can be enclosed within a TRY block. If an error occurs in the
TRY block, the control is passed to the CATCH block that may contain one or more statements.
Session
15
Error Handling
V 1.0 © Aptech Limited
429 of 452
15 Session
Error Handling
Figure 15.5 illustrates the TRY...CATCH logic.
Figure 15.5: TRY...CATCH Logic
The following is the syntax for the TRY...CATCH statements.
Syntax:
BEGIN TRY
{ sql_statement | statement_block }
END TRY
BEGIN CATCH
[ { sql_statement | statement_block } ]
END CATCH
[;]
where,
sql_statement: specifies any Transact-SQL statement.
statement_block: specifies the group of Transact-SQL statements in a BEGIN...END block.
430 of 452
Session
15
Error Handling
V 1.0 © Aptech Limited
431 of 452
15 Session
Error Handling
The system functions are as follows:
→
ERROR _ NUMBER(): returns the number of error.
→
ERROR _ SEVERITY(): returns the severity.
→
ERROR _ STATE(): returns state number of the error.
→
ERROR _ PROCEDURE(): returns the name of the trigger or stored procedure where the error
occurred.
→
ERROR _ LINE(): returns the line number that caused the error.
→
ERROR _ MESSAGE(): returns the complete text of the error. The text contains the value
supplied for the parameters such as object names, length, or times.
The functions return NULL when they are called outside the scope of the CATCH block.
→
Using TRY...CATCH with error information
Code Snippet 2 demonstrates a simple example displaying error information.
Code Snippet 2:
USE AdventureWorks2012;
GO
BEGIN TRY
SELECT 217/0;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO
432 of 452
15
Error Handling
V 1.0 © Aptech Limited
433 of 452
Session
434 of 452
15
Error Handling
BEGIN TRY
SELECT 217/0;
END TRY
BEGIN CATCH
EXECUTE sp_ErrorInfo;
END CATCH;
In this code, when an error occurs, the CATCH block of the TRY...CATCH construct is called
and the error information is returned.
Using TRY...CATCH with Transaction
Code Snippet 4 demonstrates a TRY...CATCH block that works inside a transaction.
Code Snippet 4:
USE AdventureWorks2012;
GO
BEGIN TRANSACTION;
BEGIN TRY
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_SEVERITY() AS ErrorSeverity
,ERROR_NUMBER() AS ErrorNumber
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_STATE() AS ErrorState
,ERROR_MESSAGE() AS ErrorMessage
,ERROR_LINE() AS ErrorLine;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
V 1.0 © Aptech Limited
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
In this code, the TRY...CATCH block works within the transaction. The statement inside the
TRY block generates a constraint violation error as follows:
The DELETE statement is conflicted with the REFERENCE constraint
"FK_BillOfMaterials_Product_ProductAssemblyID". The conflict occurred in database
"AdventureWorks2012", table "Production.BillOfMaterials", column 'ProductAssemblyID'.
→
Uncommittable Transactions
If an error is generated in a TRY block, it causes the state of the current transaction to be invalid
and the transaction is considered as an uncommitted transaction. An uncommittable transaction
performs only ROLLBACK TRANSACTION or read operations. The transaction does not
execute any Transact-SQL statement that performs a COMMIT TRANSACTION or a write
operation.
The XACT_STATE function returns -1 if the transaction has been classified as an
uncommittable transaction. When a batch is completed, the Database Engine rolls back any
uncommittable transactions. If no error messages are sent when the transaction enters the
uncommittable state on completing the batch, then the error messages are sent to the client. This
specifies that an uncommittable transaction is detected and rolled back.
15.6 @@ERROR
The @@ERROR function returns the error number for the last Transact-SQL statement
executed.
The following is the syntax for the @@ERROR function.
Syntax:
@@ERROR
The @@ERROR system function returns a value of the integer type. This function returns 0, if
the previous Transact-SQL statement encountered no errors. It also returns an error number only
if the previous statements encounter an error. If an error is among the list of errors in the
sys.messages catalog view includes the value from the sys.messages.messages_id column for
that error. Users can view the text associated with an @@ERROR error number in the
sys.messages catalog view.
Session
15
Error Handling
V 1.0 © Aptech Limited
435 of 452
15 Session
Error Handling
Code Snippet 5 demonstrates how to use @@ERROR to check for a constraint violation.
Code Snippet 5:
USE AdventureWorks2012;
GO
BEGIN TRY
UPDATE HumanResources.EmployeePayHistory
SET PayFrequency = 4
WHERE BusinessEntityID = 1;
END TRY
BEGIN CATCH
IF @@ERROR = 547
PRINT N'Check constraint violation has occurred.';
END CATCH
In this code, @@ERROR is used to check for a check constraint violation (which has error
number 547) in an UPDATE statement.
It displays the following error message:
Check constraint violation has occurred.
15.7 RAISERROR
The RAISERROR statement starts the error processing for a session and displays an error
message. RAISERROR can reference a user-defined message stored in the sys.messages catalog
view or build dynamic error messages at run-time. The message is returned as a server error
message to the calling application or to the associated CATCH block of a TRY...CATCH
construct.
The following is the syntax for the RAISERROR statement.
Syntax:
RAISERROR ( { msg_id | msg_str | @local_variable }
{ ,severity ,state } [ ,argument [ ,...n ] ] ) [ WITH option [ ,...n ] ]
where,
msg_id: specifies the user-defined error message number that is stored in the sys.messages
catalog view using the sp_addmessage.
436 of 452
V 1.0 © Aptech Limited
msg_str: Specifies the user-defined messages with formatting. msg_str is a string of characters
with optional embedded conversion specifications. A conversion specification has the following
format:
% [[flag] [width] [. precision] [{h | l}]] type
The parameters that can be used in msg_str are as follows:
{h | l} type: Specifies the use of character types d, i, o, s, x, X, or u, and creates shortint(h) or
longint(l) values.
The following are some of the type specifications:
d or i: Specifies the signed integer
o: Specifies the unsigned octal
x or X: Specifies the unsigned hexadecimal
flag: Specifies the code that determines the spacing and justification of the substituted value.
This can include symbols such as - (minus) and + (plus) to specify left-justification or to indicate
the value is a signed type respectively.
precision: Specifies the maximum number of characters taken from the argument value for string
values. For example, if a string has five characters and the precision is 2, only the first two
characters of the string value are used. width: Specifies an integer that defines the minimum
width for the field in which the argument value is placed.
@local_variable: Specifies a variable of any valid character data type that contains string
formatted in the same way as msg_str.
severity: Severity levels from 0 through 18 are specified by any user. Severity levels from 19
through 25 are specified by members of the sysadmin fixed server role or users with ALTER
TRACE permissions. Severity levels from 19 through 25 uses the WITH LOG option is required.
option: Specifies the custom option for the error.
Table 15.1 lists the values for the custom options.
Value Description LOG Records the error in the error log and the application log for the
instance of the Microsoft SQL Server Database Engine. NOWAIT Sends
message directly to the client SETERROR Sets the ERROR_NUMBER and @@ERROR values
to msg_id or 5000
irrespective of the severity level.
Table 15.1: Type Specification Values
When RAISERROR executes with a severity of 11 or higher in a TRY block, it will transfer the
control to the associated CATCH block.
Session
15
Error Handling
V 1.0 © Aptech Limited
437 of 452
15 Session
Error Handling
The following errors are returned back to the caller if RAISERROR executes:
→
Out of scope of any TRY block
→
Having severity of 10 or lower in TRY block
→
Having severity of 20 or higher that terminates the database connection
A CATCH block can use the RAISERROR statement to rethrow the error that has invoked the
CATCH block. For this, it will need to know the original error information which can be
obtained through the ERROR_NUMBER and the ERROR_MESSAGE system functions.
By default, the @@ERROR is set to 0 for messages that have a severity from 1 through 10.
Code Snippet 6 demonstrates how to build a RAISERROR statement to display a customized
error statement.
Code Snippet 6:
RAISERROR (N'This is an error message %s %d.',
10, 1, N'serial number', 23);
GO
In this code, the RAISERROR statements takes the first argument of N'serial number' changes
the first conversion specification of %s, and the second argument of 23 changes the second
conversion of %d. The code snippet displays the 'This is error message serial number 23'. Code
Snippet 7 demonstrates how to use RAISERROR statement to return the same string.
Code Snippet 7:
RAISERROR (N'%*.*s', 10, 1, 7, 3, N'Hello world');
GO
RAISERROR (N'%7.3s', 10, 1, N'Hello world');
GO
In this code, the RAISERROR statements return the same string, Hel. The first statement
specifies the width and the precision values and the second statement specifies the conversion
specification.
Users can also return error information from a CATCH block.
438 of 452
V 1.0 © Aptech Limited
Code Snippet 8 demonstrates how to use RAISERROR statement inside the TRY block.
Code Snippet 8:
BEGIN TRY
RAISERROR ('Raises Error in the TRY block.', 16, 1 );
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState );
END CATCH;
In this code, the RAISERROR statement used inside the TRY block has severity 16, which
causes the execution to jump to the associated CATCH block.
RAISERROR is then used inside the CATCH block to return the error information about the
original error.
15.8 ERROR_STATE
The ERROR_STATE system function returns the state number of the error that causes the
CATCH block of a TRY...CATCH construct to execute. The following is the syntax for the
ERROR_STATE system function.
Syntax:
ERROR_STATE ( )
When called in a CATCH block, it returns the state number of the error message that caused the
CATCH block to be run. This returns a NULL when it is called outside the scope of a CATCH
block.
There are specific error messages that are raised at various points in the code for the SQL Server
Database Engine. For example, an error 1105 is raised for several different conditions. Each
specific condition that raises error assigns the unique state code.
ERROR_STATE is called from anywhere within the scope of a CATCH block. ERROR_STATE
returns the error state regardless of how many times it is executed or whether it is executed
within the scope of the CATCH block. This is in comparison with the functions such as
@@ERROR that only returns the error number in the statement directly after the one that caused
error, or in the first statement of a CATCH
Session
15
Error Handling
V 1.0 © Aptech Limited
439 of 452
15 Session
Error Handling
block.
Users can use the ERROR_STATE in a CATCH block. Code Snippet 9 demonstrates how to use
ERROR_STATE statement inside the TRY block.
Code Snippet 9:
BEGIN TRY
SELECT 217/0;
END TRY
BEGIN CATCH
SELECT ERROR_STATE() AS ErrorState;
END CATCH;
GO
In this code, the SELECT statement generates a divide-by-zero error. The CATCH statement
will then return the state of the error. The ERROR_STATE is displayed as 1.
15.9 ERROR_SEVERITY
The ERROR_SEVERITY function returns the severity of the error that causes the CATCH block
of a TRY...CATCH construct to be executed.
The following is the syntax for ERROR_SEVERITY.
Syntax:
ERROR_SEVERITY ( )
It returns a NULL value if called outside the scope of the CATCH block. ERROR_SEVERITY
can be called anywhere within the scope of a CATCH block. In nested CATCH blocks,
ERROR_SEVERITY will return the error severity that is specific to the scope of the CATCH
block where it is referenced. Users can use the ERROR_SEVERITY function in a CATCH
block.
Code Snippet 10 shows how to display the severity of the error.
Code Snippet 10:
BEGIN TRY
SELECT 217/0;
BEGIN CATCH
SELECT ERROR_SEVERITY() AS ErrorSeverity;
END CATCH;
440 of 452
15.10 ERROR_PROCEDURE
The ERROR_PROCEDURE function returns the trigger or a stored procedure name where the
error has occurred that has caused the CATCH block of a TRY...CATCH construct to be
executed. The following is the syntax of the ERROR_PROCEDURE.
Syntax:
ERROR_PROCEDURE ( )
It returns the nvarchar data type. When the function is called in a CATCH block, it will return
the name of the stored procedure where the error occurred. The function returns a NULL value if
the error has not occurred within a trigger or a stored procedure. ERROR_PROCEDURE can be
called from anywhere in the scope of a CATCH block. The function also returns NULL if this
function is called outside the scope of a CATCH block.
In nested CATCH blocks, the ERROR_PROCEDURE returns the trigger or stored procedure
name specific to the scope of the CATCH block where it is referenced.
Code Snippet 11 shows the use of the ERROR_PROCEDURE function.
Code Snippet 11:
USE AdventureWorks2012;
GO
IF OBJECT_ID ( 'usp_Example', 'P' ) IS NOT NULL
DROP PROCEDURE usp_Example;
GO
CREATE PROCEDURE usp_Example
AS
SELECT 217/0;
GO
BEGIN TRY
EXECUTE usp_Example;
Session
15
Error Handling
V 1.0 © Aptech Limited
441 of 452
15 Session
Error Handling
END TRY
BEGIN CATCH
SELECT ERROR_PROCEDURE() AS ErrorProcedure;
END CATCH;
GO
In this code, the stored procedure usp_Example generates a divide-by-zero error. The
ERROR_PROCEDURE function accordingly returns the name of this stored procedure where
the error has occurred.
Code Snippet 12 demonstrates the use of ERROR_PROCEDURE function along with other
functions.
Code Snippet 12:
USE AdventureWorks2012;
GO
IF OBJECT_ID ( 'usp_Example', 'P' ) IS NOT NULL
DROP PROCEDURE usp_Example;
GO
CREATE PROCEDURE usp_Example
AS
SELECT 217/0;
GO
BEGIN TRY
EXECUTE usp_Example;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_MESSAGE() AS ErrorMessage,
ERROR_LINE() AS ErrorLine;
END CATCH;
GO
442 of 452
15.11 ERROR_NUMBER
The ERROR_NUMBER system function when called in a CATCH block returns the error
number of the error that causes the CATCH block of a TRY...CATCH construct to be executed.
The following is the syntax of ERROR_NUMBER.
Syntax:
ERROR_NUMBER ( )
The function can be called from anywhere inside the scope of a CATCH block. The function will
return NULL when it is called out of the scope of a CATCH block.
ERROR_NUMBER returns the error number irrespective of how many times it executes or
whether it executes within the scope of a CATCH block. This is different than the @@ERROR
which only returns the error number in the statement immediately after the one that causes error,
or the first statement of the CATCH block.
Code Snippet 13 demonstrates the use of ERROR_NUMBER in a CATCH block.
Code Snippet 13:
BEGIN TRY
SELECT 217/0;
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;
GO
As a result of this code, the error number is displayed when the attempted division by zero
occurs.
15.12 ERROR_MESSAGE
The ERROR_MESSAGE function returns the text message of the error that causes the CATCH
block of a TRY...CATCH construct to execute.
The following is the syntax of ERROR_MESSAGE.
Syntax:
ERROR_MESSAGE ( )
Session
15
Error Handling
V 1.0 © Aptech Limited
443 of 452
15 Session
Error Handling
When the ERROR_MESSAGE function is called in the CATCH block, it returns the full text of
the error message that causes the CATCH block to execute. The text includes the values that are
supplied for any parameter that can be substituted such as object names, times, or lengths. It also
returns NULL if it is called outside the scope of a CATCH block.
Code Snippet 14 demonstrates the use of ERROR_MESSAGE in a CATCH block.
Code Snippet 14:
BEGIN TRY
SELECT 217/0;
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO
In this code, similar to other examples, the SELECT statement generates a divide-by-zero error.
The CATCH block displays the error message.
15.13 ERROR_LINE
The ERROR_LINE function returns the line number at which the error occurred in the
TRY...CATCH block.
The following is the syntax of ERROR_LINE.
Syntax:
ERROR_LINE ( )
When this function is called in the CATCH block, it returns the line number where the error has
occurred. If the error has occurred within a trigger or a stored procedure, it returns the line
number in that trigger or stored procedure. Similar to other functions, this function returns a
NULL if it is called outside the scope of a CATCH block.
Code Snippet 15 demonstrates the use of ERROR_LINE in a CATCH block.
Code Snippet 15:
BEGIN TRY
SELECT 217/0;
END TRY
444 of 452
V 1.0 © Aptech Limited
BEGIN CATCH
SELECT ERROR_LINE() AS ErrorLine;
END CATCH;
GO
As a result of this code, the line number at which the error has occurred will be displayed.
15
Error Handling
V 1.0 © Aptech Limited
445 of 452
15 Session
Error Handling
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH
This code will cause the object name resolution error in the SELECT statement. It will not be
caught by the TRY...CATCH construct.
Running a similar SELECT statement inside a stored procedure causes the error to occur at a
level lower than the TRY block. The error is handled by the TRY...CATCH construct.
Code Snippet 17 demonstrates how the error message is displayed in such a case.
Code Snippet 17:
IF OBJECT_ID ( N'sp_Example', N'P' ) IS NOT NULL
DROP PROCEDURE sp_Example;
GO
CREATE PROCEDURE sp_Example
AS
SELECT * FROM Nonexistent;
GO
BEGIN TRY
EXECUTE sp_Example;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
15.15 THROW
The THROW statement raises an exception and transfers control of the execution to a CATCH
block of a TRY...CATCH construct.
446 of 452
V 1.0 © Aptech Limited
The following is the syntax of the THROW statement.
Syntax:
THROW [ { error_number | @local_variable },
{ message | @local_variable },
{ state | @local_variable }
][;]
where,
error_number: specifies a constant or variable that represents the error_number as int.
message: specifies a variable or string that defines the exception message as nvarchar(2048).
State: specifies a variable or a constant between 0 and 255 that specifies the state to associate
with state of message as tinyint.
Code Snippet 18 demonstrates the use of THROW statement to raise an exception again.
Code Snippet 18:
USE tempdb;
GO
CREATE TABLE dbo.TestRethrow
( ID INT PRIMARY KEY
);
BEGIN TRY
INSERT dbo.TestRethrow(ID) VALUES(1);
INSERT dbo.TestRethrow(ID) VALUES(1);
END TRY
BEGIN CATCH
PRINT 'In catch block.';
THROW;
END CATCH;
In this code, the THROW statement is used to raise once again the exception that had last
occurred.
Session
15
Error Handling
V 1.0 © Aptech Limited
447 of 452
15 Session
Error Handling
The outcome of the code will be as follows:
(1 row(s) affected)
(0 row(s) affected)
In catch block.
Msg 2627, Level 14, State 1, Line 6
Violation of PRIMARY KEY constraint 'PK__TestReth__3214EC27AAB15FEE'. Cannot insert
duplicate key in object 'dbo.TestRethrow'. The duplicate key value is (1).
448 of 452
Session
15
Error Handling
V 1.0 © Aptech Limited
449 of 452
15 Session
Error Handling
15.16.1 Answers
1. (A)
2. (B)
3. (C)
4. (D)
5. (C)
450 of 452
Summary
→
Syntax errors are the errors that occur when code cannot be parsed by SQL Server.
→
Run-time errors occur when the application tries to perform an action that is supported neither by
Microsoft SQL Server nor by the operating system.
→
TRY...CATCH statements are used to handle exceptions in Transact-SQL.
→
TRY...CATCH constructs can also catch unhandled errors from triggers or stored procedures that
execute through the code in a TRY block.
→
GOTO statements can be used to jump to a label inside the same TRY...CATCH block or to
leave a TRY...CATCH block.
→
Various system functions are available in Transact-SQL to print error information about the error
that occurred.
→
The RAISERROR statement is used to start the error processing for a session and displays an
error message.
V 1.0 © Aptech Limited
451 of 452
Session
15
Error Handling
V 1.0 © Aptech Limited
Try It Yourself
1.
For the transactions created in the Try It Yourself of Session 10 and 15, add error-handling
statements to take care of the errors.
2.
Acme Technologies Private Limited is a leading software company located at New York. The
company has achieved many awards as the best dealer in the development of software
technologies. The company has received many new projects on mobile and Web development.
At present, they are working on a database project for Payroll Management System in SQL
Server 2012.
They have created the database on Payroll management system for the employees. While
creating the tables, they receive different types of errors. Assume that you are the database
administrator of Acme Technologies and the Technical head has assigned you the task of
rectifying the errors. Perform the following steps:
a.
Write error-handling statements using the TRY...CATCH construct for both normal statements
as well as stored procedures.
b.
Display the error information using the following:
◆
ERROR_NUMBER
◆
ERROR_MESSAGE
◆
ERROR_LINE
452 of 452