You are on page 1of 383

SQL SERVER 6.

5
Chapter-1/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Introduction to Microsoft SQL Server and its features
SCOPE
RDBMS concepts overview
The ERA model
Database design and data modeling
Considerations in database design
About SQL Server 6.5
Client / Server features
Other features
SQL Server components
Distributed Management Framework
pratee
k jain
Digitally
signed by
prateek jain
DN:
cn=prateek
jain,
o=keetarp
niaj
softwares,
c=IN
Date:
2004.01.31
16:47:30 Z
Location:
Dehra doon
Signatu
re Not
Verified
SQL SERVER 6.5
Chapter-1/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
AN OVERVIEW OF RDBMS CONCEPTS
A database system is computer based record keeping system which stores information
deemed to be of significance to the organization the system is serving.
Let us consider a case study to learn how to implement a database design.
Library Case Study Overview
Objective :
To learn how to implement a database design on SQL Server 6.5.
Introduction :
Tata WebNet wants to offer library services on the net. An interview was conducted
to understand the library business needs, in order to implement a database strategy for the
librarian and the members.
The case study provides an overview of various library operations like rules for
enrolling new members, the book check out process and withdrawl of memberships.
Issue of membership :
An applicant can become a member of the library by following certain rules:
Applicant can fill an application form for the membership either from the web or
directly through the library by providing certain details like their names and
addresses.
If the applicant has been or is a member of the library, the application is rejected.
Application number is allocated to the applicant who has been selected after requisite
verifications.
Membership is allocated to the selected applicants, picking up the member details
from the application, provided the applicant comes within a week after filling in the
application form.
At the time of allocating membership security deposit is accepted from a member.
Security deposit is to be retained by the library in case of non-payment of fines or
failure to return books at the time of close of membership.
SQL SERVER 6.5
Chapter-1/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Book check out process :
Members can put a book request from the web also.
Member requesting a book submits relevant details which include Member Number,
Book name, Author and Subject and gets the book reserved.
A maximum of three books can be issued to a member.
In case a member has already been issued three books or has to pay fine,books are not
issued.
In case the book is not available in the library, member can search for:
Same book in other libraries
Any book on same subject in the same library
Any book on same subject in other libraries
Availability of books with the publishers.
A book reserved can be issued within a week of reservation.
Books can be checked out for 15 days.
On late return of book, the member is required to pay fine.
Membership withdrawl :
In case, member decides to withdraw the membership from the library, he or she
should pay all the dues to the library and return the books previously issued.
In case, he fails to do so, the security deposit should be retained.
Its been recommended that the Tata WebNet implement this design on Microsoft SQL
Server 6.5.
Before implementing the database design, the ERA Model which is the basis of database
design should be understood.
SQL SERVER 6.5
Chapter-1/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
ERA MODEL - THE BASIS OF DATABASE DESIGN
ERA model is used to explain various concepts involved in planning and organizing a
database. It is one of the data modeling tools involved in producing a fully normalized
database.
Components of ERA model
Entities
Any object of interest about which data can be collected.
EXAMPLE
Applicant is an entity about which information can be stored, such as Application No., Applicant
Name, Address.
Similarly, Book is an entity about which data can be collected such as ISBN, subject, title of the book,
author, publication etc.
Attributes
Qualifiers that identify or define characteristics of an entity.
EXAMPLE

Each Applicant has an Application no, Name, Address . These are attributes of the entity Applicant.
Entity : Applicant
Attributes : Application no.
Name
Address


Relationships
Different entities can have relationships with each other (similar to the function of
verbs in relation to nouns).
EXAMPLE

A Book is issued to a Member. The verb issued describes the relationship between the two nouns (entities),
Book and Member.

SQL SERVER 6.5
Chapter-1/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Mapping of the components of ERA Model to a database design
Different components of ERA Model are translated into different components of database
design.
Entity
An entity in an ERA Model is modeled as a table.

For example, in case of WebNet Library, the entity Applicant is translated into a
table called Applicant.
EXAMPLE
TABLE
APPLICANT
APPL_NO NAME ADDRESS
A001 BARR, PETER CHURCH STREET
A002 ALLEN, SAM PARK STREET
A003 M, MARY POND DRIVE

DATABASE ( a collection of tables)
Note : Table names must be unique within a database
BOOK TABLE TABLE
TABLE
MEMBER ARCHIVE
APPLICANT
TABLE TABLE
TABLE
NAME OF
THE TABLE
LIBRARY
NAME OF
THE
DATABASE
SQL SERVER 6.5
Chapter-1/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Characteristics of table
Tables are composed of rows (records) and columns (fields).
DIAGRAM
APPLICANT
APPL_NO NAME ADDRESS
A001 BARR, PETER CHURCH STREET
A002 ALLEN, SAM PARK STREET
A003 M, MARY POND DRIVE
APPLICANT
APPL_NO NAME ADDRESS
A001 BARR, PETER CHURCH STREET
A002 ALLEN, SAM PARK STREET
A003 M, MARY POND DRIVE
Rows and columns can be in any order.
Each table stores data about entities.
Attributes
Attributes of the entity Applicant, such as Application No., Name, Address form the
columns of the table.
EXAMPLE
Applicant is an entity about which information can be stored, such as Application no.., Name, Address.
Application no., Name, Address are the attributes of the entity Applicant.
APPLICANT
APPL_NO NAME ADDRESS
- - -
- - -
- - -
Note: Column Names must be unique within a table
ENTITY
ATTRIBUTES
RECORD (ROW)
COLUMN (FIELD)
SQL SERVER 6.5
Chapter-1/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Non-decomposable columns
All columns in a table must be non-decomposable.
If the information in a column can be broken into multiple usable parts, columns
should be redefined as two or more columns.
EXAMPLE
APPLICANT
APPL_NO NAME ADDRESS
A001 BARR, PETER CHURCH STREET
A002 ALLEN, SAM PARK STREET
A003 M, MARY POND DRIVE
APPLICANT
APPL_NO LAST_NAME FIRST_NAME ADDRESS
A001 BARR PETER CHURCH STREET
A002 ALLEN SAM PARK STREET
A003 M MARY POND DRIVE
Primary Key
An attribute or attributes whose value uniquely identifies a specific row in a relation.
It is always recommended to have a Primary Key on a table.
There can be only one Primary key per table.
Enforces data integrity by ensuring that each row in the table is unique.
EXAMPLE
APPLICANT
APPL_NO LAST_NAME FIRST_NAME ADDRESS
A001 BARR PETER CHURCH STREET
A002 ALLEN SAM PARK STREET
A003 M MARY POND DRIVE
A004 ALLEN JOHN PARK STREET
PRIMARY
KEY
UNIQUE
VALUES
SQL SERVER 6.5
Chapter-1/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Foreign Keys
A column added to a table A , that is Primary Key of another table B.
A Foreign Key references the Primary Key of a table.
Values in the column marked as Foreign Key are checked against the values in the
Primary Key column to verify that these value are legitimate.
Provides a link between the two tables.
Foreign key can also be the primary key of the same table. In that case the foreign key
should be unique.
Enforces referential integrity by ensuring that each value in the Foreign Key column
is a valid Primary Key.

EXAMPLE
MEMBER
MEM_NO LAST_NAME FIRST_NAME ... ...
M001 BARR PETER ... ...
M002 ALLEN SAM ... ...
M003 M MARY ... ...
M004 ALLEN JOHN ... ...
ISSUE
ISBN COPY_NO MEM_NO OUT_DT DUE_DT
ID12 3 M002 03-04-97 03-19-97
CP03 1 M001 03-01-97 03-16-97
Relationships
Relationships are of three types and each of them is modeled differently.
1. One-to-one relationship
2. One-to-many relationship
3. Many-to-many relationship
FOREIGN KEY
PRIMARY
KEY
SQL SERVER 6.5
Chapter-1/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
One-to-one relationship
For each occurrence of an entity, there is a corresponding single occurrence of the
other entity.

EXAMPLE

A copy of a book (since unique ISBN + copy_no) can be issued only to one member. A member can
have only one book issued for a particular copy of that book.



Modeled using a foreign key.

EXAMPLE

The primary key of MEMBER is Mem_no which will exist as an attribute in the ISSUE table as a
foreign key. (Refer to the diagram for Foreign keys given earlier.)


One-to-many relationship
Each occurrence of one entity can result in multiple occurrence of the other entity.
EXAMPLE
A publisher can publish many books. But a particular book is published by only one publisher.
The entity PUBLISHER constitutes the one part of the relationship. The entity
PUB_BOOKS constitutes the many part of the relationship.
Models as a foreign key.
Primary key of the one part of the relationship is necessarily the foreign key in the
many part of the relationship.
SQL SERVER 6.5
Chapter-1/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
The primary key of PUBLISHER is Pub_no which will exist as an attribute in the PUB_BOOKS table as a
foreign key.

PUBLISHER
PUB_NO PUB_NAME ADDRESS
P001 - -
P002 - -
PUB_BOOKS
PUB_NO SUBJECT TITLE AUTHOR COST
P001 Window 95 ABC Win 95 ABC $12.00
P002 Java Java Book XYZ $10.00
P002 SQL Server SQL SVR 6.5 PQR $10.00




Many-to-many relationship
Multiple occurrences of one entity have corresponding multiple occurrences of
another entity.
EXAMPLE
Many publishers can publish many books and many books are published by many publishers.
Many part
SQL SERVER 6.5
Chapter-1/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
RELATIONSHIP MODELED AS
one-to-one foreign key column
in either table
one-to-many foreign key column in the table
which has many relationships
many-to-many separate table as a link with
foreign key columns to both
tables
DIAGRAM
THE ERA MODEL
ENTITIES RELATIONSHIPS ATTRIBUTES
Tables
Columns or
Tables
Columns Modeled as
SQL SERVER 6.5
Chapter-1/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DATABASE DESIGN AND DATA MODELING
Roles and responsibilities of the Administrator
Installation and Configuration
Security Management
Data and Storage Management
System maintenance

Roles and responsibilities of the Implementor
Creating the logical database design
(a) Describes the organization of the database
(b) Produces a database schema which defines
(i) Information to be stored.
(ii) Organization of the data.
(iii) The tables needed.
(iv) Column definitions
Implementing the logical database design
(a) Determining storage space ( for databases etc.)
(b) Creating tables
(c) Selecting Primary Keys and Foreign Keys.
(d) Physical implementation of the Database Schema.
Designing and implementing data integrity requirements
(a) Done during all phases of a database design
(b) Restrictions are assigned to certain data to enforce data integrity
(c) Implemented at all levels in the database
Programming the database involves writing small program codes which are used to
(a) Enforce data integrity
(b) Provide information to users
(c) Automate administrative tasks
(d) Provide capability to communicate with clients (ODBC)
SQL SERVER 6.5
Chapter-1/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Database Design
Planning the database design includes
(a) Determining the business and user requirements
(b) Considering the problems that are to be used
Considerations in Database Design
Creating a Normalized database
(a) Prevents unnecessary data redundancy and inconsistencies in the database
(b) Enhance the maintainability, extensibility and performance of the database
(c) The overall goal in creating a relational database is a design that meets the rules
of a third normal form.
Considering the Degrees of Denormalization
(a) Fully normalizing the database tables doesnt work always.
(b) Denormalization is purposeful violation of the rules of a normalized database to
increase the performance of a specific task.
EXAMPLE
A join returning information from different tables might take too long , in comparison to creating a single
table that holds information from all the three tables as a single row of information.
(c) Database should be fully normalized before considering the denormalization.
(d) Occurs during all phases of implementing a database.
SQL SERVER 6.5
Chapter-1/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
ABOUT THE MICROSOFT SQL SERVER 6.5
Microsoft SQL Server 6.5 is one of the powerful, high performance, preferred Relational
DataBase Management Systems, that runs on the Microsoft Windows NT operating
system.
It is capable of supporting hundreds of simultaneous users, depending on the application
and the hardware environment.
It is designed as the central repository for all the data of an organization and to meet the
demanding requirements of distributed client/server computing.
Client/server features of SQL server
DIAGRAM
EVOLUTION OF CLIENT/SERVER COMPUTING



Host centric computing with an intelligent central Mainframe and Dumb terminals

A stand-alone intelligent Personal Computer
Mainframe
Dumb
Terminal
Dumb
Terminal
Dumb
Terminal
SQL SERVER 6.5
Chapter-1/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.



Client/Server computing across a LAN
(Clients are intelligent i.e. have CPU)
Client/Server computing and SQL Server
Client/Server computing is a type of distributed model for data storage, access and
processing which combines the best parts of Mainframe and Stand-alone technology
into a cohesive environment. (As shown in the diagram)
Server database that resides in a common location is accessed by many users called
clients from other computer systems rather than from I/O devices such as terminals.
With more intelligent client systems, users can retrieve information from the server
and manipulate/process it locally and independently without communicating with the
server, which optimizes the processing of the information.
SQL Server provides the server software that is installed on the server system and
client software installed on the client PC system.

The SQL Server database is the Server application which is responsible for creating
and maintaining database objects such as tables and indexes, maintaining integrity
and security.
The client software allows to create, maintain and access the database and all objects
from the client and allows the client applications written in host languages like Visual
Basic, C, C++ etc. to perform add, change and delete operations against the database
residing on the Server.

Client or front-end co-ordinates application logic with a Server or back-end
application using some mechanism of communication.
Server
Intelligent
Client
Intelligent
Client
Intelligent
Client
SQL SERVER 6.5
Chapter-1/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
The network software components required for the interconnection of Client and the
Server computer in case of SQL Server are built into the Windows NT system.
DIAGRAM
Traditional approach Vs Client/Server approach
Traditional approach
Traditional applications are data-dependent i.e.:
the way in which data is organized in secondary storage
the way in which data is accessed
are related to the requirements of the application.
EXAMPLE
If a file is stored in indexed sequential form, the application must have the knowledge that index exists and
internal structure of the application will be built around this knowledge.
Client/Server approach
Client/Server computing is data-independent.
Applications concerned, do not depend on any one particular storage structure and
access strategy.
SQL Server
CLIENTS
SERVER
Connections are through Network software components
built into Windows NT
C
C++
Visual Basic
SQL SERVER 6.5
Chapter-1/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
The storage structure or access strategy can be changed in response to changing
requirements without having to modify existing applications.
Microsoft SQL Server features
Best database for Microsoft Windows NT
The unified architecture of SQL Server with Windows NT, sharing programming
interfaces and tools, administration, security and network models, and broad hardware
options, facilitates building and deploying of richer applications more quickly and easily.
Multiprocessing feature of Windows NT
Windows NT can run on systems that use different microprocessors for their CPUs
such as Intel 386, 486, Pentium, x86 clones, Alpha AXP, MIPS R4000 series etc.
The key advantage of using SQL Server with Windows NT as the operating system
platform is that there are many choices of computer systems to use as server for the
SQL Server database.
I/O requests can be handled by one processor while other operations such as
validation can be performed by the other processor of the system.

Thus, multiple server requests can be handled at one time, which increases the
number of clients that can be served by the server.
DIAGRAM
Multiple server requests can be handled at one time by using more than one CPU.
Windows NT
SQL
Server
Client 1
Client 2
I/O request
Validation
CPU1
CPU2
CPU3
I/O request
Validation
Client 3
Validation
Validation
CPU4
SQL SERVER 6.5
Chapter-1/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Multithreading environment of Windows NT
Multithreading environment of Windows NT provides significant performance
improvements over environments that dont have this capability.
The two processes of SQL Server, MSSQLServer and MSQLExecutive, which are
sections of computer code that control how the computers hardware and other
software is used, use Windows NT processes to service the client systems.
For example, Transact-SQL statements when issued, are conveyed to and performed
by these two processes.

The processes are divided into multiple threads of execution. Each thread being
executed by a single processor, allows multiple execution in a multiprocessor
environment of Windows NT.
DIAGRAM
Threads of a process
( Each thread being executed on a single processor)
Windows NT security and SQL Server
Standard security
To logon to the SQL Server, each user must provide a valid login ID and password.
SQL Server has its own validation process for the connections, which is referred as
standard security.
A Process
CPU2 CPU4 CPU3 CPU1
thread 1 thread 2 thread 3 thread 4
SQL SERVER 6.5
Chapter-1/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Integrated security
Integrated security allows SQL Server to use Windows NT authentication mechanism
to validate logins for all connections.
Integrated security lets SQL Server applications take advantage of Windows NT
security features, including encrypted passwords, password aging, domain-wide user
accounts and Windows-based user administration.
Mixed security
It allows SQL Server login requests to be validated by using either integrated or
standard security methods.
Monitoring server activity and performance
Performance Monitor
SQL Performance Monitor is the integration of Microsoft SQL Server with the
Window NT Performance Monitor.
It makes possible to get up-to-the -minute activity and performance statistics about
SQL Server.
It obtains statistics from performance counters, several of which are grouped within a
performance object.
Event viewer
Windows NT Event log, is a special file containing SQL Server error messages as
well as messages for all activities on computer
This file can be viewed only by using the Windows NT Event viewer.
SQL SERVER 6.5
Chapter-1/20
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Multiple-user environment of SQL Server on Windows NT
Windows NT enables the establishment of networks and connection to other computer
systems. The connectivity feature of Window NT serves many purposes:
Network connections can be made for the purpose of sharing the resources on
different systems.
Connections can be created to access information on a remote disk of another
Windows NT or a non-Windows NT system.


Database access from the SQL Server database by the clients depends on the
communication connections that are established by the Windows NT system.

Administrative operations can be done through network connections to Windows NT.
Best database for the Internet
SQL Servers built-in Internet integration gives organizations the ability to build
Active Web Sites.
The SQL Server Web Assistant, an easy-to-use interface, allows to define a set of
data (a query) which is automatically merged into an HTML document and pushed to
the Internet Server.
DIAGRAM
SQL
Server
( Web
Assistant)
Internet Server
Web Browser
HTML
files
Browser
reviews data
SQL SERVER 6.5
Chapter-1/21
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Web users can initiate dynamic queries from an HTML document to a SQL Server,
through the Microsoft Internet Information Server (IIS).
Note: Details are covered in the later sessions.
DIAGRAM
Replication
Replication is provided as an integral element of Microsoft SQL Server 6.5.

It allows automatic distribution of read-only copies of transactional data from a single
source server to one or more destination servers at one or more remote locations.

DIAGRAM



BASIC REPLICATION MODEL
When SQL Server data is published to non-SQL Server systems like Oracle, Access,
Sybase, IBM DB2, it is called Heterogeneous Replication.
Web
Browser
IDC
Internet
Server
SQL
Server
Query
IIS requesting
data from SQL
S
SQL Server
returns data
Receiving
data
IIS
Read/Write
database
Read only data
tables
SQL SERVER 6.5
Chapter-1/22
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Distributed transaction
SQL Server supports distributed transactions. ( Transactions that span more than one
server.)

When a transaction occurs, many times more than one source of information need to
be updated

DTC (Distributed Transaction Coordinator) provides the utility functions that help
manage the distribution transaction process.

Changes on multiple servers can be committed as a single unit of work.
Open DataBase Connectivity (ODBC)
SQL Server driver enables different client applications to access data in SQL Server
database through ODBC interface without requiring any change to Server database or
the client application.
DIAGRAM
OPEN DATABASE CONNECTIVITY

Integration with OLE object technology
OLE is a programming technology that allows an application to expose objects,
properties, and methods to other controller applications.
Controller applications can then program the object application.
DBASE SQL SVR
Network
Client
Application
ODBC DLL
DBASE Driver SQL SVR Driver
SQL SERVER 6.5
Chapter-1/23
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SQL Enterprise Manager, a tool that simplifies managing multiple server
environment utilizes the OLE service, which provide easier administration of tasks
since relationship between the objects are known.
Programmability using Visual Basic, VC++ provide an extensible programming
environment for SQL Server.
DIAGRAM
OLE AND SQL SERVER


Other features
SQL Server supports very large databases, allowing the management of databases in
the 100 to 200 Gigabyte range.
In addition to using the dialect of SQL (Transact-SQL), which is a high level
language for RDBMS, SQL Server provides a variety of graphical and command line
utilities that enable clients to access data in a variety of ways.
All of Microsofts best infrastructure technology and Microsofts best development
tools are optimized to work best with Microsoft SQL server.
EXAMPLE
Microsoft Visual Basic Enterprise, Microsoft Visual C++ Enterprise include tools to manage SQL server
objects.
SQL Enterprise Manager VB, VC++, etc.
SQL OLE
SQL Server Object application
Controller
application
SQL SERVER 6.5
Chapter-1/24
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CLASSROOM EXERCISE
1. How does the multiprocessing feature of Windows NT help SQL Server?
2. What is the difference between Replication and Distribution?
3. What is the purpose of SQL Performance Monitor?
SQL SERVER 6.5
Chapter-1/25
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SQL SERVER COMPONENTS
Transact-SQL
The query language, SQL, is the standard database query language for the relational
databases. The dialect of the SQL used with SQL Server is Transact-SQL.
Transact-SQL statements are used to:
create logical storage units such as databases. (CREATE DATABASE statements)
create objects such as tables that are stored in databases. (CREATE TABLE
statements)
add and manipulate data and other database objects. (INSERT, DELETE, UPDATE
and SELECT statements)
execute SQL statements rapidly by the use of stored sets of Transact-SQL statements
such as stored-procedures .
Command line Applications
Transact-SQL statements can be entered through the ISQL (Interactive Structured
Query Language) utility.
From the Operating System prompt, ISQL is invoked with the command isql along
with the needed parameters.
EXAMPLE
isql /u<login id> /p<password>
1>
The command is given from the Operating System prompt.
The execution of the command results in entering the ISQL command session directly, since the
username and password are entered.
Each parameter is preceded by the forward slash (/) or a hyphen (-).
The ISQL command prompt will be successively numbered (as shown in the example) until the
execution command (GO) is entered.
ISQL commands used after entering ISQL.
SQL SERVER 6.5
Chapter-1/26
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Commands Purpose
GO Executes a command
RESET Clears statements that were entered
ED Invokes the default system editor
!! command Executes an Operating System command
QUIT or EXIT() Exits ISQL
Ctrl+C Terminates a query without exiting ISQL
SHUTDOWN Stops the SQL Server and exits ISQL
Note: See Appendix B for details.
GUI Applications
ISQL/w
Allows issuing of Transact-SQL statements in a graphical query interface.
Can be considered as a Windows version of ISQL command line.
SCREEN CAPTURE
SQL statements are entered in the query page of ISQL/w.
Operations like cut, copy, paste, print, save and edit previous queries can be done
easily, in comparison to ISQL command line.
On execution, Query output is displayed in the Results window.
ISQL/w has the capability for graphically analyzing the queries.
SQL SERVER 6.5
Chapter-1/27
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SQL Enterprise Manager
Used to perform all administrative operations with local or remote servers.
Following tasks can be performed using the SQL Enterprise Manager:
Manage user accounts and server logins (login option under manage in Enterprise
Manager)
Manage databases and database objects (Database devices and database options
under manage)
Start, stop and configure servers (SQL Server option under server)
Display server statistics (current activityoption under server)
Configure and manage replication (replication configuration option under server)
Manage the access control (permissions option under object)
Schedule tasks and events (scheduled tasks and alerts / operators options under
server). These are commonly called as Executive managers which are serviced by the
SQLExecutive service running in the background.
Backing up and restoring (Database backups/restore option under tools)
Managing remote servers (Remote servers option under server)
Scheduling automatic daily or weekly routine database maintenance tasks such as
database and transaction log backups, database consistency check etc. (Database
maintenance wizard option under help)
SQL Service Manager
SQL Service Manager is useful when physically working on the server.
It starts, stops or pauses the local or remote SQL Server processes.
It must be started before any operation within the database can be performed.
SQL SERVER 6.5
Chapter-1/28
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SCREEN CAPTURE
SQL Service Manager dialog box after the MSSQLServer service is started.
The traffic-light metaphor simplifies starting, stopping, pausing SQL Server.
Services in Window NT, such as MSSQLServer and SQLExecutive of SQL Server,
are system processes that run in the background within NT.
These background processes are used by SQL Server and client systems that require
their functions.
SQL Security Manager
Provides a way to map the NT users and groups to SQL Server.
Authorizes Windows NT users to access SQL Server
SQL Client Configuration Utility
Defines the Net-Library and DB-Library used for communication between the client
and the server.
Net-library is set to Named pipes which is the default communication mechanism
between the client and the server
A different network library, (other than Named pipes ) can be chosen as an alternative
communication mechanism.
It also searches for multiple copies of DB-Library and displays the version number.
DB-Library is an API for both C and VB that allows to work directly with SQL
Server.
SQL SERVER 6.5
Chapter-1/29
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SCREEN CAPTURE
SQL Server Books online
Provides online access to the entire text of the SQL Server documentation provided
by Microsoft.
Includes a powerful and easy-to-use full-text search capability.
SQL Performance Monitor
Integrates Windows NT Performance Monitor with SQL Server, providing the status
of the activities and performance statistics of both the system and the SQL Server.
SQL Trace
Monitors and records SQL Server database activity.
Monitoring can be done real-time or it can create filters that focus on actions of
particular users, applications or hosts servers.
It can display any SQL statements and remote procedure calls that are sent to any
SQL Server.
SQL SERVER 6.5
Chapter-1/30
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Microsoft Query
Allows to build SELECT queries graphically against any ODBC data source.
It can display basic schema information about a database.
SQL Server Web Assistant
Generates HTML files from SQL server data by using Transact-SQL queries, stored
procedures.
Generated Web pages can be viewed with any HTML browser.
SQL setup
SQL setup is used to:
Install new software
Upgrade existing software
Remove SQL Server
Change network support options
Add a language
Set security options.
Microsoft SQL Server ODBC driver
A help file providing information about the Microsoft SQL Server ODBC Driver.
SQL Distributed Management Objects
A help file displaying the Microsoft SQL Server Distributed Management Object
Model.
CLASSROOM EXERCISE
1. Which graphical tool of SQL Server can be used to graphically build
SELECT queries?
2. Can SQL Enterprise manager be used to start, pause, continue or stop SQL
Server services?
SQL SERVER 6.5
Chapter-1/31
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DISTRIBUTED MANAGEMENT FRAMEWORK
Distributed Management Framework (DMF ) of objects, services and components is used
to manage Microsoft SQL Server.
Logically it can be separated into three parts.
DIAGRAM
Server/Back end
Direct access to SQL Server engine and services is through Transact-SQL statements
from the command line.

The SQL Executive service manages replication, tasks, events and alerts .

The SQL Executive Service and SQL Server service work together to provide the
database back end, and run as Window NT services.
SQL Object library
DMO provides 32-bit OLE automation objects and expose interfaces for all SQL
Server management functions to any OLE-compliant application.

It acts as a middle layer between the client and the server.

SQL Enterprise Manager
SQL Server Distributed Management Objects
SQL Executive Services SQL Server Service
Clients/Front
end
SQL
Object
library
Server/Back
ends
(NT
services)
OLE Automation
SQL SERVER 6.5
Chapter-1/32
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
This capability allows applications that use these objects to manage SQL Server from
remote locations.
Clients/Front end
The client layer includes SQL Enterprise Manager as well as any applications written
using SQL-DMO automation objects.
SQL SERVER 6.5
Chapter-1/33
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Capabilities and Limitations of SQL Server
Description Capabilities/Limitations
Maximum number of databases 32,767
Maximum number of tables Two billions
Maximum number of columns per table 250
Maximum number of rows per table Unlimited ( number of rows are limited in
practice by the capacity of the storage
medium on which tables are srored)
Maximum number of devices 256
Maximum number of bytes per row 1962 (excluding text and image column)
Maximum number of indexes:
Clustered
Nonclustered
1 per table
249 per table
Maximum number of columns that can be
indexed
16
Maximum number of triggers on a table 3 ( one each for INSERT, UPDATE and
DELETE)
Maximum number of parameteres in a
stored procedure
255
SQL SERVER 6.5
Chapter-1/34
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
SQL Server is designed as the central repository for all the data of an organization and to
meet the demanding requirements of distributed client/server computing.
Components of ERA model:
Entity
Attribute
Relationships
Features:
Best database for Microsoft Windows NT
Best database for Internet
Replication
Distributed transactions
ODBC
Integration with OLE technology
Database Maintenance Plan Wizard
Remote server management
SQL Server Components:
SQL Enterprise Manager
SQL Service Manager
ISQL/w
SQL Security Manager
SQL Trace
SQL Client Configuration utility
SQL Performance Monitor
Microsoft query
SQL Server Web Assistant
SQL Books online
SQL Setup
Microsoft ODBC SQL Server Driver
SQL DMO
SQL SERVER 6.5
Chapter-1/35
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LAB EXERCISES
1. Assign your server to a group and then register your server using SQL
Enterprise Manager.
2. Explore the SQL Enterprise Manager.
3. Create a Transact-SQL script using the script generating capability of SQL
Server through SQL Enterprise Manager.
4. Use the SQL Query tool to create and execute queries in the Enterprise
manager .
5. Explore the ISQL/w utility.
6. Based on the information presented by the WebNet Library, design a
database for the desired Library system.
SQL SERVER 6.5
Chapter-2/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Managing Tables
SCOPE
Database Tables - Creation
Datatypes
System supplied datatypes
User defined datatypes
Creation
Dropping
Dropping and altering tables
Temporary tables
Frequently used system stored procedures with tables
Retrieval of data
Simple SELECT statement
Functions
SQL SERVER 6.5
Chapter-2/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DATABASE TABLES
Tables
Table is a set of related information stored within the database.
Table is a logical structure in which data is stored in rows and columns.
Column is an individual piece of information referred as a field.
Row is a set of columns referred as a record.

DIAGRAM


















A simple CREATE TABLE statement


The major part of creating a table is specifying the datatypes for the columns of the
tables.

To understand the SQL Server datatypes, consider the following simple CREATE
TABLE statement.

DATABASE
TABLE TABLE
TABLE
field
record
SQL SERVER 6.5
Chapter-2/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Syntax:

CREATE TABLE table_name
( column_name datatype [ not NULL | NULL ]
[, column_name datatype [ not NULL | NULL]]...)


CREATE TABLE parameters


Parameters Description

table_name Specifies the name of the table to be created
column_name Specifies the name of the column to be inserted into the table
datatype Specifies the type of the information that can be stored into the
column
not NULL | NULL Default is not NULL which doesnt allow an undefined column
value
NULL lets the omitting of the entry of a column value in the
column.

Note : Examples are covered along with the datatypes


Datatypes

The datatype is the first characteristic that is defined for the column of a table.
The datatype of a column controls the type of information that can be stored within
the column ( character data, integer data, date type data etc. ).
Datatypes can be categorized into:

(a) System-supplied datatypes
(b) User-defined datatypes


System supplied datatypes

SQL Server supplies various system supplied datatypes which can be categorized by
the type of the data stored within the datatype.
System supplied datatypes are case-insensitive.




SQL SERVER 6.5
Chapter-2/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Type of the data System-supplied datatypes

Binary binary [(n)], varbinary[(n)]
Character char [(n)], varchar [(n)]
Date and time datetime, smalldatetime
Numeric integer int, smallint, tinyint
Numeric floating type float [(n)], real, decimal [(p[, s])],
numeric [(p[, s])]
Monetary money, smallmoney
Special bit, timestamp
Text and Image text, image

Binary datatype

Binary data consists of characters 0 through 9 and A through F (or a through f) in
groups of two characters each, for example A0, 00, ff etc.
When specifying the length of binary datatype every two characters count as one.
Thus, two characters occupy one byte. For example, if datatype is defined as
binary(1), then it can store values from 00 to FF.
Binary strings must be preceded by 0x . For example, to input FF, type 0xFF.
Maximum binary data value is 255 bytes, each of which is FF.



binary [(n)] varbinary [(n)]

Holds 255 bytes of fixed length binary data Holds 255 bytes of variable length binary
data
Specify the maximum byte length with n Specify the maximum byte length with n
Storage size is n regardless of the actual
length of the entry
Storage size is the actual length of data
entered, not n
Choose binary when data entries in the
column will be consistently of same size
Choose varbinary when NULL values or
variation in size is expected
Accessed faster Not as fast as binary.


A binary column defined as NULL is handled as varbinary.
If values are entered greater than the length defined, the values are truncated.





SQL SERVER 6.5
Chapter-2/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

EXAMPLE

Example 1

CREATE TABLE bintable (b1 binary(1), b2 binary(2))

INSERT INTO bintable VALUES(0x0, 0x0)
INSERT INTO bintable VALUES(0x1, 0x1)
INSERT INTO bintable VALUES(0xff, 0xff)
INSERT INTO bintable VALUES(0xfff, 0xfff)
/* INSERT statement is used to
insert values into the
specified table .
The column values in the
VALUES clause are in the same
order in which the columns
are defined in CREATE TABLE .
*/

SELECT * FROM bintable

OUTPUT:

b1 b2
---- ----
0x00 0x0000
0x01 0x0100
0xff 0xff00
0x0f 0x0fff

Notice that in the last output, for binary(1), ff has been truncated and value is 0x0f.
For binary(2), the value is 0x0fff, since it has been padded with 0.

Example 2

CREATE TABLE varbintable (b1 varbinary(1), b2 varbinary(2))

INSERT INTO varbintable VALUES(0x0, 0x0)
INSERT INTO varbintable VALUES(0x1, 0x1)
INSERT INTO varbintable VALUES(0xff, 0xff)
INSERT INTO varbintable VALUES(0xfff, 0xfff)

SELECT * FROM varbintable

OUTPUT:

b1 b2
---- ----
0x00 0x00
0x01 0x01
0xff 0xff
0x0f 0x0fff


SQL SERVER 6.5
Chapter-2/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Character datatypes

Allows the storage of data consisting of combination of letters, numbers and symbols.
Character data is entered in either single or double quotes when loading it into a
storage area such as column of a table.
If the value of the string is a null value, NULL is not enclosed in single quotes.
An empty string is not same as NULL.
A char column defined as NULL is handled as a varchar column.


char datatype varchar datatype

Each character stored uses 1 byte. Each character stored uses 1 byte.
Used for storing fixed-length strings. Used for storing variable-length strings.
The number in parentheses specifies the
size of storage for each value of the
column.




Example:
char (10) specifies that each value of the
column is 10 bytes in size and can store 10
characters.
If there are fewer than 10 characters ,
blanks are added after the last specified
character
The number in parentheses specifies the
maximum size of storage which varies
according to the number of characters
stored in each column value of rows of the
table.

Example:
varchar (10) specifies that a maximum of
10 characters can be stored in the column.

However, blanks are not added , if there are
fewer characters than 10.
Can contain maximum of 255 characters Can contain maximum of 255 characters

EXAMPLE

CREATE TABLE tab1
( str1 char(5), str2 varchar(5 ))

INSERT into tab1
VALUES (ab, cd)

OUTPUT:

The insertion of the row causes first column str1 to store 2 characters a and b padded with three
spaces.
So first column str1 occupies five bytes of storage.
Second column str2 will store 2 characters c and d. ( not padded with spaces)
So second column str2 occupies 2 bytes of storage.

SQL SERVER 6.5
Chapter-2/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Date and time datatype

Consists of alphanumeric data which represents date and time.
The default format is Mon dd yyyy hh:mmAM/PM for example Jul 29 1974
06:45AM.
Date values are enclosed within quotes.
SQL Server recognizes the date portion and the time portion of the data separately,
so the date portion of data can precede or follow the time portion.

datetime datatype

Stores data in 8 bytes of two 4-byte integers; 4 bytes for the number of days before or
after the base date of Jan 1, 1900 and 4 bytes for number of milliseconds after
midnight.
Date values range from Jan 1, 1753 to Dec 31, 9999 to accuracy of 3.33
milliseconds.
Either of the portions of the data can be omitted . For example, if a date value without
time is inserted (for example Jul 29 1974), it is interpreted as Jul 29 1974
12:00AM. If only time is supplied (for example 06:45), the date value is interpreted
as Jan 1 1900 06:45AM.
If both the portions are omitted, datetime value defaults to Jan 1 1900 12:00AM.


smalldatetime datatype

It is less precise than datetime.
Storage size is 4 bytes, which consists of one small integer for the number of days
after Jan 1, 1900 and one small integer for number of minutes past midnight.
Data values can range from Jan 1, 1900 through Jun 6, 2079, with accuracy to minute.

Date formats

Alphabetic format

Mon[th] [dd][,] yyyy
Mon[th] [dd][,] [yy]yy
Mon[th] yyyy [dd]
Mon[th] [yy]yy dd

[dd] Mon[th] [,] yyyy
dd Mon[th] [,] [yy]yy
dd [yy]yy Mon[th]
[dd] yyyy Mon[th]


SQL SERVER 6.5
Chapter-2/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


yyyy MON[TH] [dd]
[yy]yy MON[TH] dd
yyyy [dd] MON[TH]

If only last two digit of the year are specified, values less than 50 are interpreted as 20yy
and values greater than or equal to 50 are interpreted as 19yy.

Numeric format

The month, day and year in a string are specified with slashes, hyphens or periods as
separators.

[m]m/dd/[yy]yy
[m]m-dd-[yy]yy
[m]m.dd.[yy]yy
[mm]/[yy]yy/dd

dd/[m]m/[yy]yy
dd/[yy]yy/[m]m

[yy]yy/dd/[m]m
[yy]yy/[mm]/dd


When the date is specified in the numeric format, the settings for DATEFORMAT
determine how date values are interpreted.

The SET DATEFORMAT command sets the date order. The default order is mdy.

EXAMPLE

The dateformat can be set as follows:

SET DATEFORMAT dmy


If the order does not match the settings, either the values are not interpreted as dates
(being out of range) or are misinterpreted. For example, 12/12/03 can be interpreted as
either of six dates, depending on the DATEFORMAT setting.

Unseparated string format

These are numeric entries without separators.
[yy]yymmdd

SQL SERVER 6.5
Chapter-2/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


These are always interpreted as ymd. The month and day must always be two digits.
A string of only four digits is interpreted as the year. The month and date are set to Jan 1.
When specifying only four digits, century must be included.

Time formats

hh:mm
hh:mm[:ss:ms]
hh:mm[:ss.ms]
hham
hh PM
[h]h[:mm:ss:ms]AM

EXAMPLE
CREATE TABLE date_table
(d1 datetime,d2 smalldatetime)

INSERT INTO date_table
VALUES(Jan 1753 1, Jan 1 1900)

SELECT * FROM date_table

OUTPUT:
d1 d2
------------ -------------
Jan 1 1753 12:00AM Jan 1 1900 12:00AM
Notice the time part has been supplied automatically.


Try inserting values which are out of range for both the datatypes.
SQL SERVER 6.5
Chapter-2/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Numeric datatypes

DIAGRAM












Numeric integer datatypes

Enables storing of whole numbers.
Arithmetic operations can be performed on these datatypes.


Integer datatypes int or integer smallint tinyint

Range -2,147,483,648
to
2,147,483,647
-32768
to
32767
0
to
255
Storage Occupies 4 bytes .

31 bits for the
magnitude and one
bit for the sign
Occupies 2 bytes.

15 bits for the
magnitude and one bit
for the sign
Occupies 1
byte.
Stores only
whole +ve
integers.


Numbers stored in integer datatypes, always occupy the same amount of storage
space, regardless of the number of digits within the allowable ranges for each integer
datatype.

For example if a column_name is defined as int , and assuming the value 1 is stored
into it, it will still occupy 4 bytes.
Numeric datatype
Numeric integer Numeric floating type
Exact numeric Approximate numeric
( int, smallint, tinyint)
(decimal, numeric) (real, float)
SQL SERVER 6.5
Chapter-2/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


EXAMPLE

CREATE TABLE tab1
( num1 int, num2 smallint, num3 tinyint)

INSERT into tab1
VALUES (400000000, 32767, 255) .

OUTPUT:

A single row is inserted into the table tab1
The values are within the acceptable range for storage of each datatype.



If the column values are outside the range of acceptable values, SQL Server returns an
error message.

EXAMPLE

CREATE TABLE tab1
( num1 int, num2 smallint, num3 tinyint)


INSERT into tab1
VALUES (1, 32768, 12)


OUTPUT:

INSERT statement will return an error message for the middle value i.e. 32768.

JUSTIFICATION:

The valid range for the smallint datatype is -32768 to 32767.



Numeric floating-point datatypes

Unlike the integer datatypes, floating-point datatypes can store decimal numbers.
These are divided into two categories:

a) Exact numeric
b) Approximate numeric



SQL SERVER 6.5
Chapter-2/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Exact numeric

Consists of numeric data with accuracy preserved to the least significant digit.
Supports two exact numeric datatypes: decimal and numeric.
Both contain an integer component to the left of the decimal point and a fractional
component to the right of the decimal point.
Different from Approximate numeric (float and real) which can not store all decimal
numbers with complete accuracy.
Both decimal and numeric are identical in implementation.
decimal[(p[,s])] / numeric[(p[,s])]
Precision (p) specifies the maximum total number of digits that can be stored both to
the left and right of the decimal point.
Scale (s) specifies the maximum number of digits that can be stored to the right of the
decimal point.
If the default and scale are not specified, the default precision SQL Server uses is 18
and the default scale is 0.
However, maximum precision that SQL Server normally supports is 28, which can be
changed.
These datatypes hold values from 10
38

-1 through -10
38
.
Storage size varies based on the specified precision.
Precision Storage bytes
1-2 2
3-4 3
5-7 4
8-9 5
10-12 6
13-14 7
15-16 8
17-19 9
20-21 10
22-24 11
25-26 12
27-28 13
29-31 14
32-33 15
34-36 16
37-38 17






SQL SERVER 6.5
Chapter-2/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


EXAMPLE

This example shows the default precision and scale and an explicit precision and scale being displayed.

CREATE TABLE ex_num
(n1 decimal, n2 numeric(7,6))

INSERT INTO ex_num
VALUES(123456789123456789, 2.222222)

SELECT * FROM ex_num

OUTPUT:

n1 n2
------------------ -------------------
123456789123456789 2.222222



Approximate numeric

float[(n)] real
Has 15-digit precision Has 7-digit precision
Range is 1.7E-308 through 1.7E+308 Range is 3.4E-38 through 3.4E+38
Storage size is 8 bytes Storage size is 4 bytes
If in float the precision is from 1 through 7, it is another name for the real datatype.

EXAMPLE

create table app_num
(n1 real, n2 float)

insert into app_num
values(1000000.1111, 1000000.1111)

select * from app_num

OUTPUT:

n1 n2
---------- -----------
1000000.0 1000000.1111


SQL SERVER 6.5
Chapter-2/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Monetary datatypes
Consists of numeric data for decimal currency.

money smallmoney

Valid range is -922337203685477.5808
to 922337203685477.5807
Valid range is -214748.3648 to
214748.3647
Storage size is 8 bytes ( integer portion +
decimal fraction portion )
Storage size is 4 bytes

Monetary data is preceded by a $ sign.
Commas are not allowed while inputting the currency.
The $ sign is not displayed in the output.
Negative values are entered by placing a (-) sign after the $ sign.


EXAMPLE

Example 1

Values inserted without $ sign.

CREATE TABLE money_table
( money1 money, money2 smallmoney)

INSERT into money_table
values( 922337203685476., 0)

OUTPUT:

The value of money1 will be 922337203685475.98 (Error)
The value of money2 will be 0.00.

Example 2

Values inserted with $ sign.

CREATE TABLE money_table
( money1 money, money2 smallmoney)

INSERT into money_table
values( $922337203685476., $0)

OUTPUT:

The value of money1 will be 922337203685476.00
The value of money2 will be 0.00.

SQL SERVER 6.5
Chapter-2/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


While displaying, monetary values are displayed to the two decimal places ( to the
nearest cent.)


EXAMPLE

CREATE TABLE money_table
( money1 money, money2 smallmoney)

INSERT into money_table
values( $922337203685477.5807, $214748.3647)

OUTPUT:

The value of money1 will be 922337203685477.58
The value of money2 will be 214748.36



Special datatypes

Special datatype consists of datatypes with a distinct or special use.
Examples of special datatype

(a) bit datatype
(b) timestamp datatype

bit datatype

Used to store information that can be represented in two states.
Stored in a single bit, although storage allocated is one byte.
Two possible patterns can be used.( 0 or 1 )
The values other than 1 or 0 are accepted but interpreted as 1.
Column of type bit cannot be NULL.
Multiple bit type in a table can be collected into bytes. For example, 7-bit columns
can fit into a byte; 9 bit columns will take 2 bytes. These bit columns dont have to be
contiguous.

timestamp datatype

A datatype that is automatically updated every time a row containing a timestamp
column is inserted or updated.
Value cannot be entered explicitly into the column defined as timestamp.
Values are not datetime data but are binary (8) , varbinary(8) data.
It has no relation to the system time.
SQL SERVER 6.5
Chapter-2/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
It is a monotonically increasing counter whose values will always be unique within a
database.
The timestamp column specifies the sequence of operations that SQL Server has
performed.
A table can only have one timestamp column.
Used to ensure that a row can uniquely be identified.
If a column is named timestamp, and datatype is not specified, it is automatically
defined as a timestamp datatype.
A column can be created with the name timestamp and any other datatype can be
assigned.
Text and image datatypes
Used to store large amounts of character or binary data.
The non-null text or image data value is stored in fixed length strings of characters in
an initially allocated 2K (2048 bytes) units.
Additional 2K units are dynamically added and linked together.
To save storage space, place a NULL value in the column, this will not allocate even
a single 2K page.
A text or image column contains NULL or a pointer (assigned at initialization) to the
first page for that entry.

text datatype

Used to store large amounts of text.
It can hold as many as 2
31
- 1 characters.
To enter the data, initialize the column by providing a non-null data with an INSERT
statement. Initialization causes a 2K data page to be allocated.
Then use the following statements as per the requirement:
READTEXT - to read the data
WRITETEXT - to write the data
UPDATETEXT - to modify the data
When text data is displayed with a SELECT statement, data is translated to ASCII
representation.

SELECT statement returns data upto the limit specified in the global variable
@@TEXTSIZE. Use the following statement to check the limit:
SELECT @@TEXTSIZE

The following statement can be used to change the limit:
SET TEXTSIZE number

Note: The maximum value that can be set is 2
31
- 1
SQL SERVER 6.5
Chapter-2/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


EXAMPLE

READTEXT statement

DECLARE @var varbinary(16) /* declares a variable of
varbinary datatype */

SELECT @var = TEXTPTR(pr_info) /* Places the pointer to the
FROM pub_info WHERE pub_id = 0736 variable var of the row
whose pub_id number is
0736 */

READTEXT pub_info.pr_info @var 1 25 /* Selects upto the twenty-
fifth character of the
pr_info column in the
pub_info table. */

WRITETEXT statement

DECLARE @var varbinary(16) /* declares a variable of
varbinary datatype */

SELECT @var = TEXTPTR(pr_info) /* Places the pointer to the
FROM pub_info WHERE pub_id = 0736 variable var of the row
whose pub_id number is
0736 */

WRITETEXT pub_info.pr_info @var /* Places the new text string
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aa.... into the row
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa pointed to by @var */
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

UPDATETEXT statement

DECLARE @var varbinary(16) /* declares a variable of
varbinary datatype */

SELECT @var = TEXTPTR(pr_info) /* Places the pointer to the
FROM pub_info WHERE pub_id = 0736 variable var of the row
whose pub_id number is
0736 */

UPDATETEXT pub_info.pr_info @var /* Replaces the 10th and 11th
10 2 bb character with bb */


image datatype

Used to store large bit patterns from 1 to 2
31
- 1 bytes in length.
Data such as employees photo, pictures, or drawings can be stored.
SQL SERVER 6.5
Chapter-2/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Data in image column is typically not entered with an INSERT statement.
When image data is displayed with a SELECT statement, data is not translated from
its ASCII representation. It can be passed on to another program that processes the
data on the client system, before it is displayed.

Text and image columns cannot be used:
as local variables
in ORDER BY, COMPUTE and GROUP BY clause
in an index
in a WHERE clause (with the exception of text datatype, that can be specified with
LIKE keyword in a WHERE clause )

User defined datatypes

A user can define his own datatype, which can then be used as a datatype for a
storage structure such as a table column.
A user defined datatype is defined by the user for a specific database.
It is defined in terms of system-supplied datatypes.
Each user-defined datatype is added as a row in the system table called systypes. (See
session 9 for details on system tables.)


Creating user -defined datatype

A user-defined datatype enables to define a datatype that can contain a length
specification and a NULL characteristic.

User-defined datatype can be created with the system stored procedure sp_addtype.

System stored procedure are routines or procedures that run on the server, which consists
of precompiled collection of SQL statements. They can be used for administering and
managing the Server and performing certain tasks.

Note: Details about System stored procedures are covered later.

Syntax:

sp_addtype user_defined_datatype_name, system_data_type, [ NULL | not NULL ]

SQL SERVER 6.5
Chapter-2/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


EXAMPLE

sp_addtype names , char(5), NULL

OUTPUT:

A user-defined datatype called names is created.
The length will always be 5 and null values are allowed.


A user-defined datatype must be unique in the database.
User-defined datatypes with different names can have the same definition.


Dropping the user-defined datatypes

User-defined datatypes can be dropped by using the system procedure sp_droptype.


Syntax:

sp_droptype user_defined_datatype_name

EXAMPLE
sp_droptype names

OUTPUT:

The user-defined datatype names is dropped.


The user-defined datatype can be dropped only if it is not in use by any of the tables.


Creating tables with fields of different datatypes

SQL Server database tables can be created using:

(a) Transact-SQL
(b) Using SQL Enterprise Manager

SQL SERVER 6.5
Chapter-2/20
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Creating tables using Transact-SQL

Using Transact-SQL, tables can be created using the CREATE TABLE statement.


CREATE TABLE

Syntax:

CREATE TABLE [database .[ owner. ]] table_name
( column_name datatype [constraint ]
[, column_name datatype [ constraint ] ] ...)

Note : Constraints will be discussed in detail in later sessions.

When creating tables, consider the following

(a) Table name must be unique within the database.
(b) Column names must be unique within a given table
(b) A datatype must be named for each column.

EXAMPLE

sp_addtype emp_no, char(4), NOT NULL

CREATE TABLE emp
(
emp_no emp_no,
lastname varchar(10) NOT NULL,
firstname varchar(10) ,
salary int
)

OUTPUT:

A table called emp is created.
The field emp_no is of the user-defined datatype emp_no and the value cannot be null.
The field lastname is a variable character string which can not be null.
The field firstname is a variable character string which can not be null ( Default is NOT NULL)
The field sa1lary is of the type int.
SQL SERVER 6.5
Chapter-2/21
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Dropping tables
A table can be removed from the database, if it is no longer needed by dropping it.
A table can be dropped by using one of the following methods:
By using SQL Enterprise Managers server window, select the table to drop, click the
right mouse button and choose drop.
Use the DROP TABLE statement.
Syntax:
DROP TABLE table_name [, table_name]
EXAMPLE
DROP TABLE tab1
OUTPUT:
Drops the table called tab1 from the current database.
When a table is dropped, all its contents, indexes and permissions associated with it
are removed.
Altering a table
After the creation of a table, its structure can be changed by adding columns. To change a
table, the definition of the table is altered.
Table defintion can be altered by using ALTER TABLE statement.
Syntax:
ALTER TABLE [database.[owner].] table_name
ADD
{ column_name datatype [constraints] }
[, { column_name datatype [constraints] }...]
EXAMPLE
ALTER TABLE tab1
ADD
col1 varchar(10) NULL
SQL SERVER 6.5
Chapter-2/22
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OUTPUT:
Adds a new column called col1 to the table tab1 of the datatype varchar which allows null.
ALTER TABLE does not allow columns to be removed.
Columns added to the table must be defined as NULL.
Temporary tables
SQL Server supports two types of temporary tables:
Local temporary table Global temporary table
Visible only to the connection that
created the table.
Available to all the connections.
Only the owner of the table (who
creates the table) can access the table.
All users can access this table.
Automatically dropped at the end of
the current session.
Dropped at the end of the last session
using the table.
Signified in the CREATE TABLE
statement by preceding the table name
with a single # sign. (#table_name)
Signified in the CREATE TABLE
statement by preceding the table name
with a ## sign. (##table_name)
Syntax:
CREATE TABLE #[#] table_name
(col_definition [, col_defintion]...)
Frequently used system stored procedures with tables
sp_help
Syntax:
sp_help [object_name]
sp_help reports information about database objects or SQL Server supplied or user
defined datatypes
SQL SERVER 6.5
Chapter-2/23
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
Example 1
sp_help
OUTPUT:
Lists information about each object in database.
All user tables present in a database can be found out.
name owner object_type
----------- ----------- ---------------
tab1 dbo user table
tab2 dbo user table
detail_insert dbo trigger
syscolumns dbo system table
: : :
Example 2
sp_help tab1
OUTPUT:
Displays information about the tab1 table.
name owner object_type when_created
----------- --------- -------------- ---------------------
tab1 dbo user table Dec 24 1997 11:30 AM
data_located_on_segment
------------------------
default
column_name type length .....
------------- ------- -------- .....
roll_no char 2 .....
name varchar 10 .....
class char 2 .....
identity seed increment
------------------------- ------- ----------
no identity value defined (null) (null)
Object does not have any indexes.
No constraints have been defined for this object.
No foreign keys reference this table.
SQL SERVER 6.5
Chapter-2/24
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
sp_rename
Syntax:
sp_rename object_name, new_name [, COLUMN]
Changes the name of a user-created object. For example, it can be used to change the
name of the table or the name of the column of a table.
EXAMPLE
Example 1
sp_rename tab1, table1
OUTPUT:
Renames the table called tab1 to table1.
Example 2
sp_rename tab2.no, rollno, COLUMN
OUTPUT:
Renames the no column in table tab2 to rollno.
While renaming a column, it must be in the form table.column.
CLASSROOM EXERCISE
1. What are exact and approximate numeric data?
2. Which system stored procedure is used to define the datatypes?
3. Can length be specified for a user-defined datatype in a CREATE TABLE
statement?
4. Are identical user-defined datatype names with only differing
capitalization with the system defined datatypes allowed for user-defined
datatypes?
SQL SERVER 6.5
Chapter-2/25
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
THE SELECT STATEMENT
Data can be retrieved from the tables quickly and easily using queries.
Simple SELECT statement
A SELECT statement is used to retrieve data from a table of the database. It acts like a
filter superimposed on a database table.
It can be used for :
Selections - Retrieving a subset of the rows in one or more tables
Projections - Retrieving a subset of the columns in one or more tables
There are two keywords that make up the primary SELECT statement:
(a) SELECT
(b) FROM
A SELECT statement specifies the columns to be retrieved.
The FROM clause specifies the tables from which rows and columns are included in a
query.
Syntax:
SELECT column_name [, column_name...]
FROM table_name
Parameters Description
column_name Specifies the name of the column that is to be retrieved from a particular
table.
table_name Specifies the name of the table from which the data is to be retrieved
SQL SERVER 6.5
Chapter-2/26
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Rules for the simple SELECT statement
Column names follow the SELECT keyword.
Column names are separated by comma.
There is no comma following the last column name.

EXAMPLE
Example 1

SELECT pub_id, pub_name FROM publishers


OUTPUT:

Selects the pub_id, pub_name of each publisher from the publishers table.
Other information about the publishers such as city, state etc. stored in the publishers table is not
displayed.

Note: The table structures for the pubs database can be referred to in the Appendix A.

OUTPUT:

pub_id pub_name
------ ---------------------
0736 New Moon Books
0877 Binnet & Hardley
1389 Algodata Infosystems
: :



SELECT *

All columns in a table can be selected from a table by using a * in place of list of the
column names.

Syntax:

SELECT * FROM table_name

The result will display columns in the order listed in the CREATE TABLE statement.





SQL SERVER 6.5
Chapter-2/27
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.



EXAMPLE

SELECT * FROM publishers


OUTPUT:

All the fields from the table publishers are displayed i.e. all the information about every publisher is
displayed.

pub_id pub_name city state country
------ -------- -------- -------- ---------
0736 New Moon Books Boston MA USA
0877 Binnet & Hardley Washington DC USA
1389 Algodata Infosystems Berkeley CA USA
: : : : :





Rearranging the order of the columns

The order in which the column names are listed in the SELECT statement determines the
order in which the columns appear in the result.

EXAMPLE
SELECT pub_name, pub_id, city FROM publishers

OUTPUT:

Returns a list of members in the order of pub_name, pub_id , city though the order of the columns in
the table publishers is pub_id, pub_name, city...


pub_name pub_id city
-------- -------- ---------
New Moon Books 0736 Boston
Binnet & Hardley 0877 Washington
Algodata Infosystems 1389 Berkeley
: : :







SQL SERVER 6.5
Chapter-2/28
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Changing column headings


By default, the column headings displayed in the results are the names designated to
the columns when the table was created.
However, it is possible to change the name of the column headings appearing in the
result.
Changing the column headings is called aliasing.
Column headings are changed to make the results more readable.
The changed column heading is not reflected in the table.
It is just in the result where instead of the original column name, the column alias
appears as the column heading.


Syntax:

SELECT column_heading = column_name [, column_name] FROM table_name

OR

SELECT column_name column_heading [, column_name...] FROM table_name


EXAMPLE


SELECT pub_id, PUBLISHER = pub_name FROM publishers

OUTPUT:

The column heading of the column name pub_id remains same as the original column name.
The column name pub_name is displayed under the heading PUBLISHER.

pub_id PUBLISHER
------ ---------------------
0736 New Moon Books
0877 Binnet & Hardley
1389 Algodata Infosystems
: :






SQL SERVER 6.5
Chapter-2/29
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Using literals

Strings called literals can be used to make the results of a SELECT statement more
readable.

The strings are enclosed in single quotes and are printed exactly as they appear.


Syntax:

SELECT column_name | string_literal [ column_name | string_literal ...]
FROM table_name


EXAMPLE

SELECT Pub No:, pub_id, pub_name FROM publishers


OUTPUT:

The literal Pub No: is printed against each of the Publisher Id.
pub_id pub_name
------- ------ ---------------------
Pub No: 0736 New Moon Books
Pub No: 0877 Binnet & Hardley
Pub No: 1389 Algodata Infosystems
: : :

SQL SERVER 6.5
Chapter-2/30
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
MANIPULATION OF DATA USING FUNCTIONS
Transact-SQL contains numerous functions to analyze and manipulate the table data.
Functions return special information from the system about users, expressions, a
database or database objects and so on.
They execute a section of code that performs an operation , which returns a desired
value.
Functions fall into the following categories:
Mathematical functions
String functions
Date functions
System functions
Conversion function

Mathematical functions

These functions perform operations on numeric datatypes such as integer, float, real,
decimal, numeric, money or smallmoney.

Syntax:

SELECT function_name (parameters)

Function Parameters Results

ABS (numeric_expression) Returns the absolute value.
ACOS, ASIN,
ATAN, ATN2
(float_expression) Returns angle in radians whose cosine, sine
or tangent is floating point value.
COS, SIN, COT,
TAN
(float_expression) Returns cosine, sine, cotangent, or tangent
of the angle in radians.
CEILING (numeric_expression) Returns the smallest integer greater than or
equal to the specified value.
DEGREES (numeric_expression) Converts from radians to degrees
EXP (float_expression) Returns the exponential value of the
specified value.
FLOOR (numeric_expression) Returns the largest integer less than or
equal to the specified value
LOG (float_expression) Returns the natural logarithm of the
specified approximate numeric.
LOG10 (float_expression) Returns the base 10 logarithm of the
specified approximate numeric.

SQL SERVER 6.5
Chapter-2/31
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Functions Parameters Results
PI ( ) Returns the constant value
3.141592653589793
POWER (numeric_expression,y) Returns the value of numeric expression to
the value of y.
RADIANS (numeric_expression) Converts from degrees to radians
RAND ([seed]) Returns a random float number between 0
and 1, optionally specifying an integer
expression as the seed.
ROUND (numeric_expression,
length)
Returns a numeric expression rounded off to
the length specified as an integer
expression.
SIGN (numeric_expression) Positive, negative or zero.
SQRT (float_expression) Returns the square root of the specified
value.

Following should be considered when using mathematical functions:

Monetary datatype should always be preceded with a dollar ($) sign. If dollar sign is
not put, the value is treated as a numeric with a scale of 4.
Floating point constants can be entered as decimal values or in exponential notation.
Integer values are entered as integers.


EXAMPLES

Example 1

SELECT FLOOR($81.45), FLOOR(81.45), FLOOR($-81.45)

OUTPUT:

----- ----- -----
81.00 81 -82.00

( 1 row(s) affected)


Example 2

SELECT CEILING(-81.45), CEILING($81.45), CEILING($-81.45)

OUTPUT:
----- ----- -----
-81 82 -81.00

( 1 row(s) affected)


Example 3
SQL SERVER 6.5
Chapter-2/32
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

SELECT round(23.777770), round(12.3, -2), round(23.77777, 2)

OUTPUT:

-------- ------- --------
24.00000 0.00 23.78000

( 1 row(s) affected )


Example 4

SELECT power(2,3), sqrt(49), rand()

OUTPUT:

------- ------- ------------------
8 7.0 0.350291451765496

( 1 row(s) affected )





Manipulation of the numeric data using arithmetic expressions

An expression is made up of column names and constant numeric values connected by
one of the arithmetic operators.

Arithmetic expressions can appear in the list of columns in the SELECT clause.

Arithmetic operators

Operator Operation Can be used with

+ Addition int, smallint, tinyint, numeric, decimal, float, real, money
and smallmoney
- Subtraction int, smallint, tinyint, numeric, decimal, float, real, money
and smallmoney
/ Division int, smallint, tinyint, numeric, decimal, float, real, money
and smallmoney
* Multiplication int, smallint, tinyint, numeric, decimal, float, real, money
and smallmoney
% Modulo int, smallint and tinyint


Note: The modulo (the integer remainder after integer division) cannot be performed on
money, smallmoney, float, or real datatypes.
SQL SERVER 6.5
Chapter-2/33
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

EXAMPLE

SELECT title_id, price, INCREASED_PRICE = (price * 1.1) FROM titles

OUTPUT:

Displays the title_id of the book, price for each of the book in the titles table and what it would be, if
cost is increased by 10 percent.

title_id price INCREASED_PRICE
-------- -------- ----------------
BU1032 19.99 21.98
BU1111 11.95 13.14
BU2075 2.99 3.28
: : :




Operator precedence

Operator precedence (the order of evaluation of operators) must be considered when
multiple operators are combined.

Operator precedence determines which computations or comparisons are performed first.

Operators have the following precedence:

Primary grouping ( )

Mulitplicative * / %

Additive + -

The operators in an expression having the same level of precedence are evaluated from
left to right. Expressions within parentheses take precedence over all other operations.

SQL SERVER 6.5
Chapter-2/34
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Manipulation of the character data using string functions

String functions are used to return values commonly needed for operations on character
data. Character data consists of any combination of letters, symbols and numbers.

String functions are usually used on char, varchar, binary and varbinary datatypes, as
well as datatypes that implicitly convert to char or varchar.

String functions can be nested , such that results returned by the inner function are
available for the operation performed by the outer function.

Constants used with the string functions are enclosed in quotation marks.

String functions are usually used in SELECT clause.

Function Parameters Result

ASCII (char_expression) Returns the ASCII code value of the
leftmost character of the character
expression.
CHAR (integer_expression) Returns the character equivalent of the
ASCII code value.
CHARINDEX (pattern, expression) Returns the starting position of the
specified pattern in the expression.
DIFFERENCE (char_expr1, char_expr2) Compares the two strings and evaluates
the similarity between them, returning a
value from 0 through 4. The value 4 is the
best match.
LOWER (char_expression) Converts the character expression to
lowercase.
LTRIM (char_expression) Returns data without the leading blanks
PATINDEX (%pattern%, expression) Returns the starting position of the first
occurrence of pattern in the specified
expression or zeroes if the pattern is not
found.
REPLICATE (char_expr, integer_expr) Repeats a character expression a specified
number of times.
REVERSE (char_expression) Returns the reverse of the character
expression.
RIGHT (char_expr, integer_expr) Returns a part of the character string
starting integer_expr characters from
right.
RTRIM (char_expression) Returns data without trailing blanks.
SQL SERVER 6.5
Chapter-2/35
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.



SOUNDEX (char_expression) Returns a four digit code to evaluate the
similarity of two character strings.
SPACE (integer_expression) Returns a string of spaces for the length
specified by the integer_expression.
STR (float_expr [, length
[, decimal ]] ))
Returns character data converted from
numeric data.
STUFF (char_expr1, start, length,
char_expr2)
Deletes length characters from expression
1 at start and then inserts expression 2
into expression 1 at start.
SUBSTRING (expr, start, length) Returns a part of a character from start of
the length specified by length.
UPPER (char_expression) Converts lowercase character data to
uppercase.


EXAMPLES

Example 1

ASCII function

SELECT ASCII (Andrews)

OUTPUT:

The ASCII code value is returned for the leftmost character in the character expression
The ASCII code value of the character expression Andrews is returned as 65 being A as the
leftmost character.

Example 2

CHAR function

SELECT CHAR(65)

OUTPUT:

The character value is returned for ASCII code.
The character value of the ASCII code is returned as A being 65 its ASCII code.
If ASCII code is outside the range of 0 to 255, a NULL is returned.

Example 3

Concatenation

SELECT name = (first_name + , + last_name)

OUTPUT:
Creates a single column consisting first_name, followed by the last_name separated by a comma
SQL SERVER 6.5
Chapter-2/36
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Example 4
STUFF function
SELECT STUFF(1234567, 3, 2, xxxx)
OUTPUT:
The resulting string will be 12xxxx567.
Example 5
SPACE function
SELECT Member No: + space (2), mem_no FROM member
OUTPUT:
mem_no
---------------------------
Member No: M001
Member No: M002
:
Example 6
SUBSTRING function
SELECT a = SUBSTRING(abcdefg,3,2)
OUTPUT:
a will have the string cd assigned to it.
The SUBSTRING function will extract two characters from the third position of the string abcdefg.
Example 7
CHARINDEX function
SELECT CHARINDEX(cd, abcdefg)
OUTPUT:
Returns 3, because the pattern cd starts from the third position in the string abcdefg.
The pattern used in CHARINDEX function is a literal string (no wildcard character are allowed).
SQL SERVER 6.5
Chapter-2/37
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Date functions
Allow manipulation of datetime values.
Can be used in the select_list in the WHERE clause, or wherever an expression is
used.
Datetime values should be enclosed in quotes.
Some functions take datepart as parameter, such as year, month, hour or second.
Syntax:
SELECT date_function(parameters)
Function Parameters Results
DATEADD (datepart, no, date) Adds the no. of dateparts to the date
DATEDIFF (datepart, date1, date2) Number of date parts between two dates
DATENAME (datepart, date) Specified datepart for the listed date, returned
as an ASCII value (e.g. July)
DATEPART (datepart, date) Specified datepart for the listed date, returned
as an integer value(e.g. 7)
GETDATE ( ) Current date and time in internal format.
The following table lists the dateparts, abbreviations and acceptable values.
Datepart Abbreviation Values
year yy 1753-9999
quarter qq 1-4
month mm 1-12
day of year dy 1-366
day dd 1-31
week wk 0-51
weekday dw 1-7 (1-Sunday)
hour hh 0-23
minute mi 0-59
second ss 0-59
millisecond ms 0-999
SQL SERVER 6.5
Chapter-2/38
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
Example 1
SELECT GETDATE()
OUTPUT:
Displays the current date and time in SQL Server format for datetime values.
Example 2
SELECT pubdate, DATEDIFF(MONTH, pubdate, GETDATE())
FROM titles
OUTPUT:
Shows the pubdate and how many months ago each book was published.
Example 3
SELECT title_id, pubdate, DATEADD(DAY, 4, pubdate)
FROM titles
OUTPUT:
Shows all titles with their publication dates and the dates as if they had slipped four days.
System functions
Provide a short hand method of querying system.
Syntax:
SELECT function_name(parameters)
Function Parameters Results
COALESCE (expr1, expr2, exprn) Returns the first non-null
expression.
COL_NAME (tableid, column_id) Returns the column name.
COL_LENGTH (table_name, column_name) Returns the column length
DATALENGTH (expression) Returns the actual length of an
expression of any datatype
DB_ID ([databasename]) Returns the database id.
DB_NAME ([database_id)] Returns the database name
GETANSINULL ([databasename]) Returns the default nullability for
the database
SQL SERVER 6.5
Chapter-2/39
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
HOST_ID () Returns the host process ID#
HOST_NAME () Returns the current host
computer name
IDENT_INCR (table_name) Returns the increment value
specified during creation of an
identity column.
IDENT_SEED (table_name) Returns the seed value specified
during creation of an identity
column.
INDEX_COL (table_name, index_id, key_id) Returns the indexed column
name
ISDATE (variable | column_name) Checks a variable or column
with the varchar datatype for a
valid dateformat
ISNULL (expression, value) Returns a specified value in
place of NULL.
ISNUMERIC (variable | column_name) Checks a variable or column
with varchar datatype for a valid
numeric format.
NULLIF (expr1, expr2) Returns the resulting expression
as NULL when expr1 is
equivalent to expr2
OBJECT_ID (object_name) Returns the object_id
OBJECT_NAME (object_id) Returns the object name.
STATS_DATE (table_id, index_id) Returns the date that the
statistics for the specified index
were last updated.
SUSER_ID ([server_username]) Returns the server users ID
SUSER_NAME ([server_user_id]) Returns the server user name
USER_ID ([username]) Returns the users ID number
USER_NAME ([user_id]) Returns the users name.
EXAMPLES
Example 1
SELECT USER_ID(Dilton)
OUTPUT:
Returns Diltons identification number, 12.
SQL SERVER 6.5
Chapter-2/40
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Example 2
SELECT USER_NAME(12)
OUTPUT:
Returns username for the user number 12, Dilton.
Example 3
SELECT AVG(ISNULL(price, $20.00)) FROM titles
OUTPUT:
Substitutes the value $20.00 for all null entries in price column and then finds the average of all the
prices in titles table.
Example 4
SELECT length = DATALENGTH(au_lname) FROM authors
OUTPUT:
Finds the length of the field au_lname in the authors table.
Data Conversion
Allows to convert expressions from one datatype to another.
Allows you to format dates in a variety of styles.
Can be used in the select_list, WHERE clause or anywhere that expressions are
allowed.
Syntax:
CONVERT (datatype [(length)], expression [, style])
datatype
Any system datatype into which the expression is to be converted. User-defined
datatypes cannot be used.
expression
A column name, function, constant, combination of column names, constants and
functions connected by operators.
SQL SERVER 6.5
Chapter-2/41
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
style
Style of date representation when converting date type data to character data.
In the following table first two columns represent the style values. Use the second column
as style to get a four-place year that includes century.
Without
century (yy)
With century
(yyyy)
Standard Date format output
- 0 or 100 Default mon dd yyyy hh:mi AM
(PM)
1 101 USA mm/dd/yy
2 102 ANSI yy.mm.dd
3 103 British/French dd/mm/yy
4 104 German dd.mm.yy
5 105 Italian dd-mm-yy
6 106 - dd mon yy
7 107 - mon dd, yy
8 108 - hh:mi:ss
- 9 or 109 Default +
milliseconds
mon dd, yyyy hh:mi:ss:ms
AM
10 110 USA mm-dd-yy
11 111 Japan yy/mm/dd
12 112 ISO yymmdd
- 13 or 113 Europedefault +
milliseconds
dd mon yyyy hh:mi:ss:ms
14 114 - hh:mi:ss:ms
EXAMPLE
Example 1
SELECT CONVERT(char(12),GETDATE(), 2)
OUTPUT:
Converts the current date to style 2, yy.mm.dd
SQL SERVER 6.5
Chapter-2/42
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Example 2
SELECT The price for + CONVERT(char(40), title) +
is $ + CONVERT(varchar(10), price) FROM titles
OUTPUT:
The price for The Busy Executives Database Guide is $19.99
The price for Cooking with Computers: Surrepititious is $11.95
:
:
The following table shows the possible datatype conversions:
To
From
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1 - I I I I N N I I I N I N N N I E E
2 I - I I I N N I I I N I N N N I E E
3 I I - I I I I E E I I I N N N N I I
4 I I I - I I I E E I I I N N N N I I
5 I I I I - I I E E I I I N N N N I I
6 N N I I I - I E E I I I N N N N I I
7 N N I I I I - E E I I I N N N N I I
8 E E E E E E E - I E E E I I I I E E
9 E E E E E E E I - E E E I I I I E E
10 I I I I I I I E E - I N N N N I I
11 I I I I I I I E E I - I N N N N I I
12 I I I I I I I I I N N - N N N N I I
13 E E N N N N N I I N N N - I N N N N
14 E E N N N N N E E N N N I - N N N N
15 N N N N N N N E E N N N N N - N N N
16 E E N N N N N N N N N N N N N - N N
17 I I I I I I I E E I I I N N N N - *
18 I I I I I I I E E I I I N N N N * -
1 - binary, 2 - varbinary, 3 - tinyint, 4 - smallint, 5 - int, 6 - float, 7 - real, 8
- char, 9 - varchar, 10 - money, 11 - smallmoney, 12 - bit, 13 - datetime,
14 - smalldatetime, 15 - text, 16 - image, 17 - decimal, 18 - numeric.
I Implicit conversion
E Explicit conversion, CONVERT function must be used.
N Converion not allowed.
* Converting from decimal or numeric to decimal or numeric requires CONVERT
when a loss of precision or scale will occur.
- Conversion of a datatype to itself; allowed but meaningless.
SQL SERVER 6.5
Chapter-2/43
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CLASSROOM EXERCISES
1. What are the different ways in which you can manipulate how columns are
displayed in a SELECT statement.
2. What is the difference between a charindex and a patindex function.
3. When a smalldatetime value (accuracy to the minute) is used with datepart,
what value is shown ?
SQL SERVER 6.5
Chapter-2/44
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LAB EXERCISES
1. Create the following user-defined datatypes:
a) mem_num as character field of 4 bytes that does not allow NULLs.
b) short_string as variable character of maximum length 20 bytes which
allows nulls.
c) bday as datetime that allows NULL.
2. Drop the user-defined datatype short_string.
3. Create a table called member which should have following fields:
Mem_no ------> of user-defined datatype mem_num
Mem_name --------> of variable character of length 20.
B_date ---------> of user-defined datatype bday.
4. Alter the table by adding one more column called level of integer type
5. Drop the above table.
6. Create the same table using the Enterprise Manager.
7. Rename the table member to mem.
8. Display the structure of the table mem.
9. Use the pubs database for the following:
a) Write SELECT statement which retrieves all the data from the titles table.
b) Write SELECT statement which will retrieve title, type, price from the
titles table.
c) Write the above query so that results set has the following format:
title price
-------- -------- ------- ------
title is: price is:
title is: price is:
d) Use a column alias to set up a new column header for the computed
column (10% discounted price). Display the title and the original price
also.
10. Display the current month name under the heading Month Name.
11. Display the current date in the style dd mon yyyy hh:mi:ss:ms.
12. Try out the examples given in the book.
SQL SERVER 6.5
Chapter-2/45
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
A table is a set of related information stored in a database.
A table is created using CREATE TABLE statement.
There are two types of datatypes:
a) System defined
b) User defined
User defined datatypes are created using the system stored procedure sp_addtype and are
dropped using the system stored procedure sp_droptype.
There are two types of temporary tables:
a) Local - Visible only to the connection that created the table.
b) Global - Available to all the connections.
sp_help and sp_rename system stored procedures can be used with tables.
Tables are dropped using DROP TABLE command and can be altered using ALTER
TABLE command.
SELECT statement is used to retrieve the data from the tables.
The data in the table can be manipulated using various type of functions:
Mathematical functions
String functions
Date functions
System functions
Conversion function
SQL SERVER 6.5
Chapter-3/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Advanced retrieval queries
SCOPE
Retrieving selected rows
Sorting results
Eliminating duplicates
Generating summary data
Aggregate functions
GROUP BY, HAVING
COMPUTE, COMPUTE BY
ROLLUP, CUBE
Correlating data using joins
INNER JOIN
CROSS JOIN
OUTER JOIN
SELF JOIN
SQL SERVER 6.5
Chapter-3/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
RETRIEVING SELECTED ROWS
Often, all the rows in a table are not required to be retrieved; only the rows that satisfy
one or more conditions are required.
In this case, the SELECT statement includes a WHERE clause, to retrieve a portion or
subset of the row in a table, based on given search conditions.
A search condition expresses the logic by which computer determines which rows of the
table are retrieved.
DIAGRAM
TABLE
COLUMN1 COLUMN2 COLUMN3
1
- -
2
- -
: : :
6
- -
COLUMN1 COLUMN2 COLUMN3
2 - -
Search conditions include:
Comparison operators =, >, <. >=, <=, <>, !=, !<, !>
Ranges BETWEEN, NOT BETWEEN
Lists IN, NOT IN
String matches LIKE, NOT LIKE
Unknown values IS NULL, IS NOT NULL
Combination of these AND, OR
Negations NOT
Assuming only one record matches the search
condition, only that record is retrieved.
SELECT select_list
FROM table
WHERE search_condition
SQL SERVER 6.5
Chapter-3/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Retrieving rows based on comparisons
Comparison operators allow to SELECT rows by comparing a column of a row to a given
value or expression.
The following table shows the comparison operators:
Operator Description
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> != Not equal to
!> Not greater than
!< Not less than
( ) Controls precedence
Syntax:
SELECT column_name [, column_name...]
FROM table_name [, table_name...]
WHERE expression comparison_operator expression
Guidelines for using comparison operators:
Expression is a constant, column_name, function, sub-query or any combination of
them connected by arithmetic operators ( *, +, _ etc. ) or the operators AND, OR,
NOT.
Output for statements involving comparison operators depends on the sort order
(ascending or descending) chosen during installation. For example, in comparing char
and varchar data, < means earlier in the installed sort order and > means later.
Trailing blanks are ignored in comparisons i.e. abcd and abcd are equivalent.
While using comparison operators, the data with datatype char, varchar, text,
datetime and smalldatetime should be enclosed in single quotes.

EXAMPLES

Example 1

SELECT *
FROM publishers
WHERE country = USA

Character constant enclosed in quotes.
( Search condition )
SQL SERVER 6.5
Chapter-3/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


OUTPUT:

All the publishers in the publishers table whose country is USA will be displayed with all the
information ( Pub_id, pub_name, city and state) .



Example 2

SELECT pub_name
FROM publishers
WHERE pub_name >= Binnet

OUTPUT:

Retrieves pub_name for the rows that are alphabetically greater than or equal to Binnet for the
pub_name field.


Example 3

SELECT title_id, increased_price = price * $2.00
FROM titles
WHERE price < $7.00

OUTPUT:

Displays the title_id and the increaed_price for those books whose prices are less than $7.00.


Example 4

SELECT title_id, title
FROM titles
WHERE pub_date > 30/06/91

OUTPUT:

Displays the title_id and title of the books whose pub_date is greater than 30th Jun, 91.













SQL SERVER 6.5
Chapter-3/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Retrieving rows based on ranges

BETWEEN operator allows to select rows of data such that data in a given column
contain values within a range.

The keyword BETWEEN is followed by
the beginning value
the keyword AND
the ending value

Syntax:

SELECT column_name [, column_name...]

FROM table_name [, table_name...]

WHERE expression [NOT] BETWEEN expression AND expression


Guidelines for using BETWEEN operator:

BETWEEN keyword specifies an inclusive range to search i.e. if either the minimum
value or the maximum value of the range is found, as well as any in between, the row
is returned.

EXAMPLE

SELECT pubdate, title FROM titles
WHERE pubdate BETWEEN 1/1/91 AND 12/31/91

OUTPUT:
Displays the pubdate and title of the book for all those books whose pubdate is of year 91.



Actual numbers forming the range of values need not be stored in the table.
Considering the above example, 1/1/91 and 12/31/91 dont need to be stored in the
table.
Exclusive range can be specified using > and < operator.
NOT BETWEEN finds rows outside the range which is specified .
While using comparison operators, the data with datatype char, varchar, text,
datetime and smalldatetime should be enclosed in single quotes.



SQL SERVER 6.5
Chapter-3/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Selecting rows based on lists

IN operator is used when rows are to be selected that match one of the several listed
values.

If the row value matches any value in the list of value, the row is selected.

IN defines a set by explicitly naming the members by the set in parentheses, separated by
comma.

NOT IN selects the rows that do not match items in the value list.

Syntax:

SELECT column_name [, column_name...]
FROM table_name [, table_name...]
WHERE expression [NOT] IN (value_list)

EXAMPLE

SELECT title, type FROM titles
WHERE type = mod_cook OR type = trad_cook

OUTPUT:
Displays the type and title of a book whose type is either mod_cook or trad_cook.

The results can be obtained by using IN operator in the following manner.


SELECT title , type FROM titles
WHERE type IN (mod_cook, trad_cook)






Selecting rows based on character strings

A column value that contains character values can be matched to a pattern of characters
for retrieving one or more rows from the table. This is referred as pattern matching.

Pattern consists of characters to be matched and wildcard characters.




list of values
SQL SERVER 6.5
Chapter-3/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Wildcard Description

% Any string of zero or more characters
_ Any single character
[] Any single character within the specified range or set.
[^] Any single character not within the specified range or set.

Wildcard characters can be combined and may be used more than once in the pattern.

LIKE operator is used to select rows containing fields that match the pattern.

Expression Returns

LIKE RE% All names beginning with RE
LIKE Re% All names beginning with Re
LIKE %ata All names ending with ata
LIKE %ee% All names having ee in the name
LIKE _ita All four letter names ending in ita
LIKE [RE]% All names beginning with R or E
LIKE [A-D]ata All four letter names beginning with any single letter from A to D
and ending in ata.
LIKE H[^c]% All names beginning with H not having a c as the second
character.

Syntax:

SELECT column_name [, column_name...]
FROM table_name [, table_name...]
WHERE expression [NOT] LIKE string

Wildcard and character strings are enclosed in single quotes.


EXAMPLE

Example 1

SELECT stor_name FROM stores WHERE stor_name LIKE %Book%


OUTPUT:

Displays all the store names which have the string Book in their name.


SQL SERVER 6.5
Chapter-3/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


stor_name
--------------------------
Eric the Read Books
Doc-U-Mat: Quality Laundry and Books
Fricative Bookshop


Example 2

SELECT au_lname FROM authors WHERE au_lname LIKE _e%

OUTPUT :

Displays all the au_lname from the table authors whose second letter in the name is e.

au_lname
-------------
Bennet
del Castillo
DeFrance



LIKE is used with char, varchar, text, datetime, smalldatetime.
Output depends on the sort order chosen during installation.
Wildcards used without LIKE are interpreted as literals rather than as patterns.
Search for the wildcard characters themselves can be done using square brackets.
When an expression is beginning with wildcard, an index can not be used. If the
given name is %abc, it wouldnt know where to start in the table, when the table
would be searched.


Choosing rows based on unknown values

A NULL means that a value for that column is unavailable or unknown.
To select rows with NULL values, the IS NULL keyword is used in the WHERE
clause.
NULL is not same as zero or blank.
Two NULLs are not equal to each other. Thus, they fail all kind of comparisons.
NULL will be the first to display in an ascending order in the output .

Syntax:

SELECT select_list
FROM table_list
WHERE column_name IS [NOT] NULL


SQL SERVER 6.5
Chapter-3/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

EXAMPLE

SELECT title FROM titles WHERE price IS NULL

OUTPUT:
Displays all the books where the price is not known.



Choosing rows based on several search arguments

Using logical operators such as AND, OR and NOT in the WHERE clause allows to
combine search arguments.
Arithmetic operators are handled before logical operators.
AND and OR are used to connect search expressions in the WHERE clause.
AND and OR join two or more expressions.
AND return results only when all of the conditions are true.
OR return results when either of the condition is true.
NOT negates the expression that follows it.
When more than one logical operator is used in a statement, NOT is evaluated first,
then AND, and finally OR.
Parentheses can be used to change the order .

Syntax:

SELECT select_list
FROM table_list
WHERE [NOT] expression { AND | OR } [NOT] expression

EXAMPLE

Example 1

SELECT pub_id, pub_name FROM publishers
WHERE (pub_name LIKE %pub% OR pub_name LIKE S%)AND(country = USA)

OUTPUT:
Displays the pub_id and pub_name of the publishers whose
name either starts with S or has the pattern pub in its name
and the country is USA.

Example 2

SELECT pub_id, pub_name FROM publishers
WHERE (pub_name LIKE %pub%) OR (pub_name LIKE S% AND country =
France)

SQL SERVER 6.5
Chapter-3/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

OUTPUT:

Displays the name of the publishers whose
either name consists of the string pub.
or, the name should start with S with the country France.




Eliminating duplicates


The default result shows all the rows which satisfy the WHERE clause.
If only distinct values are required for a particular combination of columns, the
keyword DISTINCT is used.

Syntax:

SELECT [ ALL | DISTINCT ] select_list
FROM table_name
WHERE search_conditions

EXAMPLE

SELECT DISTINCT country FROM publishers

OUTPUT:
Only distinct countries are displayed from the table publishers.



Sorting the Results

For sorting the query results set on one or more columns , the ORDER BY clause is
used.
ORDER BY depend on the sort order configured on SQL Server at the time of
installation.


Syntax:

SELECT column_name [, column_name]
FROM table_name
[ORDER BY column_name | select_list_number | expression [ASC | DESC ]
[,column_name | select_list_number | expression] [ASC | DESC ]]


SQL SERVER 6.5
Chapter-3/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Relative column number can be used rather than the column name in the ORDER BY
clause.
If neither ascending, nor descending is specified, Ascending is assumed.
Upto 16 columns can be used in ORDER BY

EXAMPLE

SELECT pub_id, type, price , title
FROM titles
ORDER BY 2,3 DESC

OUTPUT:

Price is sorted in descending order and type defaults to ascending order.
CLASSROOM EXERCISE
1. Does the BETWEEN keyword specify an inclusive range of search.

2. How can you sort the query results?
SQL SERVER 6.5
Chapter-3/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
GENERATING SUMMARY DATA
Aggregate functions
Aggregate functions allow to produce new summary result columns that contain data
based on the existing columns and rows.
For example, a result column can be produced that gives the average cost in the cost
column of a table.
The basic Transact-SQL aggregate functions are:
Function Parameters Operation
AVG ( [ ALL | DISTINCT] expression ) Average of values in a numeric
expression, either all or distinct
COUNT ( [ ALL | DISTINCT] expression ) Number of values in an expression,
either all or distinct
COUNT (*) Number of selected rows
MAX (expression) Highest value in the expression
MIN (expression) Lowest value in the expression
SUM ( [ ALL | DISTINCT] expression ) Total of values in a numeric
expression, either all or distinct
EXAMPLES
Using AVG
SELECT AVG(price) FROM titles
OUTPUT:
Returns the arithmetic average of the price column for all rows of the titles table.


Using COUNT


SELECT COUNT(*) FROM titles

OUTPUT:

Returns the number of rows in the titles table.

SELECT COUNT(DISTINCT type) FROM titles

SQL SERVER 6.5
Chapter-3/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

OUTPUT:

COUNT function includes duplicates in its count, but doesnt include NULL values.
The use of DISTINCT returns the number of each unique value .
Displays the number of different types on which the books are available from the titles table.



SELECT COUNT(*) FROM titles WHERE price > 20.00

OUTPUT:

Function applies to only the rows that match the criteria specified in the WHERE clause.
Displays the count of rows in the titles table whose price are greater than 20.
SELECT COUNT(price) FROM titles
OUTPUT:
Displays how many books have been assigned price.



SELECT count(*) FROM titles WHERE price <> NULL

OUTPUT:

Displays the same result as the above query.
Displays how many books have been assigned price.



Using MIN

SELECT min(qty) FROM sales

OUTPUT:

Returns the smallest value in the column qty of the table sales.


More than one aggregate function can be used in a single SELECT statement.
SUM, AVG are used on numeric columns. Result is treated as int.
Only COUNT(*) can be used on image and text datatypes.
SQL SERVER 6.5
Chapter-3/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


GROUP BY And HAVING

GROUP BY clause when used in SELECT statement, divides a table into groups.
GROUP BY clause organizes summary data into groups, producing summary
information for groups defined in the selected table.
The HAVING clause sets further restriction on the result rows .
The HAVING clause relates to the GROUP BY clause in same way as the WHERE
clause relates to the SELECT statement.

Syntax:

SELECT column_name, [, colum_name]
FROM table_name
WHERE search_conditions
[GROUP BY [ALL] column_name1, column_namen
[HAVING search_conditions ]]

Characteristics of the clauses:

WHERE clause excludes rows that do not meet its search condition.
GROUP BY clause collects rows that met the WHERE clause search conditions and
places those rows into a group for each unique value in the GROUP BY clause.
Omitting the GROUP BY clause creates a single group for the whole table.
HAVING clause excludes groups that do not meet its conditions. Thus, specific
groups can be selected by using HAVING clause.
Aggregate functions in the SELECT list calculate summary values or each group.
GROUP BY clause can include expressions.
GROUP BY ALL displays all groups, even those excluded from, calculations by a
WHERE clause.
If GROUP BY ALL and HAVING are used in the same query, the HAVING clause
overrides the ALL used in the GROUP BY.
The only groups returned will be the ones that meet the HAVING condition.

EXAMPLES
Example 1

SELECT stor_id, copies_sold = SUM(qty)
FROM sales
GROUP BY stor_id

OUTPUT:

Displays the stor_id and the total quantity of the books sold by that particular store.
SQL SERVER 6.5
Chapter-3/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Example 2

SELECT stor_id, copies_sold = SUM(qty)
FROM sales
GROUP BY stor_id
HAVING SUM(qty) > 10

OUTPUT:

Lists the stor_id and total quantity of books sold by each store only if sold quantity is more than ten.
stor_ids which sold more than ten are identified by the HAVING clause.


Example 3

SELECT title_id, copies_sold = SUM(qty)
FROM sales
WHERE ord_date BETWEEN 1/1/1994 AND 12/31/1994
GROUP BY ALL title_id

OUTPUT:

Lists all the title_id and quantity of books that sold during the year 1994.
GROUP BY ALL includes even those books which are not sold in 1994, the quantity for which is
displayed as NULL.

Title_id copies_sold
--------- ----------
BU1032 15
BU1111 (null)
: :
TC7777 (null)




COMPUTE and COMPUTE BY


COMPUTE clause uses aggregate functions to produce the summary rows in the
query results.
COMPUTE BY adds further summary rows by column.
COMPUTE clause produces both the detail and summary rows in the same report,
whereas GROUP BY produces new columns.
COMPUTE clause used for control-break summary reports where detail rows are
listed and sorted by primary and foreign key values.
When a value of specified key changes, subtotal for the key values are calculated
since the last break.
After the subtotals are displayed, detail data is listed until the key value changes
again.

SQL SERVER 6.5
Chapter-3/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Syntax:

COMPUTE row_aggregate(column_name)
[, row_aggregate(column_name)]
[BY column_name [, column_name]]

EXAMPLE

SELECT type, price FROM titles WHERE type LIKE %cook%
ORDER BY type, price
COMPUTE SUM(price)

OUTPUT:

Total price for the type which contains cook as the string is calculated.

Type price
----- -----
mod_cook 2.99
mod_cook 19.99
trad_cook 11.95
trad_cook 14.99
trad_cook 20.95

sum
===========
70.87


Example 2

SELECT type ,price FROM titles
WHERE type LIKE %COOK
ORDER BY type, price
COMPUTE SUM(price) BY type

OUTPUT:

Adds BY type to the compute clause.
This breaks the results into subgroups.

type price
----------------------------------------
mod_cook 2.99
mod_cook 19.99
sum
======
22.98



SQL SERVER 6.5
Chapter-3/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
type price
----------------------------------------
trad_cook 11.95
trad_cook 14.99
trad_cook 20.95
sum
======
47.89

Compare the above example with the following GROUP BY example.

SELECT type, tot_price = SUM(price)
FROM titles
WHERE type like %cook
GROUP BY type

OUTPUT:

Type tot_price
------ ----------
mod_cook 22.98
trad_cook 47.89


Example 3

SELECT type ,price FROM titles
WHERE type LIKE %COOK
ORDER BY type, price
COMPUTE SUM(price) BY type
COMPUTE SUM(price)
OUTPUT:

Adds a grant total to the Example 2.

type price
----------------------------------------
mod_cook 2.99
mod_cook 19.99
sum
======
22.98

type price
----------------------------------------
trad_cook 11.95
trad_cook 14.99
trad_cook 20.95
sum
======
47.89
sum
======
70.87

SQL SERVER 6.5
Chapter-3/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

COMPUTE and COMPUTE BY restrictions

DISTINCT keyword is not allowed with row aggregate functions.
Columns in the COMPUTE clause must appear in the statements select list.
SELECT INTO can not be used in the same statement as a COMPUTE clause.
If COMPUTE BY is used, ORDER BY must be used.
The columns listed after COMPUTE BY must be identical or subset of those listed
after ORDER BY. They must have the same order.
Text and image datatypes cannot be included in the COMPUTE or COMPUTE BY
clause.
CLASSROOM EXERCISES
1. Considering the last example of COMPUTE BY, display the summary
report on another field advance, along with the price. The grouping
condition remains same.
GROUP BY with the ROLLUP and CUBE operators
ROLLUP and CUBE operators are used with aggregate functions to generate additional
rows in the result set.
Syntax:
SELECT [ALL | DISTINCT ] column_name, [, colum_name]
INTO[new_table_name]
[FROM table_name1 [, table_name16]
WHERE search_conditions
[GROUP BY [ALL] column_name1, column_namen
[WITH { CUBE | ROLLUP}]]
[HAVING search_conditions ]
[ORDER BY clause]
[COMPUTE clause]
ROLLUP
It creates groupings by moving from right to left along the list of columns in the
GROUP BY clause.
It then supplies the aggregate function to these groupings.
The result set of the GROUP BY clause with a ROLLUP operators returns
cumulative aggregates such as running sums or running averages.
SQL SERVER 6.5
Chapter-3/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CUBE

Creates all combinations of groupings from the list of columns in the GROUP BY
clause.
Every possible combination of columns or expressions in the GROUP BY clause is
used to produce the super-aggregates.
Mathematically, these combinations form an n-dimensional cube.

Guidelines for ROLLUP and CUBE

A maximum of 10 grouping expressions are permitted when WITH ROLLUP is
specified.
Columns or expressions must be explicitly specified in the GROUP BY clause and
GROUP BY ALL is not permitted.
Maximum size of GROUP BY column list is 900 bytes.


EXAMPLES

A GROUP BY example

SELECT type AS Book Type, pub_id, AVG(price)AS avgprice FROM titles
GROUP BY type, pub_id

OUTPUT:

Average price of a book for each publisher by book type appears in the result column on the right.

Book Type pub_id avgprice
---------- -------- --------
business 0736 2.99
business 1389 17.31
mod_cook 0877 11.49
popular_comp 1389 21.48
psychology 0736 11.48
psychology 0877 21.59
trad_cook 0877 15.96
UNDECIDED 0877 NULL


ROLLUP example


SELECT type AS Book Type, pub_id, AVG(price)AS avgprice FROM titles
GROUP BY type, pub_id
WITH ROLLUP

OUTPUT:

Average price of each book type for each publisher (also returned by GROUP BY alone)
Average price for each book type for all publishers.
SQL SERVER 6.5
Chapter-3/20
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Average price for all book types for all publishers .
The rows that contain NULL in pub_id column, represent the average price of a book type for all
publishers.
The row containing NULLs in both the Book Type and pub_id represents the grand total average for all
books, regardless of type or publisher.
Book Type pub_id avgprice
---------- -------- --------
business 0736 2.99
business 1389 17.31
business NULL 13.73
mod_cook 0877 11.49
mod_cook NULL 11.49
popular_comp 1389 21.48
popular_comp NULL 21.48
psychology 0736 11.48
psychology 0877 21.59
psychology NULL 13.50
trad_cook 0877 15.96
trad_cook NULL 15.96
UNDECIDED 0877 NULL
UNDECIDED NULL NULL
NULL NULL 14.77
CUBE example
SELECT type AS Book Type, pub_id, AVG(price)AS avgprice FROM titles
GROUP BY type, pub_id
WITH CUBE
OUTPUT:
Average price of each book type for each publisher (also returned by GROUP BY alone and ROLLUP)
Average price for each book type for all publishers (also returned by ROLLUP).
Average price for all book types for all publishers .(also returned by ROLLUP).
Average price for all book types for each publisher.
Rows with NULL in only one column i.e. book type, represent the average price of a book for each
publisher.

Book Type pub_id avgprice
---------- -------- --------
business 0736 2.99
business 1389 17.31
business NULL 13.73
mod_cook 0877 11.49
mod_cook NULL 11.49
popular_comp 1389 21.48
popular_comp NULL 21.48
psychology 0736 11.48
SQL SERVER 6.5
Chapter-3/21
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

psychology 0877 21.59
psychology NULL 13.50
trad_cook 0877 15.96
trad_cook NULL 15.96
UNDECIDED 0877 NULL
UNDECIDED NULL NULL
NULL NULL 14.77
NULL 0736 9.78
NULL 0877 15.41
NULL 1389 18.98



SQL SERVER 6.5
Chapter-3/22
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

IMPLEMENTING JOINS


Join is an operation that allows you to retrieve data from two or more tables. The result is
a single table with columns from both the tables and rows that satisfy the search
conditions.

Implementation

Join can be specified on two tables at a time using a column from each table as a
connecting or join column.
There can be more than one join in a single SELECT statement.
A connecting column should have values that match or compare easily, representing
the same or similar data in each of the tables included in the join.
A join statement:
a) Specifies a column from each table.
b) Compares the values in those columns row by row.
c) Combines rows with qualifying values into new rows.


Syntax:


SELECT table_name.colmn_name [, table_name.column_name]
FROM {table_name, table_name}
WHERE table_name.column_name join_operator table_name.column_name

Any time a column is referenced that appears in both tables in a join, each column
name must be qualified with the format, table_name.column_name.
FROM clause lists all the tables involved in the join operation.
WHERE clause specifies the rows that should be included in the result sets.
In the WHERE clause, a join_operator is used between components being joined.
Following table lists the join operators

Symbol Description
= Equal to
> Greater than
< Lesser than
>= Greater than or equal to
<= Lesser than or equal to
<> Not equal to
SQL SERVER 6.5
Chapter-3/23
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Join can be of the following types:
Inner joins
Cross joins
Outer joins
Self joins
Inner join
Inner joins connect two tables into a third table that includes only the rows that satisfy the
join condition.
Two common types of inner join are
(a) Equi join
(b) Natural join
Equi join
Column values being compared are equal.
Produces redundant column information because the join column information is
displayed twice .

EXAMPLE

Example 1

SELECT authors.au_lname, authors.state, publishers.*
FROM publishers, authors
WHERE publishers.city = authors.city

OUTPUT:

au_lname state pub_id pub_name city state country
--------- ------ ------- -------- ----- ------ -------
Carson CA 1389 Algodata Berkeley CA USA
Bennet CA 1389 Algodata Berkeley CA USA

Example 2

SELECT * FROM authors, publishers
WHERE authors.city = publishers.city

OUTPUT:

The column city will appear twice in the output.




SQL SERVER 6.5
Chapter-3/24
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Natural join

Column values being compared are equal to for two or more tables, but the join
column is displayed once.
Eliminates the redundant column data in the results set that an equi join produces.

EXAMPLE


SELECT pub_name, title FROM titles, publishers
WHERE titles.pub_id = publishers.pub_id

OUTPUT:

pub_name title
--------------------- -------
Algodata Infosystems The Bus
Algodata Infosystems But is it
New Moon Books You can
: :


Cross joins

A cross or unrestricted join produces results set that includes every combination of all
rows between the tables in the join.
It matches every row of one table to every row of the other table.
Cross joins return a table that is the joined tables cartesian product.
For example, if there are 2 rows in one table and 3 rows in other, the results include 6
rows.
The results are typically unusable.


EXAMPLE

SELECT pub_name, title FROM titles, publishers

OUTPUT:

All rows of publisher table are matched with all rows of the titles table.



Outer joins

Normally in joins, only matching rows (rows with values in the specified columns
that satisfy the join condition) are included in the results.
Sometimes, it is desirable to retain the nonmatching information by including
nonmatching rows in the results of a join.
SQL SERVER 6.5
Chapter-3/25
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Outer join allows to restrict the rows in one table while not restricting the rows in
other table.
It is useful when you want to see where primary key and foreign key tables are out of
synchronization, or have orphan problems.

The SQL Server outer join operators include:

*= Includes all rows from first table regardless of the statements restriction.
=* Includes all rows from second table regardless of the statements restriction.

Rules for outer joins

Outer join displays all rows in the outer table, including those not matched to rows in
the related table.
An outer join can be done only between two tables.


EXAMPLE

Example 1

SELECT title, stor_id, ord_num, qty, ord_date
FROM titles, sales
WHERE titles.title_id *= sales.title_id

OUTPUT:

Lists titles and sales details, including titles that have no sales.
The *= operator tells SQL Server to include all the rows from the title table.

title stor_id ord_num qty ord_date
---------- ---------- -------- ------ -------------------
The Busy 8042 423LL930 10 Sep 14 1994 12:00AM
The Busy 6380 6871 5 Sep 14 1994 12:00AM
Cooking 8042 P723 25 Mar 11 1993 12:00AM
: : : : :
The psy NULL NULL NULL NULL
: : : : :

Example 2

SELECT au_fname, pub_name FROM authors, publishers
WHERE authors.city =* publishers.city

OUTPUT:

All rows in the second table i.e. publishers table are included in the results, regardless of whether there
is matching data in the authors table.


SQL SERVER 6.5
Chapter-3/26
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Using NULL in outer joins

If there are null values in the tables that are to be joined, null values will never match
each other.
For this reason, NULL should not be used as search condition on the inner table
columns in outer join.

EXAMPLE

Tab1 Tab2

a1 a2 b1 b2
----- ------ ------ ------
1 abc NULL def
NULL pqr 4 xyz
4 hij


Left outer join

SELECT * FROM tab1, tab2 WHERE a1 *= b1

OUTPUT:

Null values are not matching, hence for a1 having NULL value, corresponding match in other table for
b1 ( the first record) is not selected.
Only the value 4 is matched.


a1 a2 b1 b2
------ ------ ------ ------
1 abc NULL NULL
NULL pqr NULL NULL
4 hij 4 xyz



Self joins


A self join correlates rows of a table with other rows within that same table.
It is commonly used when a query compares the same information.
The compared columns must be the same or compatible datatypes.

Table aliases

In order to join the same table it is necessary to assign the table two aliases so that the
table can be referenced logically as two different tables.

Aliases are assigned in the FROM clause by specifying the alias after the table name.
SQL SERVER 6.5
Chapter-3/27
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Syntax:

SELECT column_name [, column_name]
FROM table_name alias [, table_name alias]
WHERE table_name.column_name
join_operator
table_name.column_name

EXAMPLE

SELECT a1.au_fname, a1.au_lname, a2.au_fname, a2.au_lname
FROM authors a1, authors a2
WHERE a1.city = Oakland
AND a1.state = CA
AND a1.zip = a2.zip
AND a1.au_id < a2.au_id

OUTPUT:

Determines which authors in Oakland, California live in the same ZIP code area.
Query involves a join of the authors table with itself, the authors table appears in two roles.
au_fname au_lname au_fname au_lname
--------- --------- --------- ---------
Dean Straight Dirk Straight
Dean Straight Livia Karsen
Dirk Straight Livia Karsen
CLASSROOM EXERCISE
1. What are the two ways to generate the summary data.

2. Find the titles of all the books of a particular type and names of
their authors.(Refer to the database given in the appendix )
Hint : More than two tables to be joined.

3. What do joins allow to do?

4. What are some of the SQL Server join operators?
SQL SERVER 6.5
Chapter-3/28
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LAB EXERCISES
Use pubs database for the following queries:
1. Display the details of all the authors from the authors table whose state is
CA.
2. Display the title_id and the price of the book if increased by 20% under the
heading new_price, only for the books whose advance is greater than 5000.
3.Write a query on the titles table that returns the total price of the books
against a particular pub_id in a column called tot_price.
4.Create a list of all pub_id and a count of all books published by that pub_id.
Only display pub_id who have more than 5 books.
5. Find all books with sales between 4095 and 12000.
6. Find all the authors who live in California, Indiana or Maryland.
7. Find all the phone numbers in the authors table that have area code 415.
8. Find all business books in the titles table, no matter what their advances are as
well as all psychology books that have an advance greater than 5500.
9. Find all business books and psychology books that have an advance greater than
5500.
10. List the title_id and title for all titles that contain the characters prog.
11. Create a sorted list of the titles in the titles table.
12. Find the average price and sum of year-to-date sales , grouped by type and
publisher_id.
13. Find the average price for each type of book and order the results by average
price and type.
14. Group the titles table by publisher, including only those publishers with
id > 0800,who have paid more than 15000 in total advances and who sell
books for less than an average of $20.
15.Try out the control break report using COMPUTE and COMPUTE BY as given
in the example in the book and also for the classroom exercise.
16.Try out the ROLLUP, and CUBE operators as give in the example.
17. Retrieve the names and publishers of all books for which advances greater
than $7500 were paid.
18. Find the titles for which more than 50 copies have been sold.
19. Find the titles of all the books of type trad_cook and the names of their
authors.
20. Create the joins using Microsoft Query Utility also.
SQL SERVER 6.5
Chapter-3/29
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
SELECT statement includes a WHERE clause to retrieve a subset of the row in a table
based on given search condition.
Rows can be retrieved based on comparisons using comparison operators ( =, >, <, >=,
<=, !=, !>, !<, ()) .
Rows can be retrieved based on ranges using BETWEEN operator.
Rows can be retrieved based on lists using IN operator.
Rows can be retrieved based on character strings using LIKE operator.
Columns whose values are not known are retrieved using NULL keyword.
Logical operators AND, OR and NOT allow to combine search arguments.
Duplicates are eliminated using DISTINCT keyword.
ORDER BY clause is used for sorting the query results set.
Aggregate functions like AVG, COUNT, MAX, MIN, SUM allow to produce summary
data.
GROUP BY clause organizes summary data into groups, producing summary
information
for groups defined in the selected table.
COMPUTE, COMPUTE BY are used for control break summary reports.
ROLLUP and CUBE operators are used with aggregate functions to generate additional
rows in the result set.
Joins are used to retrieve data from two or more tables
INNER JOIN - Connect two tables into a third table that includes only the rows that
satisfy the join condition.
CROSS JOIN - Produces every combination of all rows between the tables in the join.
OUTER JOIN - Allows to restrict the rows in one table while not restricting the row in
other table.
SELF JOIN - Correlates rows of a table with other rows within that same table.
SQL SERVER 6.5
Chapter-4/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Subqueries and data manipulation statementsw
SCOPE
Performing subqueries
Nested SELECT statements
Type of subqueries
Correlated subqueries
SELECT INTO
UNION operator
Inserting Rows
Inserting Partial Data
Default Options
Inserting Rows with SELECT
Inserting Rows with Stored Procedures
Updating Rows
Updating Based On Data from Other Tables
Deleting Rows
Removing Rows Based On Data in Other Table
SQL SERVER 6.5
Chapter-4/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
PERFORMING SUBQUERIES
SELECT statements can be nested within other statements like SELECT, INSERT,
UPDATE or DELETE statements. These nested SELECT statements are called sub-
queries.
To use a sub-query, use the inner query within the parentheses to specify that it should be
evaluated before the outer query.
Nesting SELECT statements (Nested queries)
The nested or inner SELECT statement within another SELECT, INSERT, UPDATE
or DELETE statement is evaluated and the result is available to the outer statement.
A sub-query can return a single value, such as an aggregate, which can be used
wherever a single value can be used.
If a sub-query produces a column of values, it can only be used in the WHERE clause
where an expression can be used.
A sub-query can be nested inside the WHERE or HAVING clause of an outer
SELECT, INSERT, DELETE or UPDATE statement, or inside another sub-query.
There is no practical limit of nesting.
If a table appears only in a sub-query and not in the outer query, then columns from
that table cannot be included in the output (the select_list of the outer query).
EXAMPLE
To find the books that are of the same price as the book The Gourmet Microwave, there are 2 ways.
Either in two steps.
or, in a single step using subquery.
In two steps:
Step 1:
SELECT price FROM titles WHERE title = The Gourmet Microwave
OUTPUT:
price
---------
2.99
SQL SERVER 6.5
Chapter-4/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Step 2:
SELECT title, price FROM titles WHERE price = 2.99
OUTPUT:
title price
------------------------------- -------
You Can Combat Computer Stress 2.99
The Gourmet Microwave 2.99
Using subquery
SELECT title, price FROM titles WHERE price =
(SELECT price FROM titles WHERE title = The Gourmet Microwave)
Types of sub-queries
Sub-queries can be used in these contexts:
WHERE expression [NOT] IN
WHERE expression comparison_operator [ANY | ALL]
WHERE [NOT] EXISTS
IN operator
The result of a sub-query with IN or NOT IN will return a list of values.
The outer query makes use of the results returned by the inner query.
EXAMPLE
SELECT pub_name FROM publishers WHERE pub_id IN
(SELECT pub_id FROM titles WHERE type = psychology)
OUTPUT:
pub_name
----------------
New Moon Books
Binnet & Hardley
The statement is evaluated in two steps.
The inner query returns the identification numbers of the publishers who have published books on
psychology.
SQL SERVER 6.5
Chapter-4/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

These values are substituted into the outer query, which finds the names that match with the
identification numbers in the publishers table.
The second step looks like this:
SELECT pub_name FROM publishers WHERE pub_id IN (0877, 0736)
ANY operator
Compares a value to each value returned by a list or subquery.
IN operator is equivalent to =ANY.
> ANY means greater than at least one value. In other words, greater than minimum.
For example , > ANY(1,2,3) means greater than 1.
Thus, in > ANY, for a row to satisfy the condition specified in the outer query, the
value in the column that introduces the subquery must be greater than at least one of
the values in the list of values returned by the subquery.
EXAMPLE
SELECT emp_id FROM employee
WHERE job_lvl > ANY (SELECT job_lvl FROM employee WHERE pub_id =
9999)
OUTPUT:
The query finds the employees whose job levels are larger than the minimum job level for pub_id
9999.
The inner query finds a list of job levels for pub_id 9999.
The outer query looks at all values in the list and finds employees with job level larger than the lowest
job level of pub_id 9999.
ALL operator
Forces the specified relation for the column of a WHERE clause to be true for all
values returned by the sub-query.
NOT IN is equivalent to !=ALL.
Using the > comparison operator i.e. > ALL means greater than every value. In other
word, greater than the largest value. For example, > ALL (1,2,3) means greater than
3.
> ALL means that for a row to satisfy the condition specified in the outer query, the
value in the column that introduces the subquery must be greater than each value in
the list of value returned by the subquery.
SQL SERVER 6.5
Chapter-4/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
SELECT emp_id FROM employee
WHERE job_lvl > ALL (SELECT job_lvl FROM employee WHERE pub_id =
9999)
OUTPUT:
The query finds the employees whose job levels are larger than the maximum job level for pub_id
9999.
The inner query finds a list of job levels for pub_id 9999.
The outer query looks at all values in the list and finds employees with job level larger than the largest
job level of pub_id 9999.
EXISTS keyword
When a sub-query is introduced with the keyword EXISTS, it functions as an
existence test.
The WHERE clause of the outer query tests for the existence of rows returned by the
sub-query.
The sub-query doesnt produce data; it returns a value: TRUE or FALSE.
EXAMPLE
Example 1
SELECT au_lname, au_fname FROM authors WHERE EXISTS
(SELECT * FROM publishers WHERE authors.city = publishers.city)
OUTPUT:
Finds authors who live in the same city as a publisher.
An alternate way to get the same result.
SELECT au_lname, au_fname FROM authors WHERE city = ANY
(SELECT city FROM publishers)
Example 2
SELECT title FROM titles WHERE EXISTS
(SELECT * FROM publishers WHERE pub_id = titles.pub_id AND city
LIKE C%)
OUTPUT:
Finds titles of books published by any publisher located in the city that begins with the letter C.
SQL SERVER 6.5
Chapter-4/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Sub-query restrictions
The select_list of a sub-query introduced with a comparison operator can include only
one expression or column name.
If the WHERE clause of the outer statement includes a column name, it must be join
compatible.
EXISTS can operate on SELECT *, and IN can operate on select_list.
Columns of image and text type can not be included in the sub-query.
The DISTINCT keyword cannot be used with sub-queries that include a GROUP BY
clause.
A view created with a sub-query cannot be updated.
A subquery cannot include an ORDER BY clause, a COMPUTE clause or an INTO
keyword.
Correlated Sub-queries
Previous queries were all evaluated by executing the sub-query once, and substituting
the resulting value or values into the WHERE clause of the outer query.

A correlated query is one in which the WHERE clause references a table in the
FROM clause of the outer query.

In this case, sub-query is evaluated for each row of the table referenced in the outer
query.

Thus, the sub-query is repeatedly executed, once for each row that might be selected
by the outer query.

A correlated query is used to answer multi-part questions whose answer depends on
the value in each row of the parent query.
EXAMPLE
To find all the titles whose price is more than the average price of the books of the same publication as that
book .
Main query
SELECT title_id, pub_id, price FROM titles
WHERE price > (Average price of the books of the same publication as that book)
SQL SERVER 6.5
Chapter-4/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Sub-query
SELECT AVG(price) FROM titles
WHERE pub_id = (Book rows value of PUB_ID)
Correlated Subquery
SELECT title_id, pub_id, price FROM titles x
WHERE price > ( SELECT AVG(price) FROM titles WHERE pub_id = x.pub_id)
SELECT INTO
A SELECT statement with an INTO clause allows you to define a table and put data
into it without going through the usual data definition process.
SELECT INTO creates a new table based upon results of a query.
If a table already exists with the same name, this statement will fail.
The new table is based on the
columns specified in the select_list.
the table named in the FROM clause.
rows chosen in the WHERE clause.
Syntax:
SELECT select_list
INTO new_table_name
FROM table_list
WHERE search_conditions
Remarks:
By default, the SELECT INTO statement allows to create only a temporary table.
The SELECT INTO clause selects into a new permanent table only if the select
into/bulkcopy database option is set. (Covered later)
To select rows into a table that already exists, INSERT statement must be used.
If columns in the select_list have no titles, then the columns in the newly created table
will have no names.
Columns with no names can only be referenced with SELECT * FROM tablename.
Therefore, columns might need to be aliased.
New column headings should not have spaces.
SQL SERVER 6.5
Chapter-4/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
Example 1
SELECT title = SUBSTRING (title, 1, 40), price = price * 1.1
INTO #table1
FROM titles
SELECT * FROM #table1
OUTPUT:
Lists the first 40 characters of each title, along with the price if increased by 10 percent.
The results are placed in the temporary table #table1.
The SELECT statement is used to see the results.
UNION operator
The UNION operator allows to manipulate the results of two or more queries by
combining the results into a single set.
A UNION results in an increase in number of rows.
Whereas a join results in increase in number of columns.
The column structure and datatypes have to be compatible.
Syntax:
SELECT select_list [INTO clause]
[FROM clause]
[WHERE clause]
[GROUP BY clause]
[HAVING clause]
[UNION [ALL]
SELECT select_list
[FROM clause]
[WHERE clause]
[GROUP BY clause]
[HAVING clause]]
[ORDER BY clause]
[COMPUTE clause]
SQL SERVER 6.5
Chapter-4/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
By default, UNION operator removes duplicate rows from the result set.
Using ALL option includes all rows in the result set.
All select_list in the UNION statement must have the same number of columns,
similar datatypes, and must occur in the same order.
If the UNION statement contains an ORDER BY clause, the entire results set is
sorted.
Columns names come from the first SELECT statement.
EXAMPLE
SELECT title, stor_name, ord_date, qty
FROM titles, sales, stores
WHERE titles.title_id = sales.title_id
AND stores.stor_id = sales.stor_id
UNION
SELECT title, No sales, null, null
FROM titles
WHERE title_id NOT IN (SELECT title_id FROM sales)
OUTPUT:
The first set is derived from a three-table join.
The result set is united to the second result set which retrieves information about titles that have no
sales.
title stor_name ord_date qty
--------------- ------------ --------- -------
Net Etiquette No sales NULL NULL
The Psycho No sales NULL NULL
Sushi News & Brews Jun 15 20
Is Anger Barnums Sep 13 75
: : : :
CLASSROOM EXERCISE
1. What is the difference between a correlated sub-query and a sub-query?
What makes it a correlated subquery?
2. What is the function of SELECT statement with an INTO clause?
3. Find the names of authors who have participated in writing at least
one book of type popular_comp. (Hint: Multiple nested query)
4. Is <>ANY equivalent to NOT IN?
SQL SERVER 6.5
Chapter-4/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

MODIFYING DATA
Insertion of rows
The INSERT statement adds a new row to the table.
It consists of :
(a) INSERT statement
(b) VALUES clause
INSERT statement
It specifies the table or view into which the row is to be inserted.
The table should be existing, before the INSERT statement can be used.
It can contain a column list to specify certain columns instead of the entire row.
VALUE clause
It specifies the data to be inserted.
It is a required keyword used to introduce the list of values for each column in the
column_list or table.
Character and date data must be enclosed in the quotes.
Syntax:
INSERT [INTO]
{table_name | viewname} [ (column_list)]
VALUES { value_list }
EXAMPLE
CREATE TABLE applicant
(fname varchar(10), lname varchar(10), address varchar(10))
INSERT INTO applicant
VALUES (Alton, john, 2 BLOCK)
OUTPUT:
A new applicant is added to the table applicant with all the details.
SQL SERVER 6.5
Chapter-4/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Inserting partial data
Data need not be specified in the VALUES clause for the columns that allow NULL
or a default value. (Default value is a value that is added automatically added when
user does not specify any value explicitly. Defaults are covered later in detail)
In the INSERT clause, the column names should be listed for the data which is
supplied.
If a column_list is given, the data in the VALUES clause corresponds to those
columns only.
Syntax:
INSERT [INTO]
{table_name | view_name } [(column_list)]
VALUES { value_list }
EXAMPLE
INSERT INTO publishers (pub_id, pub_name)
VALUES(1212, Press Press)
SELECT * FROM publishers
WHERE pub_name = Press Press
OUTPUT:
A new publisher is added, with the ID and name without filling in the other information.
The city, state and country fields allow null values.
pub_id pub_name city state country
-------- --------- ----- ----- --------
1212 Press Press (null) (null) (null)
Default options
The DEFAULT VALUES clause inserts a row containing default values for all
columns. (Creation of defaults for columns is covered later )
The next appropriate value will be inserted if the column has IDENTITY property (an
automatically assigned incremented value, or it has the timestamp datatype.)
If a default for the column does not exist and the column allows NULLs, NULL will
be inserted.
If any column of the table does not have a default or does not allow NULL, an error
will be returned and the INSERT statement is rejected.
SQL SERVER 6.5
Chapter-4/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Syntax:
INSERT tablename DEFAULT VALUES
DEFAULT
It inserts a default value for the specified column.
DEFAULT is not valid for a column with the IDENTITY property.
Columns with IDENTITY property should not be listed in the column_list or
value_clause.
Syntax:
VALUES ( DEFAULT | constant_expression [, DEFAULT | constant_expression])
EXAMPLE
Assuming table called table_name is already existing, which has four columns and the third column has a
default bound to it i.e. if no value is supplied, the default value should be inserted in the column
INSERT INTO table_name
VALUES ( 2422, abc, DEFAULT, pqr)
OUTPUT:
Inserts a default value for the third column.
Note: Creation of defaults is covered later
A default value is inserted if one exists for the column or for the user defined
datatype.
NULL is entered if NULL is specified for the column when the table was created and
no default value exists for the column.
If NULL is not allowed and a specified default does not exist, an error is generated,
and row is not added.
SQL SERVER 6.5
Chapter-4/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Inserting rows with SELECT
SELECT clause allows to insert rows into an existing table from one or more other
tables.
Rows can be inserted from the same table also.
Syntax:
INSERT table_name SELECT column_list
FROM table_list WHERE search_condition
INSERT table and the SELECT results set must be compatible in terms of the number
of columns, columns ordering, datatypes and so on.
If any table_name columns are omitted, either a default should exist, or a value
should be provided, or NULL is allowed for the columns omitted.
The INSERT SELECT inserts many rows.
EXAMPLE
INSERT stores
SELECT substring(au_id, 8, 4), au_lname, address, city, state, zip
FROM authors
OUTPUT:
Adds a new store for each author using the last four digit of ID as a new store ID, and authors last
name for the new store name.
Inserting rows with stored procedure
INSERT statement can populate a table with results returned from a stored procedure.
Thus, data can be imported from the remote systems.
Syntax:
INSERT [INTO]
{table_name | view_name } [(column_list)]
EXEC { procedure_name | @procedure_name_var}
[[@parameter_name=] {value | @variable [OUTPUT] | DEFAULT}
[,[@parameter_name = ] {value | @variable [OUTPUT] | DEFAULT }]]
SQL SERVER 6.5
Chapter-4/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
The table is loaded with data returned from SELECT statements in the stored
procedure.
The table must already exist.
Data returned from PRINT, RAISERROR, FETCH statements or other output is not
stored in the table.
Data returned from the SELECT statement must conform to the datatypes in the
existing tables column.
A procedure that returns multiple result sets appends the data to the table.
Note: For details, refer session no. 8
EXAMPLE
INSERT INTO emp_info
EXEC fetch_data
OUTPUT:
The fetch_data user-defined stored procedure pulls data from remote sites into local tables.
Note: Try this exercise after learning creation of user-defined stored procedure (session 8)
Updating row data
The UPDATE statement changes data in existing rows in a table.
It operates on only one table.
SET specifies the column(s) and changed value.
WHERE identifies specific rows to update.
Syntax:
UPDATE {table_name | view_name }
SET [{table_name | view_name}]
{ column_list1 | variable_list1 | }= expression
[,column_listn | variable_listn | }= expression]
[WHERE clause]
expressions is a column name, constant, function (aggregate functions are not allowed),or
any combination of column names, constants and functions connected by an operator(s)
or a subquery.
SQL SERVER 6.5
Chapter-4/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
If the UPDATE statement violates integrity constraints, the update does not take
place and the entire update is rolled back.
EXAMPLE
UPDATE applicant
SET fname = ALTON
WHERE fname = ALLEN
OUTPUT:
In the table applicant the applicant whose first name is ALLEN is changed to ALTON.
Updating Based on data from other tables
A table can be updated using data from other tables.
This is implemented using the FROM clause.
For each row in the table to be updated, it has to meet the criteria of the outer
WHERE clause.
The nested SELECT, which must be a single value SELECT executes once for each
row.
The selected value will update the specified row.
If nested SELECT statement is not a single value, the results are unspecified.
A single UPDATE statement can not update the same row twice
Syntax:
UPDATE table_name[(column_list)]
SET column_name = expression
FROM table_list
WHERE serach_condition
EXAMPLE
Assuming a table called member is already existing which has a field called first_name.
UPDATE member
SET first_name = ( SELECT fname FROM applicant
WHERE lname = DOILEY)
OUTPUT:
The first_name of the member in the member table is changed.
It is set to the first_name in the applicant table whose last_name is DOILEY.
SQL SERVER 6.5
Chapter-4/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Deleting rows
DELETE statement allows to remove one or more rows from a table.
Syntax:
DELETE [from] table_name
WHERE search_conditions
If no WHERE clause is specified, all rows will be deleted.
EXAMPLE
Example 1
DELETE applicant
WHERE fname = ALTON
OUTPUT:
A record from the applicant table is deleted whose first_name is ALTON.
Example 2
DELETE applicant
OUTPUT:
All the rows from the table applicant are deleted.
Removing Rows Based on data in other tables
Syntax:
DELETE [from] table_name
FROM {table_name [, { table_name}...]}
WHERE search_conditions
The WHERE clause in a DELETE statement can look at data in other tables and
determine whether a row in the given table should be deleted.
This allows naming of more than one table or view to use with a WHERE clause to
specify which rows to delete.
The FROM clause allows to delete rows from one table based on the data stored in
other tables .
SQL SERVER 6.5
Chapter-4/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
DELETE FROM titleauthor
FROM authors a, titles t
WHERE a.au_id = titleauthor.au_id
AND t.title_id = titleauthor.title_id
AND t.title LIKE %computers%
OUTPUT:
Deletes all records from the titleauthor table where the book title contains computers.
The TRUNCATE table statement
It removes all rows from the table.
Table structure continue to exit.
It is faster than DELETE statement because it does not logs the individual deletes.
DELETE statement removes rows one at a time and logs each deleted row as
transaction.
Immediately frees all the space occupied by that tables data and indexes.
TRUNCATE TABLE guarantees that all rows are removed from the table and cannot
be rolled back.
The statement cannot be used on a table referenced by a FOREIGN KEY constraint.
Syntax:
TRUNCATE TABLE [[database.]owner.] table_name
CLASSROOM EXERCISE
1. Can you modify more than one table with a single UPDATE, INSERT or
DELETE statement.
2. Can more than one row be modified with the above statements?
3. How do you insert the rows into a table from another table? Contrast
this with SELECT INTO.
SQL SERVER 6.5
Chapter-4/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

LAB EXERCISES
Use pubs database for the following:
1. Find the names of authors who have participated in writing at least one book
which is of type popular_comp.
2. Find the authors who live in California and who receive less than 30% of the
royalties for a book.
3. Find the names of the publishers who have not published books of type
business.
4. Perform the following query a) using subquery b) using join.
Double the price of all books published by New Moon Books.
5. Remove all records of sales of books of type business using a subquery. Can
the same operation be performed using joins?
6. Find the names of all books priced higher than the current minimum price.
7. Find the books priced higher than the lowest priced book in the type
trad_cook.
8. Use a correlated subquery to find the types of books that are published by more
than one publisher.
9. Find sales where the quantity is less than the average quantity for sales of that
title.
10. Find the names of publishers who do not publish books of type business.
11. Copy the structure (not data) of the table publishers to another table called
publishers2.
12. Insert into titles table, the following data:
title_id - BU2222, title - Faster1, type - business, pub_id - 1389,
price - NULL, advance - NULL, royalty - NULL, ytd_sales - NULL ,
notes - ok, pubdate - 06/17/87.
13. Insert only the following values in certain fields only:
title_id - BU1237, title - ABC, type - business, pub_id - 1389,
notes - great, pubdate - 06/18/86
14. Insert all the details of authors who live in San Francisco into a new table called
SanAuthors.
15. Delete all the authors from the authors table whose last name is McBadden.
16. Try out the examples given in the book.
SQL SERVER 6.5
Chapter-4/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
SELECT statement can be nested within other statements like SELECT, INSERT ,
DELETE and UPDATE statements. These nested SELECT statements are called
subqueries.
Subqueries can be used in three contexts:
WHERE expression [NOT] IN
WHERE expression comparison_operator [ANY / ALL]
WHERE [NOT] EXISTS
In correlated subqueries, subquery is evaluated for each row of the table referenced in the
outer query.
SELECT INTO defines a table and puts data into it.
UNION operator manipulates the results of two or more queries by combining the results
into a single set.
INSERT statement adds a new row to the table.
UPDATE statement is used to change the existing data in a table.
DELETE statement removes one or more rows from a table.
TRUNCATE TABLE statement is similar to DELETE statement except that it can be
used only to remove all rows from the table and does not log the delete operation.

SQL SERVER 6.5
Chapter-5/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Implementation of Indexes and views
SCOPE
Types of Indexes
Clustered
Nonclustered
Implementing Indexes
Creating and dropping Indexes
Performance analysis
Table Scan Vs Index Search
SHOWPLAN
Optimizer Hints
UPDATE STATISTICS
DBCC commands
Views
Advantages
Creating and dropping views
Modifying data through views
SQL SERVER 6.5
Chapter-5/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
TYPES OF INDEXES
Indexes
Indexes are SQL Servers internal method of organizing the data in a table in such a way,
that the data can be retrieved optimally.
An index is a collection of data values of a column in a table and their corresponding
pointers to the rows where those values are physically represented in that table..
DIAGRAM
MEM_NUM LAST_NAME FIRST_NAME AGE SEX
M003 BARR PETER 13 M
M001 ALLEN SAM 14 M
M002 M MARY 13 F
M005 ALLEN JOHN 14 M
M004 SOLLY ALLEN 14 M
. . . . .
. . . . .
. . . . .
M001
.
.
M004
M005
.
.
.
MEMBER
INDEX ON
MEM_NUM
SQL SERVER 6.5
Chapter-5/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Creation of Indexes
Indexes are another kind of objects, similar to tables, that are stored in the databases.
Indexes require pages of data to store their rows, like tables.
When an index is created, the database
(a) Scans the table.
(b) Gathers the values of the column that is being indexed.
(c) Writes a list of those values and their corresponding pointers to the rows
where those values physically exist, on to the index page.
How SQL Server uses the index
SQL Server uses an index as the index of the book is used.
It searches the index to find a particular value and then follows the pointer to locate the
row containing the value.
EXAMPLE
Note : Refer to the diagram on page 2 of the session.
SQL Server locates the record containing M004 in the MEMBER table by searching the index for the data
value M004 and following the pointer.
Types of indexes
There are two types of indexes
(a) Clustered indexes
(b) Nonclustered indexes
Clustered indexes
The file being indexed is stored in data pages with several records in each page.
SQL SERVER 6.5
Chapter-5/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


DIAGRAM




Page 5 Page 6 Page 7 Page 8 Page 9 Page 10

14 13 12 15 18 25

11 10 17 20 23 26

16 19 22 21 27 24








After the creation of a clustered index records are in the order of the index.


DIAGRAM



Page 5 Page 6 Page 7 Page 8 Page 9 Page 10

10 13 16 19 22 25

11 14 17 20 23 26

12 15 18 21 24 27







Index contains one entry per page, giving the topmost value of the indexed field
occurring in that page and a pointer to start of the page.






data pages
data pages
SQL SERVER 6.5
Chapter-5/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

DIAGRAM

Page 100 Page 101

Page Key Page Key

5 10 8 19

6 13 9 22

7 16 10 25



Page 5 Page 6 Page 7 Page 8 Page 9 Page 10

10 13 16 19 22 25

11 14 17 20 23 26

12 15 18 21 24 27








The sequence of data pages is represented by the sequence of entries in the index.

If the index gets large, an index to an index is created. ( Represented by the Root
level and the non leaf level in this case)
data pages
Index pages
SQL SERVER 6.5
Chapter-5/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


DIAGRAM

Page 103

Page Key

102 10


Page 102

Page Key

100 10

101 19
Page 100 Page 101

Page Key Page Key

5 10 8 19

6 13 9 22

7 16 10 25



Page 5 Page 6 Page 7 Page 8 Page 9 Page 10

10 13 16 19 22 25

11 14 17 20 23 26

12 15 18 21 24 27




In clustered index, the actual data pages represent the leaf level of the index i.e.
actual data pages are a part of the index.

Thus, the physical order of the rows is same as the indexed order. Data pages are
physically ordered on a hard disk using the logical order of the clustered index.

data pages
Leaf level
Root level
Non
leaf
level
SQL SERVER 6.5
Chapter-5/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Advantages of clustered index


Removes the need for sequential scanning of the indexed file.
UPDATE and DELETE operations are accelerated since these operations require
much reading.


Consider using a clustered index for


Queries that return a range of values using operators such as BETWEEN , >, <=, <,
<=.

EXAMPLE
SELECT * FROM emp

WHERE hire_date BETWEEN 5/1/95 AND 6/1/95


Queries that return large result sets.


Clustered index guidelines

There can be only one clustered index per table.
A clustered index should always be the first index to be created.
If CLUSTERED is not specified, a nonclustered index would be created, which is the
default.
Requires over twice the space to build (1.21 * table size) ; space to store the original
sequence until the index is built, and the space to create the clustered index.
Space required to create an index comes from the tables database.


SQL SERVER 6.5
Chapter-5/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Nonclustered indexes


DIAGRAM



14 13 21 19 20 12

11 10 17 22 23 26

25 27 16 24




10 14 20 24

11 16 21 25


12 17 22 26

13 19 23 27







Physical ordering of the rows is not same as their indexed order.

Nonclustered index specifies the logical ordering of the table.

Leaf level pages of a non-clustered index are index pages i.e. contains indexed
values and pointers to rows on data pages and are not the actual data pages of the
table.

These actual data pages are unordered.

Conceptually, there is a level of indirection between the index structure and the data
itself.

data pages
leaf level of index
SQL SERVER 6.5
Chapter-5/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Nonclustered Index guidelines

Number of nonclustered index permissible on one table is 249.

Clustered indexes should be created before the nonclustered indexes, because
clustered indexes change the physical order of the rows, and nonclustered indexed
would have to be rebuilt.


Consider using a nonclustered index for


Queries that return a small or single row result sets.


EXAMPLE

SELECT * FROM member

WHERE mem_num = M001



Columns that contain a large number of unique values. For example mem_num
column of member table.


Clustered indexes Vs Nonclustered indexes



Clustered Index Non clustered index

Indexed order of key values is same as the
physical order.
Indexed order of key value is not same as
physical order.
Leaf level pages of a clustered index
contain actual data pages.
Leaf level pages of a non-clustered index
are index pages.
A table can contain one clustered index. A table can have 249 nonclustered indexes.


SQL SERVER 6.5
Chapter-5/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


IMPLEMENTING INDEXES



Reasons for using Indexes


Enforces the uniqueness of rows.

Speeds the execution of SQL statements with search conditions, that refer to the
indexed column.

Reduces the number of I/Os required by the SQL Server query optimizer, to reach
any given piece of data in a table.

In certain cases, front-end application might require an index.



Indexing guidelines


When creating indexes on columns, consider the following:

Using indexes is appropriate for columns that are used frequently in search
conditions.

Indexes should be made for the tables for which queries are more frequent than
inserts and updates.

Primary keys should be indexed uniquely by creating a clustered or nonclustered
index.

Indexing on foreign keys help process joins more efficiently.

A column that is often accessed in sorted order should be given a clustered index.

Columns frequently used in joins should always be indexed.

The columns frequently used in WHERE clause and the columns which are searched
for range of value should be indexed.



SQL SERVER 6.5
Chapter-5/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Good index candidates


Candidates Notes

Foreign Keys Prime candidates for indexes. Helps the lookup times
immensely.
Large result set queries For the queries that will be returning a large dataset result,
indexing is preferred.
Order by and group support Columns that are referenced in these clauses will benefit
greatly from an index.



Optimizing indexes based on usage patterns



In a system where lots of inserts and updations are expected, the indexes on the table
must be limited, because when records are inserted or updated, the indexes must be
updated as well.


On the other hand, in a query-centric system where few inserts are happening, all the
indexes needed to improve the query performance can be implemented. Limiting factor in
this case becomes the disk space.



Reasons for not indexing every column


Building an index takes time.

Disk space is required for each index in addition to the space used by the table.

When updating, inserting, or deleting rows the index is also dynamically maintained
to reflect any changes.

SQL SERVER 6.5
Chapter-5/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


CREATING INDEXES


SQL Server automatically creates an index for the PRIMARY KEY and UNIQUE
constraints ( if defined with CREATE TABLE statement.)

The other indexes have to be created explicitly using the CREATE INDEX statement.
The statement creates an index on column(s) in a table.


Syntax:


CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name

ON [ [ database.] owner.] table_name ( column_name [, column_name ]...)

[ WITH

[FILLFACTOR = fillfactor ]

[ [,] IGNORE_DUP_KEY ]

[ [,] { SORTED_DATA | SORTED_DATA_REORG}]

[ [,] { IGNORE_DUP_ROW | ALLOW_DUP_ROW }]]



Index rules

Only the owner of the table can CREATE or DROP the index.

Indexes can be created on tables in another database by qualifying the
database.table_name.

Indexes speed data retrieval but can slow data update.

Index can not be created on a view.

Index can not be created on columns defined with bit, text and image datatypes.

The various options for CREATE INDEX are covered in the following sections.

SQL SERVER 6.5
Chapter-5/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

UNIQUE

The option specifies to create a unique index in which no two rows are permitted to
have the same index value.

The system checks for the duplicate values when the index is created ( if data already
exists) and checks each time data is added with an INSERT or UPDATE statement.

If the duplicate values are found, statement is canceled (roll backed) irrespective of
the number of rows affected and an error message is returned.

A UNIQUE index can not be created on a column where the key is NULL in more
than one rows, because these are treated as duplicate values for indexing purpose.

EXAMPLE
Assuming a table called applicant is already existing which has a field called appl_id.

CREATE UNIQUE INDEX app_ind

ON applicant ( appl_id)

OUTPUT:

Creates an index called app_ind on the appl_id column of the applicant table that enforces uniqueness.



CLUSTERED

If the option is specified, the index will be created as a clustered index.

EXAMPLE
CREATE UNIQUE CLUSTERED INDEX app_clind

ON applicant (appl_id)





OUTPUT:

Creates an index called appl_clind on the appl_id column of the applicant table that enforces
uniqueness.
The index will physically order the data on the disk because the CLUSTERED is specified.

SQL SERVER 6.5
Chapter-5/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


NONCLUSTERED

Specifies that a nonclustered index is to be created.

This is the default index type.

If no index type is specified, a nonclustered index is created.

EXAMPLE
CREATE NONCLUSTERED INDEX app_nonind

ON applicant (fname)

OUTPUT:

Creates a noclustered index called appl_nonind on the fname column of the applicant table .



FILLFACTOR

When an index page fills up, SQL Server splits the data onto separate data pages to
make room for new rows. Page splitting is costly operation in terms of I/O and should
be thus avoided.

Specifying a FILLFACTOR tells SQL Server how to pack the index data into the
index data pages .

FILLFACTOR tells SQL Server to preserve a percentage of free space on the index
data page for other similar rows which will be inserted in the future and thus avoids
page splitting.

FILLFACTOR improves the performance by minimizing the amount of page splitting
that occurs each time the index page becomes full.
SQL SERVER 6.5
Chapter-5/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Specifying a FILLFACTOR when creating an index on a table without data has no
effect because SQL Server has no way of placing the data in the index correctly.

When using the FILLFACTOR option consider the following guidelines:

(a) Primarily used as an option to fine-tune performance.

(b) A small FILLFACTOR is useful for the table when inserting a lot of data after the
index creation. (except 0)


EXAMPLE

If a table is going to have many more values, a low FILLFACTOR of about 10 can be specified.

SQL Server will preallocate space in the index pages for those values so that it wont need to page split.
Thus, the data is spread over more pages, leaving space for the rows that you plan to add.



(c) A high FILLFACTOR will enforce more frequent page splits because SQL Server
will have no room on the index page to add any additional values. This option is
good for highly concurrent, read-only tables.

(d) User specified FILLFACTOR values can be from 1 through 100.

(e) For read-only databases, a FILLFACTOR of 100 is optimal.

(f) If FILLFACTOR is not specified , SQL Server uses the default FILLFACTOR
value to determine how much to fill an index page. The default value is 0. When
FILLFACTOR is 0 only, only the leaf pages are filled. Space is left in nonleaf pages
for at least one entry.


FILLFACTOR Internal page Leaf page
0%
one free slot
*
100% full
1-99%
one free slot
*
<= FILLFACTOR % FULL
100% 100% full 100% full
*
Two free slots for nonunique clustered indexes.

The FILLFACTOR is not maintained after the index is initially built. However, if index
pages become too full and page splits become a performance problem, indexes can be
dropped and rebuilt to reestablish the desired FILLFACTOR.
SQL SERVER 6.5
Chapter-5/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

EXAMPLE

CREATE NONCLUSTERED INDEX zip_ind

ON author (zip)

WITH FILLFACTOR = 100


OUTPUT:

FILLFACTOR option is set to 100.
It fills every index page completely .

NOTE : Useful only when it is known that no index values in the table will ever change.



IGNORE_DUP_KEY


Controls what happens when an attempt to enter a duplicate key in a unique clustered
index is made.

Meaningful only when the UPDATE or INSERT statement affects multiple rows.

If the IGNORE_DUP_KEY is specified, and an UPDATE or an INSERT statement
affecting several rows creates duplicate keys, then only the rows causing the
duplicates are ignored, the other rows are added or changed as usual.

No error message is generated for the duplicate value.

A unique index can not be created on a column that already includes duplicate values,
whether or not IGNORE_DUP_KEY is set.

EXAMPLE
CREATE UNIQUE CLUSTERED INDEX item_ind

ON items (item_id)

WITH IGNORE_DUP_KEY

OUTPUT:

Creates a unique clustered index called item_ind on the items table.
If a duplicate key is entered, transaction for that particular record is ignored.



SQL SERVER 6.5
Chapter-5/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

SORTED_DATA

Speeds up the index creation for clustered indexes.

Tells SQL Server, that data to be indexed is already physically sorted in the order of
the index.

SQL Server verifies by checking that each item is greater than the previous item.

If any discrepancy is found, an error is reported and index creation is aborted.

The option reduces the time and space required to create clustered index.

Time is reduced because no time is spent in ordering the data.

Space is reduced because there is no need for the temporary workspace required for
placing the sorted values before creating the index.


SORTED_DATA_REORG


Differs from SORTED_DATA because it physically reorganizes the data.

SORTED_DATA is faster than the SORTED_DATA_REORG because the data is
not copied and nonclustered indexes will not be rebuilt.

Using SORTED_DATA_REORG is a good idea when the table becomes fragmented.
Table fragmentation occurs through the process of data modifications (INSERT,
UPDATE and DELETE statements) made against the table.( Whether or not table is
fragmented, is determined from DBCC statement covered later)

SQL SERVER 6.5
Chapter-5/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


IGNORE_DUP_ROW
This option is for creating a nonunique clustered index.

This has no effect on nonclustered index because SQL Server internally assigns
identifiers to the records being indexed and doesnt have to manage the physical order
of the data according to the clustering.

ALLOW_DUP_ROW

Cant be set on an index thats allowed to IGNORE_DUP_ROW.

If enabled, no errors are returned and no data is affected if multiple duplicate records
are created in a clustered index.

The IGNORE_DUP_KEY, IGNORE_DUP_ROW, and ALLOW_DUP_ROW index
options control what happens when a duplicate row is created with the INSERT or
UPDATE statement.

The following table shows when these options can be used

Index type Options

Clustered IGNORE_DUP_ROW,
ALLOW_DUP_ROW
Unique clustered IGNOR_DUP_KEY
Nonclustered None
Unique nonclustered IGNORE_DUP_KEY


The following table illustrates how ALLOW_DUP_ROW and IGNORE_DUP_ROW
attempts to create a nonunique clustered index on a table that includes duplicate rows and
attempts to enter duplicate rows into a table.


Option set Table has duplicate rows Insert duplicate row

Neither option CREATE INDEX statement fails INSERT statement fails
ALLOW_DUP_ROW Statement is completed Statement is completed
IGNORE_DUP_ROW Index is created but duplicate
rows are deleted; error message is
returned.
All rows accepted except
duplicates; error message
is returned.

SQL SERVER 6.5
Chapter-5/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Displaying information about Indexes

SQL Server has two ways to show information about indexes.

(a) The graphical method via SQL Enterprise Managers Index Manager.
(b) The command-line method via the system stored procedure sp_helpindex.

sp_helpindex

Syntax:

sp_helpindex table_name

table_name is the unqualified table name because if the table is not in the active database,
the required database should be made active before executing the procedure.

sp_helpindex returns the first eight indexes found on a database table. It shows the name
of the index, its description (clustered / nonclustered / unique ) and description about the
keys.


Dropping indexes

When an index is no longer needed, it can be removed from a database and the storage
can be reclaimed.

Syntax:

DROP INDEX [owner.] table_name.index_name
[, [owner.]table_name.index_name...]

EXAMPLE
DROP INDEX member.mem_ind

OUTPUT:

The index called mem_ind of the table member is dropped.



Only the owners of the table can drop the index.

Doesnt apply to indexes created by PRIMARY KEY or UNIQUE constraints.

SQL SERVER 6.5
Chapter-5/20
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


PERFORMANCE ANALYSIS


Table scans Vs Index search

When executing a query, the optimizer has two choices:

(a) Scan the table.
(b) Use the index.

Optimizer performs the following:

Estimates how much work is involved if it uses the index versus how much work is
involved if it doesnt.

The optimizer then determines which method to use based on the information in the
distribution page.

Distribution pages are a sampling of data values that SQL Server uses to decide if the
index is useful. These provide a ratio of the number of rows for which the selection
clause will qualify to the number of rows in table. They are used to determine whether
it is more efficient to use the index or to scan the table. A distribution page occupies
one full data page.

Distribution pages are created when you run UPDATE STATISTICS command on
data containing indexes or when index is created on already existing data.

Performs a table scan if the table is small, or if it expects to return a large percentage
of rows.

Including the name of the indexed column, in the WHERE clause of SELECT
statement, improves the chance that the optimizer will use the index.


SHOWPLAN

Displays detailed information on the final access method that the optimizer chooses
for the query.
The information can be displayed by executing the SET SHOWPLAN ON statement.
Shows each step that optimizer uses in joining tables and which indexes, if any, to
choose to be the least costly method of accessing the data.
Useful to determine if the indexes that have been defined on a table are actually being
used by the optimizer.

SQL SERVER 6.5
Chapter-5/21
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Optimizer hints

If SQL Server fails to pick an index that should provide better performance and it
chooses some other index, then the use of the index providing the better performance can
be forced by specifying it in the FROM clause.

In most cases, optimizer should be allowed to pick the best optimization method, because
as data changes over time the index specified in the select statement may no longer be
efficient.

The following is an option that can be an optimizer hint:

SELECT ....

FROM table_name (INDEX = index_name | index_id) ...

This specifies the index name or ID to use for that table .

An index_id of 0 forces a table scan. An index_id of 1 forces the use of clustered index
(if exists). The other values of n are determined by the number of indexes on the table.

EXAMPLE
Example 1

SELECT last_name, first_name

FROM member ( INDEX = mem_ind)

WHERE last_name = SOLLY


OUTPUT:
The optimizer is used to force the use of the nonclustered index to retrieve rows from a table.


Example 2

SELECT last_name, first_name , hire_date

FROM emp ( INDEX = 0 )

WHERE hire_date > = 10/10/1996

OUTPUT:

The optimizer is forced for the table scan.

SQL SERVER 6.5
Chapter-5/22
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.



UPDATE STATISTICS
SQL Server keeps statistics about the distribution of key values for each index in the
distribution page.
This information is used to make decisions about which indexes to use in query
processing.
This requires to issue an UPDATE STATISTICS statement periodically - especially
after extensive changes to a table.
This is because a distribution page contains static information and the UPDATE
STATISTICS statement is required to update the information in the distribution page
based on the current data in a table.

Syntax:

UPDATE STATISTICS [[ database.] owner.] table_name [index_name]

UPDATE STATISTICS guidelines

Runs automatically when an index is created or recreated on a table that already
contains data.
UPDATE_STATISTICS creates one page of distribution statistics per index. This
information is used by the optimizer in deciding whether or not to use the index in
processing a query.
Whenever the distribution of data changes, execute UPDATE STATISTICS to keep
the information current.

EXAMPLE

Example 1

UPDATE STATISTICS loan

OUTPUT:

Will update the statistics for all indexes on the loan table .


Example 2

UPDATE STATISTICS loan loan_ind

OUTPUT:

Will update statistics for only the loan_ind index on the loan table.
SQL SERVER 6.5
Chapter-5/23
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DBCC commands
DBCC SHOW_STATISTICS
Displays the statistical information in the distribution page for an index on a specified
table.
Indicates the selectivity of an index (lower the density returned, higher the
selectivity).
It provides the basis for determining whether or not an index would be useful to the
optimizer.

Syntax:

DBCC SHOW_STATISTICS ( table_name, index_name )
The system function STATS_DATE can be used to see the last date the statistics were
updated.
DBCC_SHOWCONTIG
Determines if the table is heavily fragmented.
When the table is heavily fragmented, fragmentation can be reduced by dropping and
recreating a clustered index which will compact the data such that data pages are
essentially full again, However, level of fullness can also be configured with the
FILLFACTOR option.


Syntax:

DBCC SHOWCONTIG ( table_id, [index_id] )
CLASSROOM EXERCISES
1. What is the difference between SORTED_DATA and
SORTED_DATA_REORG?
2. Can an index be created on a temporary table?
SQL SERVER 6.5
Chapter-5/24
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
IMPLEMENTATION OF VIEWS
Views
A view is an alternate way of looking at data derived from one or more tables in the
database.
The user is allowed to see only selected pieces of information in the database.
DIAGRAM
APPLICANT
APPL_NO LAST_NAME FIRST_NAME ADDRESS
A001 BARR PETER CHURCH STREET
A002 ALLEN SAM PARK STREET
A003 M MARY POND DRIVE
View of
APPLICANT
APPL_NO LAST_NAME
A001 BARR
A002 ALLEN
A003 M
Views also allow you to define calculated or derived information.
EXAMPLE
A view definition can do computation on a column of a table and display the computed field as a field in
the view.
The computed field will appear as a regular column to the users view.
Users view
SQL SERVER 6.5
Chapter-5/25
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Advantages of view
Allow users to focus on the data of their interest only. Data that is not needed by the
users can be left out of the view.
Manipulation of the data is simplified by defining frequently used queries as views.
Customization of the users view of the database can be done which allows different
users to look at the information in the database specifically for their needs.
It provides security by allowing users to query and modify the data only which they
see; rest of the data is neither visible nor accessible. ( set by using CREATE VIEW
statement with CHECK OPTION).
To provide security, users access can be confined to :
(a) A subset of rows or columns of a base table.
(b) The rows that qualify for a join of more than one base table.
(c) A statistical summary of base table.
(d) A subset of another view or some combination of views and base tables.
With views data can be exported to other applications using bcp utility. (covered
later)
Creation of views
Views can be created by using Enterprise Manager or by Transact-SQL.

A view is stored as a separate object in the database.
Creating views by using Transact-SQL
Syntax:
CREATE VIEW [owner.] view_name
[(column_name [, column_name])]
[WITH ENCRYPTION]
AS select_statement [WITH CHECK OPTION]
WITH CHECK OPTION
By default, data modification statements on view are not checked to determine
whether the rows affected will be within the definition of the view .
SQL SERVER 6.5
Chapter-5/26
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
An INSERT statement can be issued on a view to add a row to an underlying table even if that row is
not defined by the view.
An UPDATE statement can be issued that changes a row so that the row no longer meets the criteria
for the view.
If above modifications should be checked, WITH CHECK OPTION should be used.
The WITH CHECK OPTION forces all data modification statements executed
against the view to adhere to the criteria set within the SELECT statement defining
the view.
When this option is set, on row modification through a view guarantees, that data will
remain visible through the view after the modification has been committed.
WITH ENCRYPTION OPTION
This option encrypts the syscomments entries that contain the text of the CREATE
VIEW statement.
Thus, the view definition can not be seen by anyone.
Querying the syscomments table or using sp_helptext will not allow the user to see
the view definition.
To unencrypt, the view should be dropped and recreated.
EXAMPLES
Projection (subset of column) example
CREATE VIEW twocolumns
AS
SELECT appl_no, last_name FROM applicant
SELECT * FROM applicant
SELECT * FROM twocolumns
OUTPUT:
A view called twocolumns is created which will allow the users to view only the two columns appl_no
and last_name.
The other two columns of the table applicant i.e first_name and address are not shown.
SQL SERVER 6.5
Chapter-5/27
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Appl_no last_name first_name address
-------- ---------- ----------- -------------
A001 BARR PETER CHURCH STREET
A002 ALLEN SAM PARK STREET
A003 M MARY PND DRIVE
( 3 row(s) affected)
appl_no last_name
-------- ---------
A001 BARR
A002 ALLEN
A003 M
( 3 row(s) affected )
Computed column example
CREATE VIEW fines_due
(title_no, member_no, Amt_due)
AS
SELECT title_no, mem_no, (fine_assessed fine_paid)
FROM loan
SELECT * FROM fine_due
A view of a view example
CREATE VIEW fines_due_view
AS
SELECT * FROM fines_due WHERE Amt_due > 15
SELECT * FROM fines_due_view
View restrictions
A view can be created only in the current database.
One must have permission to SELECT the objects referenced in the view definition
when using the view.
SELECT INTO cannot be used because it creates a temporary table, and temporary
tables cannot be referenced in views.
Outer joins should not be used in view definitions. Because querying such a view
with a qualification on a column from the inner table of the outer join, the result can
be unexpected.
A trigger or an index cannot be created on a view.
A view can reference a maximum of 250 columns.
CREATE VIEW statements cannot be combined with other SQL statements in a
single batch.
The UNION operator cannot be used within a CREATE VIEW statement.
SQL SERVER 6.5
Chapter-5/28
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Dropping views
When a view is dropped, the definition of the view is deleted. The DROP VIEW
statement removes a view from the database.
Syntax:
DROP VIEW [owner.] view_name [, [owner.] view_name...]
EXAMPLE
DROP VIEW fine_due
OUTPUT:
Drops the view fine_due
Displaying information
To display the text used to create a view, sp_helptext system stored procedure can be
used.
Syntax:
sp_helptext obj_name
EXAMPLE
sp_helptext fines_due_view
OUTPUT:
Displays the text of the view fines_due_view
To get a report of the tables or views on which a view depends, and of the objects that
depend on a view, system stored procedure sp_depends can be used.
Syntax:
sp_depends obj_name
SQL SERVER 6.5
Chapter-5/29
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Modifying data through views
Whenever data is modified through a view, the modification takes place at the table
level.
A view does not keep a separate copy of data.
A row cannot be inserted into a view unless the NOT NULL columns in the
underlying object have defaults.
Views cannot affect more than one underlying table.
EXAMPLE
Suppose a view is based on columns from two tables table1 and table2, then a modification to the view that
affects just table1 or just table2 is acceptable, but an update that affects both the underlying tables is not
permitted.
Modifications cannot be made to certain columns like, columns with computed
values, built in functions and row aggregate functions.
CLASSROOM EXERCISES
1. Is an INSERT statement allowed if a computed column exists within the view?
2. If a view is defined with a SELECT * clause, and the structure of the underlying
table is altered, what will be the result if the view is used?
SQL SERVER 6.5
Chapter-5/30
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LAB EXERCISES
1. Create a table called students with the following fields:
Rollno - int, Class - int , Name - varchar(10), Age - int, Sex - char(1)
2. Create an index on the column Name .
3. Create a clustered index on the column Rollno that enforces uniqueness. Notice
that index will physically order the data on the disk.
4. Create an index on the Rollno and Class columns of the students table.
5. Create a table called store which has following fields:
stor_id - int, stor_name- varchar(10), city - varchar(10), state - varchar(10),
zip - varchar(10)
6. Create a nonclustered index on the field zip, such that it fills every page
completely.
7. Create a unique clustered index on the table store on field stor_id, such that if a
duplicate key is entered, the INSERT or UPDATE statement will be ignored.
8. Use the sp_helpindex system stored procedure. What are the results?
9. Drop the index created on the Name field of the table students.
10. Execute the statement SET SHOWPLAN ON, and then query the table students
using the index key.
11. Execute the same query by using the index_id 0. Note whether index was
used.
12. Use the DBCC commands on the indexes created and analyze the results.
13. Create a view which will have the fields title, type and price from the table
titles.
14. Create a view called accounts which should have three field called title,
advance, amt_due from the titles table. The due amount is calculated as the
product of the price, royalty and ytd_sales.
15. Show the text of the view accounts.
16. Create a view called CAonly from the table authors who belong to the state
CA only. Any data modifications should apply only to the authors within the
state of California only. Verify by modifying the data for both with and
without the state CA.
SQL SERVER 6.5
Chapter-5/31
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
An index is a collection of data values of a column in a table and their corresponding
pointers to the rows where those values are physically represented in the table.
There are two types of indexes:
a) Clustered indexes - Actual data pages are a part of index. Physical order of the rows is
same.
b) Nonclustered indexes - Actual data pages are unordered.
Index is created using CREATE INDEX statement.
FILLFACTOR tells SQL Server to preserve a percentage of free space on the index page
for future expansion.
Indexes can be dropped by using DROP INDEX statement.
Distribution pages are a sampling of data values that SQL Server uses to decide if the
index is useful.
Distribution pages are updated using UPDATE STATISTICS command.
By using view a user is allowed to have a look at only selected pieces of information in
the database.
A view is created by using CREATE VIEW statement.
SQL SERVER 6.5
Chapter-6/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Designing Data Integrity
SCOPE
Data Integrity concepts
Entity Integrity
Domain Integrity
Referential Integrity
IDENTITY property
Defaults and rules
Creation
Implementation
Constraints
Defining constraints
Implementing constraints
Types of constraints
SQL SERVER 6.5
Chapter-6/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DATA INTEGRITY
What is data integrity
A critical issue in DataBase Management Systems is ensuring that the data in the
database adheres to a predefined set of rules.
These rules will be consistent with the processes the system supports.
The consistency and accuracy of the data stored in the database with respect to the
processes the system supports, is referred as data integrity.
Reasons for enforcing data integrity
Data integrity is enforced
(a) to prevent invalid data entry into the database tables.
(b) to enforce the rules that are associated with the information in the database.
Data integrity in Conventional system Vs SQL Server
Conventional system SQL Server
Requires data integrity logic to be coded
into each application.
Stores the data integrity logic in the
database itself.
DIAGRAM
Conventional System
Application
RULES
Application
RULES
Application
RULES
File Server
data
SQL SERVER 6.5
Chapter-6/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Advantages of storing data integrity logic in the database itself
Single control point for database consistency
Simplifies maintenance
When rules need to be changed, change is required at only one place- the SQL Server
database itself
Less costlier to define rules at database level
Data integrity at this level is optimized for fast performance
All applications can take advantage of the global rules, rather than building similar
logic in each individual application
Need for rules at the client is eliminated since all rules are stored with the data itself.

SQL Server offers two methods of defining data integrity logic on the data.
1. Create one global object and apply it to various parts of data in the database.(Defaults
and rules)
2. Create and apply data integrity logic at the object creation level. (Constraints)

Using the latter method, data integrity logic is built-in at the table level, which means
there is one less step (association) than there is if an object is created independently.


Types of data integrity

(a) Entity integrity
(b) Domain integrity
(c) Referential integrity



Microsoft Excel Visual Foxpro Visual Basic
File Server
data
Rules
SQL Server
SQL SERVER 6.5
Chapter-6/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Entity integrity

Requires that all rows in a table have a unique identification value, the primary key
value.
Lack of primary key restricts the usefulness of data, as its elements would not be
uniquely retrieved.
Searches or statistical analysis may be meaningless if record exists that are not
uniquely identifiable.
Primary key value can be changed and the whole row can also be deleted, both of
which depend on the level of integrity required between the primary key and foreign
key references.
Entity integrity is enforced through indexes, UNIQUE constraints or PRIMARY
KEY constraints.



Domain integrity

Specifies a set of permissible or possible data values that are valid for that field.
Also determines whether null values are allowed.
Enforced through the use of validity checking.
Also enforced by restricting the type ( through datatypes), the formats of the columns
(rules and constraints )or the range of possible values ( rules, FOREIGN KEY and
CHECK constraints).


Referential integrity

Refers to consistency among tables.
Ensures that the relationships among the primary keys ( in the referenced table) and
foreign keys ( in the referencing tables) are always maintained.
Ensures that key values are consistent.
Requires that there be no references to non-existent values.
A row in the referenced table can not be deleted, if a foreign key exists that refer to
the row.
Similarly, primary key in the referenced table also can not be changed, if a foreign
key exists that refer to the row. It would result in orphaned records.
A foreign key value can not be inserted into the referencing table, if no row with the
corresponding primary key exists in the referenced table.
SQL SERVER 6.5
Chapter-6/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
When referential integrity is enforced in SQL Server:
a) Adding records to the related table is not allowed when there is no associated record
in the primary table.
b) Changing values in the primary table is not allowed that would result in orphaned
records in a related table.
c) Deleting records from a primary table is not allowed when there are matching
related records
Enforcing data integrity
Enforcing data integrity involves preserving the consistency and correctness of the data
stored in the database by
(a) validating the contents of individual fields.
(b) verifying field values with respect to one another.
(c) validating data in file or table as compared to another file or table.
(d) verifying the successful and accurate updation of the database for each transaction.
Enforcement of data integrity can be categorized into procedural data integrity and/or
declarative data integrity.
Procedural data integrity
Implemented using triggers, stored procedures and views.

Triggers enforce procedural data integrity because they are automatically fired.

Views and stored procedures do not directly support data integrity, but help in
maintaining and supporting data integrity.

EXAMPLE

Views and stored procedures can be used in combination with triggers.

Triggers can call a stored procedure , the stored procedure code is automatically executed by the trigger
providing data integrity.

By placing the code in the stored procedure the code is available to both the user and the trigger.
The user can voluntarily execute the stored procedure.


SQL SERVER 6.5
Chapter-6/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Declarative data integrity

Declared as a part of the database definition.

More concise and less error prone than procedural data integrity.

Integrity checking is performed by DBMS, not by rules, stored procedures or triggers.

Declarative constraints are directly defined on the tables and columns with CREATE
TABLE / ALTER TABLE statements.

Enforced through the use of constraints that restrict the data values that can be
inserted into the database or as the result of an update.


Earlier releases of SQL Server enforced data integrity by using user-defined datatypes,
defaults, rules, triggers and stored procedures.

SQL Server 6.5 supports a variety of table definition extensions that achieve the same
results without requiring separate objects (rule and defaults) or additional steps to bind
these objects to various columns.


Integrity type Former options SQL Server 6.5 options

Entity Unique indexes PRIMARY KEY
UNIQUE KEY
IDENTITY property
Domain Datatypes, Defaults, Rules DEFAULT constraint
FOREIGN KEY constraint
CHECK constraint
Referential Triggers FOREIGN KEY constraint
CHECK constraint





SQL SERVER 6.5
Chapter-6/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

IDENTITY PROPERTY


IDENTITY property

Used to create columns called identity columns that contain system-generated
values.

The system generated values uniquely identify each row inserted into the table.

This feature can be used to generate sequential number (for example, Member
Number)

SQL Server automatically generates a value based on

(a) the previous identity value
(b) the increment specified for the column in the table definition.

IDENTITY property can be placed on any column and in any sequence.

Only one identity column can be created per table.

Rules for the IDENTITY property

Identity column can not be updated.
NULLs are not allowed in the identity column.
Identity column must be used with integer datatype ( int, smallint or tinyint), numeric
or decimal.
numeric and decimal datatypes must be specified with a scale of 0.
The increment value should be integer.

Syntax:

IDENTITY [ ( seed, increment) ]

IDENTITY parameters

Parameter Description Default

seed Specifies the starting value 1
increment Specifies the step used to increment the next value
( Decrementing a value can be done by using negative
numbers)
1

SQL SERVER 6.5
Chapter-6/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

EXAMPLE

Example 1

CREATE TABLE class
(
roll_no INT IDENTITY( 100, 2),
name VARCHAR(10)
)

INSERT class VALUES ('BILL')

INSERT class VALUES('JOHN')

SELECT * FROM class


OUTPUT:

(1 row(s) affected )

(1 row(s) affected )

roll_no name
----------- ----------
100 BILL
102 JOHN

(2 row(s) affected )

Creates a table called class with two columns : roll_no and name
The column roll_no uses the identity property.
Two records are inserted with the values for name column only.
The value is automatically taken and incremented for the roll_no column.
The starting value or seed is set to 100 i.e the roll_no for first record with the name BILL will be 100.
The increment value is 2 i.e. the roll_no for the second record with the name JOHN will be 102.
Thus, the values in the roll_no column will be 100, 102, 104 and so on.

Example 2

CREATE TABLE class1
(
roll_no INT IDENTITY( 104, -1),
name VARCHAR(10)
)

INSERT class1 VALUES ('BILL')

INSERT class1 VALUES('JOHN')

INSERT class1 VALUES('MARY')

SELECT * FROM class1

SQL SERVER 6.5
Chapter-6/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

OUTPUT:

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

roll_no name
----------- ----------
104 BILL
103 JOHN
102 MARY

(3 row(s) affected)

Creates a table called class1 with two columns : roll_no and name
The column roll_no uses the identity property.
Three records are inserted with the values for name column only.
The value is automatically taken and decremented for the roll_no column.
The starting value or seed is set to 104 i.e the roll_no for first record with the name BILL will be 104.
The decrement value is -1 i.e. the roll_no for the second record with the name JOHN will be 103.
Thus, the values in the roll_no column will be 104, 103, 102 and so on.



Using identity column

IDENTITYCOL keyword

IDENTITYCOL keyword allows to refer to an identity column. It is not necessary to
remember the column name that has the IDENTITY property defined.

When referencing data in a table, the keyword IDENTITYCOL can be used in place of
the identity column.

EXAMPLE
SELECT * FROM class1 WHERE IDENTITYCOL = 104

OUTPUT:

roll_no name
----------- ----------
104 BILL

( 1 row(s) affected )

Instead of using the column name roll_no, the keyword IDENTITYCOL has been used.
The record for roll_no 104 will be displayed roll_no being an identity column.

SQL SERVER 6.5
Chapter-6/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


The keyword can be qualified with a table name if necessary.
The keyword can be used in SELECT, UPDATE, DELETE and INSERT statements.


Seed value and Increment value

The two system functions IDENT_SEED and IDENT_INCR, return the IDENTITY
information for an object containing the identity column.


IDENT_SEED function


Syntax:


IDENT_SEED ( table / view )

Returns the seed value specified during creation of an identity column.

EXAMPLE

Example 1

SELECT IDENT_SEED(class)

OUTPUT:

-----------
100

( 1 row(s) affected )


Example 2

SELECT IDENT_SEED(class1)

OUTPUT:

-----------
104

( 1 row(s) affected )




SQL SERVER 6.5
Chapter-6/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

IDENT_INCR function

Syntax:

IDENT_INCR (table / view)

Returns the increment value specified during creation of an identity column.

EXAMPLE

Example 1

SELECT IDENT_INCR(class)

OUTPUT:

-----------
2

( 1 row(s) affected )


Example 2

SELECT IDENT_SEED(class1)

OUTPUT:

-----------
-1


( 1 row(s) affected )



Global variable

EXAMPLE

SELECT @@IDENTITY

OUTPUT:

--------
102

( 1 row(s) affected )

Shows the last row inserted during this session having the identity value.

SQL SERVER 6.5
Chapter-6/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Reusing IDENTITY values

While using the INSERT statement to insert the data into the table, value should not be
included for an identity column.

By default data cannot be inserted directly into an identity column, but if a row is
accidentally deleted, an identity value can be recreated.

The SET option IDENTITY_INSERT provides the ability to recover a row in the case of
an unwanted deletion.

The option :

Turns on the automatic generation of values by the system at the user level and relies
on the user to insert a value into the identity column.
Can be set by table owner, database owner or SA.
Can be set on by a user for one table at a time.
Can be set on by multiple users for one table at same time.
Doesnt enforce uniqueness. A UNIQUE index must be created to enforce the
uniqueness.


EXAMPLE
SET IDENTITY_INSERT Pubs.class ON

OUTPUT:

The IDENTITY_INSERT property is set ON.

After the IDENTITY_INSERT property is set ON, the identity column can be referenced in the INSERT
statement and values can also be inserted explicitly.

INSERT class (roll_no, name) VALUES (110, Jincy)

OUTPUT:

Inserts a row with a specified roll_no.
Note : The column list must be provided in the INSERT statement when IDENTITY_INSERT is on.
SQL SERVER 6.5
Chapter-6/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DEFAULTS AND RULES
There are several tools that SQL Server implements to help manage the information in
the system. In this section two of the tools - Rules and Defaults, are described.
Rules and Defaults are one of the methods of enforcing the data integrity.
Defaults and rules create objects that are bound to a column or a user-defined data type.
Rules Vs Defaults
Rules Defaults
Used to enforce value restrictions on
columns.
Suggest column values and provide a
value when a column is inserted into a
view that does not include that column.
Control the values that can be stored within
the table columns and within user defined
datatypes.
Supply a value for an inserted row when
users do not supply one with their
information to be inserted.
Rules and defaults can be defined and stored in the database but are still not enforced on
any columns. They must be bound to a column to enforce the Rule or Default.
Rules and defaults can be bound to multiple columns.
Defining Rules
Rules specify the restriction on the values that can be inserted into a table column or a
user-defined datatype.
Any data that is to be entered into either a column or user defined datatype on which
a rule has been defined, must meet the criteria defined for that column or user-defined
datatype.
Creating Rules
Syntax:
CREATE RULE [ owner.] rule_name
AS @condition_expression
SQL SERVER 6.5
Chapter-6/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
.
Following should be considered when creating rules.
Rules are created with the CREATE RULE statement, and then are bound to a
column or user-defined datatype with the sp_bindrule system stored procedure.
Data entered prior to the creation and binding of a rule is not checked.
Rules can be bound to a particular column, to a number of columns, or to all
columns in the database that have a given user-defined datatype.
When a value is entered SQL Server ,checks it against any rule that has been created
for the specified column.
A rule is stored as a separate database object, thus,
(a) If a table on which rule is applied is dropped , the rule remains available to be
applied against other tables.
(b) A rule can be applied not only to columns but also to the user-defined datatypes.
A column can have only one rule.
Rules use expressions that are applied to columns or user-defined datatypes to restrict
the allowable values that can be entered.
The expression can use :
(a) A function to perform the test on information, which returns a comparison value
which can be used to validate the value in the column.
(b) Comparison Operators like BETWEEN, LIKE, and IN which test the value and
make sure that it falls within the bounds which have been set for that column.
Parameters for the AS clause:
(a) Any name or symbol can be used to represent the value when writing the rule but
the first character must be @.
(b) AS clause reads like a WHERE clause .
(c) Substitutes the local variable or parameter with the inserted or updated value.
(d) Can reference the name of a parameter more than once in a rule.
EXAMPLE
CREATE RULE country_code
AS
@code IN(AS, BH , WE)
OUTPUT:
A rule is created which allows any of these three values: AS BH, or WE.
Binding rules
After a rule is created, sp_bindlrule system stored procedure is used to bind a rule to a
column of the table or to a user-defined datatype.
SQL SERVER 6.5
Chapter-6/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Syntax:
sp_bindrule rule_name, object_name [, futureonly]
Parameter Description
rule_name Name of the rule specified in the CREATE RULE statement.
object_name Name of the table and column, or the user-defined datatype to which the
rule is to be bound. If object_name is not of the form table.column, it is
assumed to be a user-defined datatype.
futureonly Applies to just user-defined datatypes not column names.
Existing columns of the user-defined datatype inherit the new rule unless
they have a rule bound directly to them or the futureonly option is used.
New columns of the user-defined datatype always inherit the rule.
Thus, futureonly prevents existing columns of a user-defined datatype
from inheriting the new rule.
EXAMPLE
Binding the rule to user-defined datatype
sp_bindrule country_code, countrytype
OUTPUT:
The rule country_code is bound to the user-defined datatype countrytype .


Binding the rule to a column

sp_bindrule country_code, world.country

OUTPUT:
The rule country_code is bound to the column country of the table world.
SQL SERVER 6.5
Chapter-6/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
FUTUREONLY example

sp_bindrule country_code, countrytype, FUTUREONLY

OUTPUT:
The rule country_code is bound to the user-defined datatype countrytype.
No existing columns of type countrytype are affected.
Unbinding rules
Unbinding a rule simply detaches the rule from the column or user-defined datatype.
The rule is stored in the database for further use until it is dropped.
Syntax:
sp_unbindrule object_name [, futureonly]
If the object_name parameter is not of the form table.column, SQL Server assumes
it is a user-defined datatype.
futureonly is used only when unbinding rule from a user-defined datatype. It prevents
existing columns of that datatype from losing this rule.
SQL SERVER 6.5
Chapter-6/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Defaults
A default specifies a value to be inserted into the column to which the object is bound.
Syntax:
CREATE DEFAULT [ owner.] default_name
AS constant_expression
Following should be considered before creating defaults:
If NOT NULL is specified for a column and for that column if default is not
specified, an error message is generated whenever someone fails to make an entry
into that column.
Built in functions that do not reference database objects can be included in the
constant_expression.
Column must be large enough for the default.
The default needs to be the same datatype as the column or user-defined datatype it
will be bound to.
DEFAULTS need to adhere to any CHECK constraints.
The defaults need to adhere to any rules for that columns.
The following table shows the relationship between the existence of a default and the
definition of a column as NULL or NOT NULL.
Column Definition No Entry,
No Default
No Entry,
Default
Entry NULL,
No Default
Enter NULL,
Default
NULL NULL Default NULL NULL
NOT NULL error Default error error
EXAMPLE
CREATE DEFAULT phone_def
AS
(000)353-7777
OUTPUT:
A default is created which inserts this default value to the column.
SQL SERVER 6.5
Chapter-6/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Binding defaults
After a rule is created, sp_bindefault system stored procedure is used to bind a rule to a
column of the table or to a user-defined datatype.
Syntax:
sp_bindefault default_name, object_name [, futureonly]
Parameter Description
rule_name Name of the rule specified in the CREATE DEFAULT statement.
object_name Name of the table and column, or the user-defined datatype to which the
default is to be bound. If object_name is not of the form table.column,
it is assumed to be a user-defined datatype
futureonly Applies to just user-defined datatypes not column names.
Existing columns of the user-defined datatype inherit the new default
unless they have a default bound directly to them or the futureonly option
is used.
New columns of the user-defined datatype always inherit the default.
Thus, futureonly prevents existing columns of a user-defined datatype
from inheriting the new default.
EXAMPLE
Binding the default to user-defined datatype
sp_bindefault phone_def, phonenumber
OUTPUT:
The default phone_def is bound to the user-defined datatype phonenumber.


Binding the default to a column

sp_bindefault titleno_def, title.title_no

OUTPUT:
The default titleno_def is bound to the column title_no of the table title.
SQL SERVER 6.5
Chapter-6/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Unbinding defaults
Unbinding a default simply detaches the default from the column or user-defined
datatype.
The default is stored in the database for further use until it is dropped.
Syntax:
sp_unbindefault object_name [, futureonly]
If the object_name parameter is not of the form table.column, SQL Server assumes
it is a user-defined datatype.
futureonly is used only when unbinding default from a user-defined datatype. It
prevents existing columns of that datatype from losing this default.
Dropping Defaults and rules
When dropping a default on a NULLs-allowed column SQL Server will insert NULL
as the value for that column if rows are added but, no value is entered.
When dropping a default on a NOT NULLs column, SQL Server will send an error
message if rows are added but no value is entered.
Syntax:
DROP DEFAULT [owner.]default_name
[,[,owner.] default_name...]
DROP RULE [owner.]rule_name
[,[,owner.] rule_name...]
Consider following when dropping defaults and rules
The DROP command removes the default and/or rule from the database.
Unbind defaults and rules from columns and user-defined datatypes before dropping
them.
Only the owner can drop defaults and rules.
Guidelines when binding rules and defaults
A bound default applies only to rows that are affected by the INSERT statement.
A bound rule applies only to rows that are affected by the INSERT and UPDATE
statement.
SQL SERVER 6.5
Chapter-6/20
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Default and rule datatypes must be compatible with column or user-define datatypes.
Default and rule can not be bound to a system datatype.
If a default or rule is bound to a user-defined datatype and a different default or rule is
bound to a column of that datatype, the default or rule bound to the column is the one
that will be used.
sp_helptext system stored procedure can be used to display the text of the defaults
and the rules.
CLASSROOM EXERCISES
1. Can a character rule be bound to a column of a numeric datatype?
2. Can a default be bound to a SQL Server supplied datatype?
3. How can a value be inserted into a table with just one column that has an
identity property?
SQL SERVER 6.5
Chapter-6/21
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CONSTRAINTS
Constraints are one of the methods to enforce data integrity.
These are application rules that SQL Server enforces for you.
They limit the possible values that users can enter into a column or columns.
Constraints are defined by using the CREATE TABLE statement or by using SQL
Enterprise Manager.
Constraints can be added to the existing table or can be dropped by using the ALTER
TABLE statement.
Guidelines for using constraints
When a table with constraints is dropped, all the constraint definitions are also
removed.
Constraint violation results in termination of current statement.
Triggers are executed after all the constraints have been evaluated.
Constraints can be applied at table level or column level.
sp_helpconstraint and sp_help system stored procedure can be used for help on
constraints.
Defining constraints
Constraints can be applied using CREATE TABLE or ALTER TABLE.
Constraint is separate from the tables structure, thus constraints can be dropped,
changed, or created without having to drop and recreate the table.
CREATE TABLE [database.[owner].] table_name
(
{ col_name column_properties [ constraint [constraint]]
| [[,] constraint]}
[[,] {next_col_name | next_constraint}]
)
ALTER TABLE [database.[owner].] table_name
[WITH NOCHECK]
[ADD
{ col_name column_properties [ constraint [constraint]]
| [[,] constraint]}
[[,] {next_col_name | next_constraint}] | [DROP [ CONSTRAINT]
constraint_name [, constraint_name]]
SQL SERVER 6.5
Chapter-6/22
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Implementing constraints
Constraints can be placed on either a column or table.
If it applies to a single column, it can be created as a column constraint.
If a constraint applies to multiple columns, it is a table level constraint.
Disabling constraint checking
Checking against a particular constraint when adding new data to a table can be
disabled by adding a NOCHECK clause to the ALTER TABLE statement.
Checking against all constraints on a table can be disabled by adding a NOCHECK
ALL clause.
However, this clause do not disable checking against PRIMARY KEY, UNIQUE and
DEFAULT constraints.
Enabling a constraint that has been disabled requires either executing another ALTER
TABLE statement that contains CHECK clause or executing an ALTER TABLE
statement that contains a CHECK ALL clause.
EXAMPLE
Example 1
ALTER TABLE member
NOCHECK CONSTRAINT con1
OUTPUT:
Disables the constraint con1, in the table member table.
Example 2
ALTER TABLE member
NOCHECK CONSTRAINT ALL
OUTPUT:
Disables all the constraints on the member table (except for the PRIMARY KEY and UNIQUE
constraints, which cannot be disabled.)
Types of constraints
SQL Server provides five types of constraints:
PRIMARY KEY
UNIQUE
FOREIGN KEY
DEFAULT
CHECK
SQL SERVER 6.5
Chapter-6/23
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
PRIMARY KEY constraint
Primary key is a column or combination of columns that uniquely identifies a row.
PRIMARY KEY constraint can be used to enforce entity integrity.
It ensures that no duplicate values are entered, and NULLs are not allowed.
Syntax:
[CONSTRAINT constraint_name ]
PRIMARY KEY [ CLUSTERED | NONCLUSTERED ]
(col_name [, col_name [, col_name]])
[WITH FILLFACTOR = number]
Rules:
Can be created on column or table level.
Enforced through the creation of UNIQUE index on the specified columns.
Can only be placed on a column defined as NOT NULL.
Table-level PRIMARY KEY constraints can specify one or more columns.
Column level PRIMARY KEY constraints are placed on that column.
Only one PRIMARY KEY constraint per table is permitted.
Can only add a primary key to a new column if that column uses the IDENTITY
property or the primary key has to be created on an existing column.
Specifying the WITH NOCHECK option will not prevent the PRIMARY KEY
constraint from validating existing data.
This constraint automatically creates a UNIQUE index.
This index is not visible to the user and cannot be dropped directly.
It is dropped when PRIMARY KEY constraint is dropped.
EXAMPLE
ALTER TABLE authors
ADD CONSTRAINT au_ident
PRIMARY KEY (au_name, au_fname, address)
OUTPUT:
Assigns three column composite primary key to the table authors.
UNIQUE CLUSTERED index is created on these columns.
If a PRIMARY KEY, UNIQUE constraint or a CLUSTERED index already exists on the table, it will
need to be dropped before adding a new constraint.
Otherwise, an error message will appear that there is a duplicate PRIMARY KEY constraint.
SQL SERVER 6.5
Chapter-6/24
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
UNIQUE constraint
Can be used to enforce the entity integrity on a non-primary key.
Specifies that no two rows can have the same index value.
Can be used for alternate candidate keys.
Similar to the PRIMARY KEY constraint except that it allows NULL.
Syntax:
[CONSTRAINT constraint_name ]
UNIQUE [ CLUSTERED | NONCLUSTERED ]
(col_name [, col_name [, col_name]])
[WITH FILLFACTOR = fillfactor]
Rules:
Can be created at the column or table level.
No two rows in a table can have the same non-null values.
Enforced through the creation of a UNIQUE clustered or non-clustered index on the
specified column(s).
Column datatype can allow a NULL value.
Can specify one or more column(s) from the table level.
Multiple UNIQUE constraints can be placed on a table.
If an INSERT or UPDATE violates the UNIQUE requirement of the index, a
constraint violation message is received.
EXAMPLE
ALTER TABLE stores
ADD
CONSTRAINT con1
UNIQUE NONCLUSTERED ( stor_name, city)
OUTPUT:
Adds a UNIQUE constraint on the stor_name and city columns.
SQL SERVER 6.5
Chapter-6/25
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
FOREIGN KEY constraint
Defines a multi-column foreign key reference to another table.
Used in conjunction with the REFERENCES constraint when the key comprises more
than one column.
Syntax:
[CONSTRAINT constraint_name ]
[FOREIGN KEY (col_name [, col_name [, col_name]])]
REFERENCES [owner.] ref_table [(ref_col [, ref_col [, ref_col]])]
Rules:
Number of columns and datatypes specified in the FOREIGN KEY statement must
match the number of columns and datatypes in the REFERENCES clause and must
be listed in the same order.
Can reference the PRIMARY KEY or a UNIQUE constraint of another table.
An index for FOREIGN KEY constraint is not created automatically.
Specifying the WITH NOCHECK option will prevent the FOREIGN KEY constraint
from validating existing data.
REFERENCE constraint require that data added to a table containing a REFERENCE
constraint must have a matching value in the table that it references.
EXAMPLE
ALTER TABLE juvenile
ADD
CONSTRAINT con2 FOREIGN KEY ( adult_memno)
REFERENCES adult( member_no)
OUTPUT:
Adds a FOREIGN KEY constraint to the juvenile table on the adult_memno column.
adult_memno field in juvenile table can have values only from the values present in the member_no
column of the table adult.
Order of processing
Constraints are checked before triggers.
The order of processing is rules, REFERENCES, CHECK, referenced by , and then
triggers.
SQL SERVER 6.5
Chapter-6/26
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DEFAULT constraint
It supplies a value, when the user doesnt enter one in a column.
DEFAULT constraints do not need binding.
Syntax:
[CONSTRAINT constraint_name]
DEFAULT { constant_expression | NULL}
{FOR col_name]
Rules:
Can be created at the column and/or table level.
Have the same definition and restrictions as the current SQL Server defaults.
Only one DEFAULT can be defined per column.
Cannot be placed on identity columns.
Allows system supplied values to be inserted when no value is specified. For
example, USER, CURRENT_USER etc.
EXAMPLE
ALTER TABLE member
ADD
CONSTRAINT df_add DEFAULT UNKNOWN FOR address
OUTPUT:
Adds DEFAULT constraint on the member table so that value UNKNOWN is automatically added to
the column if user does not supply a value.
SQL SERVER 6.5
Chapter-6/27
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CHECK constraint
Determines the type of data that can be entered in a particular column or in a column
that has a given user-defined datatype.
It is similar to a rule.
Multiple CHECK constraints can be applied to a single column.
Syntax:
[CONSTRAINT constraint_name]
CHECK [NOT FOR REPLICATION] expression
Rules:
Can be created at the column level or table level.
Used to limit the values that can be inserted into a column.
Can contain a user-specified search condition.
Cannot contain sub-queries.
Specifying the WITH NOCHECK option will prevent the CHECK constraint from
validating existing data.
Can reference other columns in the same table. Rules cannot.
NOT FOR REPLICATION prevents the specified CHECK constraint from being
enforced for the distribution process used by replication.
EXAMPLE
ALTER TABLE member
ADD
CONSTRAINT chk_name
CHECK (first_name LIKE [A-Z][A-Z][A-Z][A-Z]
OUTPUT:
Assuming the length of the column first_name to be 4, puts a check that only letters are allowed in the
name field.
SQL SERVER 6.5
Chapter-6/28
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Complete table definition
EXAMPLE
CREATE TABLE table1
(
pub_id char(4) NOT NULL
CONSTRAINT con1 PRIMARY KEY CLUSTERED
CHECK (emp_id IN (1000, 2000, 3000),
pub_name varchar(30) NULL,
city varchar(30) NULL,
state char(3) NULL,
DEFAULT (CA)
)
CLASSROOM EXERCISES
1. Can a default be bound to a column that already has a DEFAULT constraint.
2. Can a CHECK constraint coexist with a rule on a column?
3. Compare a default and a DEFAULT constraint.
4. Compare a rule and a CHECK constraint.
SQL SERVER 6.5
Chapter-6/29
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LAB EXERCISES
1. Create a table called master having following fields:
mem_id - identity, with seed of 100 and increment of 2.
mem_name - varchar(10)
salary - int
address - varchar(10)
city - varchar(10)
state - varchar(10)
2. Insert the following values into the table master.
mem_name - abc, salary - 2000, address - golf link,
city - Delhi, state - Delhi
3. Retrieve the above record from the table using IDENTITYCOL keyword.
4. Display the seed and increment value for the table master.
5. Insert another record of your choice into the table master.
6. Insert one more record in the table master with the value 100 in the identity
column.
7. Create rule called rule1 which should restrict the range of integers inserted
into the column ( >1000 and < 8000)
8. Create a default called def1 as UNKNOWN.
9. Bind the rule rule1 to the column salary and the default def1 to the column
address .
10. Insert a record in the table master with salary = 10000. Input other detail of
your choice.What is the output?
11. Insert the following record using DEFAULT.
mem_name - xyz, salary - 2000, city - Bho, state - MP
12. Unbind the rule and default from the columns.
13. Drop the rule and the default.
14. Create a table called emp which has the following fields
emp_id - Primary key constraint, and can consist of two initial alphabetic
characters, followed by five digit number.
fname - varchar (20), not null
job_id - smallint, should not be null, if user does not specify value,
the default should be 1
hire_date - datetime, by default system date should be entered.
15. Try out the examples given in the book which are relevant to your tables.
SQL SERVER 6.5
Chapter-6/30
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
The consistency and accuracy of the data stored in the database is referred as data
integrity.
Types of data integrity:
a) Entity integrity
b) Domain integrity
c) Referential integrity
IDENTITY property is used to create identity columns that contain system generated
value.IDENTITYCOL keyword allow to refer to an identity column.
IDENT_SEED function returns the seed value specified and IDENT_INCR returns the
increment value.
IDENTITY INSERT ON can be used to explicitly enter data into the column with the
IDENTITY property.
Rules specify the restriction on the values that can be inserted into a table column or a
user-defined datatype.
Defaults provide a value for an inserted row when users do not supply one.
CREATE RULE and CREATE DEFAULT statements are used to create rules and
defaults.
sp_bindrule - Binds a rule to a column or a user-defined datatype.
sp_bindefault - Binds a default to a column or a user-defined datatype.
sp_unbindrule - Unbinds a rule from a column or a user-defined datatype.
sp_unbindefault - Unbinds a default from a column or a user-defined datatype.
DROP statements are used to drop the rules and defaults.
Constraints are another method to enforce data integrity.
Constraints are defined using CREATE TABLE statement and added or dropped using
ALTER TABLE statement.
Types of constraints:
PRIMARY KEY constraint
FOREIGN KEY constraint
UNIQUE constraint
CHECK constraint
DEFAULT constraint
SQL SERVER 6.5
Chapter-7/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Programmability
SCOPE
Batches and Scripts
Flow-Control language
Cursors
Transaction log
Transaction Management
Locks
Types of locks
Locking items
Table locking options
SQL SERVER 6.5
Chapter-7/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
BATCHES AND SCRIPTS
Batches
A batch is a set of SQL statements submitted together and executed as a group.
A batch is compiled only once, and is terminated by an end-of-batch signal.
The end-of-batch signal is GO command.
Batches can be submitted through ISQL/w utility, command line utility or through
files (scripts) passed to isql.
A file submitted to isql can include more than one batch of SQL statements, if each
batch is terminated by the GO command batch separator.
If there is a syntax error in a batch, nothing in the batch will execute.
Scripts
Scripts are a series of batches submitted together.
DIAGRAM
SELECT...
UPDATE...
GO
BEGIN TRAN
.........
COMMIT TRAN
GO
...........
..........
GO
BATCH
BATCH
BATCH
SCRIPT
SQL SERVER 6.5
Chapter-7/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Combining statements in a single batch
When creating batches, certain statements can be combined to create a batch and others
cannot be combined.
Statements that can be combined Statements that cannot be combined
CREATE DATABASE CREATE PROCedure
CREATE TABLE CREATE RULE
CREATE INDEX CREATE DEFAULT
CREATE TRIGGER
CREATE VIEW
EXAMPLE
Valid batch
CREATE DATABASE
CREATE TABLE
GO
Invalid batch
CREATE DATABASE
CREATE TABLE
CREATE RULE
GO
Correct use of above batch in form of multiple batches
CREATE DATABASE
CREATE TABLE
GO
CREATE RULE
GO
Rules to be followed for batches
Rules and defaults cannot be bound to columns and then used within the same batch.
Thus, sp_bindrule and sp_bindefault cannot be used in the same batch as INSERT
and UPDATE statements that invoke the rule or default.
CHECK constraints cannot be defined and used in the same batch.
An object cannot be dropped and then referenced or recreated in the same batch.
You cannot alter the table and reference the new columns in the same batch.
SQL SERVER 6.5
Chapter-7/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CLASSROOM EXERCISES
Which one of the following batches are invalid and why?
1. DROP TABLE table1
CREATE TABLE table1
(col1 char(2), col2 int)
GO
2. CREATE VIEW view1 AS SELECT col1 FROM table1
GO
3. CREATE VIEW view1 AS SELECT col1 FROM table1
INSERT table1 VALUES (AB)
GO
SQL SERVER 6.5
Chapter-7/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
FLOW-CONTROL STATEMENTS
Using Flow-control statements
Transact-SQL contains several statements called Flow-control statements that are used to
change the order of execution of statements within a set of statements.
Thus, Flow-control statements :
Control the flow of execution of SQL statements within a set of statements such as
statement blocks and stored procedures.
Permit to organize statements to provide the capabilities of a conventional
programming language such as C or COBOL.
Flow-control keywords Description
DECLARE statement Defines local variables and cursors.
PRINT statement Prints a user-defined message.
RAISERROR statement Returns user-specified message in the same form as SQL
Server returns errors.
BEGIN...END Defines the start and the end of the block.
IF...ELSE Controls conditional execution within a batch.
WHILE Repeats statements while a specific condition is true.
BREAK Exits the innermost WHILE loop.
CONTINUE Restarts a WHILE loop.
CASE expression Makes an execution decision based .
RETURN statement Formally exits from a batch or a procedure.
WAITFOR statement Specifies a time interval or an event for executing a
transaction.
GOTO Transfers control from a statement to another statement
that contains a user-defined label.
SQL SERVER 6.5
Chapter-7/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Defining and using variables
Variables in Transact-SQL can be either local or global.
Local variables
Local variables are user-defined entities that are assigned values.
The variables are defined and assigned a datatype by using a DECLARE statement.
Initial value is assigned with a SELECT statement.
Syntax for declaring a local variable :
DECLARE @variable_name datatype [, @variable_name datatype]
Syntax for assigning values to local variables:
SELECT @variable_name = expression | SELECT statement
[, @variable_name = expression | SELECT statement]
[ FROM list_of_tables] [ WHERE expression]
[ GROUP BY...] [ HAVING...] [ ORDER BY...]
Guidelines for using local variables
Local variables are available for use within the same batch or procedure.
They are always referenced with an @ preceding their names.
The datatype of a local variable can be defined as a user-defined datatype as well as a
system datatype.
Local variable can not be defined as a text or image datatype.
Local variables should not be defined with the same name as system variables.
SQL SERVER 6.5
Chapter-7/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
Example 1
DECLARE @var char(40) /* Declares a variable
var of datatype char
*/
SELECT @var = Assigning value to local variable
/* Assigns a string to the
variable var */
PRINT @var /* Prints the string in the
variable var */
OUTPUT:
The string assigned to the variable var gets printed.
(1 row(s) affected)
Assigning value to local variable
Example 2
DECLARE @var char(40) /* Declares a variable
var of datatype char
*/
SELECT @var = "Assigning value to local variable"
/* Assigns a string to the
variable var */
PRINT @var /* Prints the string in the
variable var */
GO /* End of a batch */
PRINT @var /* Intended to print the
local variable var outside
the batch */
OUTPUT:
The PRINT statement inside the batch will print the contents of the variable var.
The PRINT statement outside the batch will give error, since the local variable is available only in the
batch in which it is declared.
(1 row(s) affected)
Assigning value to local variable
Msg 137, Level 15, State 2
Must declare variable '@var'.
SQL SERVER 6.5
Chapter-7/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Example 3
SELECT app_no, first_name FROM applicant /* Shows all the app_no and
first_name from the table
applicant*/
DECLARE @var char(35) /* Declares a variable
var of datatype char
*/
SELECT @var = first_name FROM applicant WHERE app_no='A006'
/* Assigns the first_name to
the variable var
whose app_no is A006*/
PRINT @var /* Prints the contents of the
variable var */
OUTPUT:
App_no and first_name of the table applicant are displayed first.
The first_name corresponding to the app_no A006 is ETHEL which is assigned to the variable
var.
The contents of the variable are printed.
app_no first_name
------ --------------------
A005 SABARINA
A006 ETHEL
A007 VERONICA
(3 row(s) affected)
(1 row(s) affected)
ETHEL
Example 4
DECLARE @var char(35) /* Declares a variable var of
datatype char */
SELECT @var = first_name FROM applicant /* Last value of the SELECT
statement is assigned to
the variable var*/
PRINT @var /* Prints the contents of
the variable var */
SQL SERVER 6.5
Chapter-7/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OUTPUT:
If a SELECT statement returns more than a single value, then the last value returned is assigned to the
variable.
The last value in the field first_name is VERONICA is assigned to the variable var.
(3 row(s) affected)
VERONICA
Global variables
Global variables are predefined and maintained by the system.
Global variables are not defined by your routines, they are defined at the server level.
Always referenced by preceding with @@ sign.
Global variables can be referenced to have a report on system activity or about your
operations.
Global variables Description
@@CONNECTIONS Total logins or attempted logins since
SQL Server was last started.
@@CPU_BUSY Amount of CPU time of SQL Server
work since SQL Server was last started.
@@CURSOR_ROWS The number of qualifying rows in the
last-opened cursor.
@@DBTS The value of the current timestamp
datatype for the database which is unique.
@@ERROR Last error number generated by the
system, 0 if successful.
@@FETCH_STATUS Status of the last FETCH statement.
@@IDENTITY Last inserted identity value.
@@IDLE Amount of idle time since SQL Server
was last started.
@@IO_BUSY Amount of SQL Server time spent in I/O
operations.
@@LANGID Language ID of the language currently
used.
@@LANGUAGE Name of the current language.
@@MAX_CONNNECTIONS Maximum simultaneous connections.
@@MAX_PRECISION Precision level for decimal and numeric
datatypes as currently set in the server.
@@MICROSOFTVERSION Version number used internally to track
the current version of the server.
SQL SERVER 6.5
Chapter-7/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Global variables Description
@@NESTLEVEL Nesting level of current execution.
@@OPTIONS Current values of query-processing SET options. (
Same as the configuration values for user options
in sp_configure.
@@PACK_RECEIVED Number of input packets read since SQL Server
was last started.
@@PACK_SENT Number of output packets written since SQL
Server was last started.
@@PACKET_ERRORS Number of errors occurred while SQL Server was
sending and receiving packets.
@@PROC_ID Currently executing stored procedure ID.
@@ROWCOUNT Number of rows affected by last query.
@@SERVERNAME Name of the local server.
@@SERVICENAME Name of the running service.
@@SPID Server process ID number of the current process.
@@TEXTSIZE Number of bytes of text or image data a SELECT
returns.
@@TIMETICKS Number of microseconds per-tick.
@@TOTAL_ERRORS Number of errors during read or write since SQL
Server was last started.
@@TOTAL_READ Number of disk reads by SQL Server since SQL
Server was last started.
@@TOTAL_WRITE Number of disk writes by SQL Server since SQL
Server was last started.
@@TRANCOUNT Number of currently active transactions for the
current user.
@@VERSION Date and version number of current SQL Server.
EXAMPLE
print @@servicename /* Prints the name of the
running service*/
declare @mess char(40) /* Declares a variable mess
of the datatype char */
select @mess = 'Server name is ' + @@servername
/* Global variable
@@servername retrieves
the name of the local
server which is
concatenated with the
string and assigned to
the variable mess */
print @mess /* Prints the contents of
the variable mess */
SQL SERVER 6.5
Chapter-7/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OUTPUT:
The name of the running service is printed and then the contents of the variable mess are printed.
MSSQLServer
(1 row(s) affected)
Server name is NTCCSERVER
PRINT statement
Used to display characters enclosed in quotes, or variables.
Maximum number of characters that can be displayed is 255.
The local and the global variable must be of the type char or varchar.
Syntax:
PRINT text | @local_variable | @@global_variable
EXAMPLE
Example 1
PRINT Printing through PRINT statement /* Prints text enclosed in
quotes */
OUTPUT:
The string enclosed in the quotes gets printed.
Printing through PRINT statement
SQL SERVER 6.5
Chapter-7/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Example 2
DECLARE @num int /* Declares a variable num
of the datatype int */
SELECT @num = 12 /* Assigns the value 12 to
the variable num */
DECLARE @charnum char(2) /* Declares a variable
charnum of datatype char*/
SELECT @charnum = CONVERT(char(2), @num) /* Converts the value
stored in the variable
num to character for
printing and assigns to
the variable charnum */
PRINT @charnum /* Prints the contents of
the variable charnum */
OUTPUT:
The value stored in the variable num gets printed by the PRINT statement after its conversion to
datatype char.
(1 row(s) affected)
(1 row(s) affected)
12
Example 3
DECLARE @cnt int /* Declares a variable
cnt of datatype int */
SELECT @cnt = COUNT(*) FROM member /* Assigns the number of
rows in the table member
to the variable cnt */
DECLARE @cntchar char(2) /* Declares a variable
cntchar of datatype char
*/
SELECT @cntchar = CONVERT(char(2), @cnt) /* Converts the count
stored in the variable
cnt to character for
printing and assigns to
the variable cntchar */
DECLARE @mess char(40) /* Declares a variable mess
to print the message */
SELECT @mess = There are + @cntchar + rows in the table Member
/* Assigns the string to
the variable mess */
PRINT @mess /* Prints the string */
SQL SERVER 6.5
Chapter-7/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OUTPUT:
The count of the rows in the table member gets stored in the variable cnt.
The count stored in the variable cnt is converted to character for printing and assigned to the variable
cntchar.
The string is printed by the PRINT command.
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
There are 4 rows in the table member
Example 4
declare @mess char(3) /* Declares the variable
mess of the datatype
char */
select @mess = convert(char(3),@@rowcount)/* Converts the value
returned by the global
variable into character
value and assigns it to
the variable mess */
print @mess /* Prints the value in the
variable mess */
OUTPUT:
The value returned by the global variable is converted to character value and is assigned to the variable
mess.
The value in the variable is printed.
(1 row(s) affected)
1
String data can not be concatenated directly in a PRINT statement. Text and variables
must be concatenated into a single variable and output that variable with the PRINT
statement.
SQL SERVER 6.5
Chapter-7/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
Wrong usage:
DECLARE @var char(2) /* Declares a variable num
of datatype int */
SELECT @var = ABC /* Assigns the string
ABC to the variable
var */
PRINT @var +is of datatype char /* Wrong usage for printing
the string */
OUTPUT:
The concatenated string will not be printed by the PRINT statement.
The following error will be generated.
Msg 170, Level 15, State 1
Line 5: Incorrect syntax near '+'.
Correct usage:
DECLARE @var char(3) /* Declares a variable num
of datatype int */
SELECT @var = ABC /* Assigns the string
ABC to the variable
var */
DECLARE @mess char(40) /* Declares a variable mess
to print the message */
SELECT @mess = @var+ is of datatype char/* Assigns the string to
the variable mess */
PRINT @mess /* Prints the string */
OUTPUT:
The concatenated string is assigned to the variable mess and is then printed by the PRINT statement.
(1 row(s) affected)
(1 row(s) affected)
ABC is of datatype char
SQL SERVER 6.5
Chapter-7/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
RAISERROR statement
RAISERROR returns a user-defined error message in the same form that SQL Server
returns errors. It sets a system flag to record that an error has occurred.
Format in which SQL Server return error messages
Following is the sample format in which SQL Server returns errors.
Msg 208, Level 16, State 1
Invalid object name 'trial'.
Msg 208 Error number
Error message number stored in the sysmessages table.
Invalid object name 'trial'. Error text
The text of the message associated with the error number 208. It is also stored in the
sysmessages table.
Level 16 Severity level
Severity level associated with the message. Severity level is used to indicate the degree of
the error encountered.
Severity levels are in the range of 1 to 25. Larger the number, greater is the severity.
State 1 State
State is an integer value from 1 through 127 that represents information about the
invocation state of an error.
User-defined error messages
Following is the syntax for defining the user-defined messages in the form SQL Server
returns its errors.
Syntax:
RAISERROR ( { mess_id | text of message} , severity , state
[, argument1] [, argument2]
[ WITH LOG]
SQL SERVER 6.5
Chapter-7/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
mess_id
It is the user-specified error number and must be in the range 50,000 to
2,147,483,647.
It is stored in the sysmessages system table using system stored procedure
sp_addmessage. ( Syntax is following this section)
text of message
User-specified error message can be specified as a string literal in the form of text of
message or through a local variable in place of text of message.
It is also stored in the sysmessages table using system stored procedure
sp_addmessage.
The error message can have as many as 255 characters.
severity
It is the user-defined severity level associated with the message.
Severity levels 0 through 18 can be used by any user.
For severity levels 19 through 25, the WITH LOG option is required.
Only the system administrator can issue RAISERROR with a severity level of 19
through 25.
state
It is an integer value from 1 through 127 that represents information about the
invocation state of an error.
If -1 is specified for state, it defaults to 1.
Adding user-defined messages using Stored Procedure
Syntax:
sp_addmessage mess_id, severity, text of message [, language [, REPLACE]]
language specifies one of the languages SQL Server was installed with.
REPLACE is used to specify that you want to replace an existing user-defined
message in the sysmessages table with a new entry.
SQL SERVER 6.5
Chapter-7/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
sp_addmessage 99999,13, 'User defined error' /* Adds a message to the
sysmessages table
with error number
99999 and severity 13
*/
SELECT * FROM sysmessages WHERE error = 99999
/* Displays that the
message has been
added to the
sysmessages table */
RAISERROR (99999, 13,1) /* Raises the error */
OUTPUT:
The message gets added to the sysmessages table.
With the RAISERROR statement, the user-defined error message is displayed in the form the SQL
Server returns the error.
New message added.
error severity dlevel description langid
------ -------- ------ ----------------- ------
99999 13 0 User defined error 0
(1 row(s) affected)
Msg 99999, Level 13, State 1
User defined error
Dropping user-defined messages using Stored Procedure
Syntax:
sp_dropmessage mess_id
EXAMPLE
sp_dropmessage 99999
OUTPUT:
Message dropped.
SQL SERVER 6.5
Chapter-7/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Generating user-defined error without storing the message into the sysmessages
table
EXAMPLE
Example 1
DECLARE @var int /* Declare the variable var of
datatype int */
SELECT @var=1 /* The value 1 is assigned to the
variable var */
IF @var < 2
RAISERROR 55555 'User-defined error'
/* If the value of var is < 2,
error is raised with the user-
defined error number and he
associated message */
OUTPUT:
The value in the variable var is less than 2, thus the RAISERROR statement will get executed.
When level and state are not provided, the default values 16 and 1 are taken for the level and state
respectively.
(1 row(s) affected)
Msg 55555, Level 16, State 1
User-defined error
Example 2
raiserror ('Error not given the error number', 12,1)
/* Raises the error with the text
given in single quotes and the
error number 50000 */
OUTPUT:
The user-defined error will have the message number 50000.
All user-defined messages generated with RAISERROR statement , without a number in sysmessages
table , return a message_id of 50000.
Msg 50000, Level 12, State 1
Error not given the error number
SQL SERVER 6.5
Chapter-7/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Example 3
RAISERROR (70000, 13, 1) /* Statement to raise error with
error number 70000 which
doesnt exist in the
sysmessages table*/
OUTPUT:
If a user-specified error number has not been added to the sysmessages table and the message text has
not been specified, a system error message will be generated.
Msg 2758, Level 16, State 1
RAISERROR could not locate entry for error 70000 in Sysmessages.
arguments
If the message created is to be supplied with some arguments , then supplied
arguments (argument1, argument2, and so on) will be passed to the message.
The following format is supported for text of message when arguments are used:
text of message %type
Type Description
d or i Signed integer
o Unsigned octal
p Pointer
s String
u Unsigned integer
x or X Unsigned hexadecimal
EXAMPLE
Example 1
raiserror ( 'User defined error %s', 13, 1, 'argument supplied')
/* The argument argument
supplied is supplied to the %s
of the string enclosed in the
quotes */
OUTPUT:
The %s in the user-defined string takes the parameter from the specified argument.
Msg 50000, Level 13, State 1
User defined error argument supplied
SQL SERVER 6.5
Chapter-7/20
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Example 2
sp_addmessage 99999,13, 'User defined error - %s'
/* A message is added to the
sysmessages table. The text of
the message expects a
parameter at the time of
execution */
raiserror ( 99999, 13, 1, 'argument supplied')
/* The string argument supplied
is specified as an argument to
the message number 99999 */
OUTPUT:
When the message with the number 99999 (stored in sysmessages table ) is raised, an argument is
supplied.
The argument is taken up as a parameter by the text of the message stored in the sysmessages in place
of %s.
The full string gets printed.
New message added.
Msg 99999, Level 13, State 1
User defined error - argument supplied
WITH LOG
Logs the error in the server error log and the event log.
This option is generally required for messages with a severity level of 19 through 25
It can be issued only by the system administrator.
If severity is 19 to 25, the client connection will be terminated after receiving the
message and the error will be logged in the error log and the event log.
Usage of @@ERROR
When an error is raised, the error number is placed in the global variable
@@ERROR, which stores the error number most recently generated by the system.
@@ERROR is set to 0 if the severity is between 1 and 10 inclusive.
Messages with severity levels 10 and under are not errors, but they do provide
additional information.
SQL SERVER 6.5
Chapter-7/21
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
Example 1
DECLARE @err char(20) /* Declares a variable err of
datatype char */
RAISERROR ('error with severity between 1 and 10', 2, 1)
/* An error is raised with
severity level 2 */
SELECT @err = CONVERT( char(20), @@error)
/* The variable err is assigned
the value stored in the global
variable @@error */
PRINT @err /* The value in the variable err
is printed */
OUTPUT:
The value 0 will be printed, since the severity level is 2.
Msg 50000, Level 2, State 1
error with severity between 1 and 10
(1 row(s) affected)
0
Example 2
DECLARE @err char(20) /* Declares the variable err of
datatype char */
RAISERROR ('error with severity greater > 10', 12, 1)
/* An error is raised with
severity level 12 */
SELECT @err = CONVERT( char(20), @@error)
/* The variable err is assigned
the value stored in the global
variable @@error */
PRINT @err /* The value in the variable err
is printed */
SQL SERVER 6.5
Chapter-7/22
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OUTPUT:
@@error will have the value 50000, since the severity level is 12.
Msg 50000, Level 12, State 1
error with severity greater > 10
(1 row(s) affected)
50000
BEGIN...END
A series of statements enclosed by BEGIN and END is called a statement block. The
statement block is executed as a unit.
The keyword BEGIN is used to define the start of the block of transact-SQL
statements.
The keyword END is used after the last Transact-SQL statement that is part of the
same block of statements.
Syntax:
BEGIN
[SQL statements | statement block]
END
Statement blocks are often used with IF...ELSE and WHILE flow control statements.
If BEGIN and END are not used, only the first statement immediately following the
IF...ELSE or WHILE is executed.
EXAMPLE
IF EXISTS ( SELECT * FROM member where first_name='BETTY')
BEGIN
PRINT 'entry found for BETTY'
SELECT last_name FROM member where first_name = 'BETTY'
END
/* The PRINT and SELECT
statements are enclosed in a
block. */
ELSE
PRINT 'entry not found for BETTY'
SQL SERVER 6.5
Chapter-7/23
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OUTPUT:
The IF condition evaluates to true.
The statements enclosed in the BEGIN and END keywords get executed.
entry found for BETTY
last_name
--------------------
COOPER
(1 row(s) affected)
IF...ELSE block
IF and ELSE keywords are used to control conditional execution of SQL statements.
The condition for testing is defined as an expression following the keyword IF. The
syntax of an IF...ELSE statement is as follows:
Syntax:
IF expression
SQL_statement | statement_block
[ELSE]
[IF expression]
SQL_statement | statement_block
The SQL statement / statement block which follows the IF keyword and the
conditional expression, is executed if the condition is satisfied.
The optional ELSE keyword specifies an alternative SQL statement / statement block
that is executed when the IF condition is not specified.
There is no limit to the number of nesting levels in IF.

EXAMPLE
Example 1
IF EXISTS ( SELECT * FROM member where first_name='BETTY')
PRINT 'entry found'
/* EXISTS statement is evaluated
for True/False.
Checks the existence of the
first_nameBETTY in the
member table.
Prints entry found if
condition satisfied */
PRINT 'entry not found' /* Prints the string entry not
found */
SQL SERVER 6.5
Chapter-7/24
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OUTPUT:
EXISTS statement evaluates to true, since the entry is found in the member table.
Thus, prints the statement following the IF statement i.e. entry found.
The message entry not found is also displayed because ELSE option is not used.
entry found
entry not found
Example 2
IF EXISTS (SELECT * FROM member where first_name='BILL')
PRINT 'entry found'
/* EXISTS statement is evaluated
for True/False.
Checks the existence of the
first_nameBILL in the
member table.
Prints entry found,only if
condition is satisfied */
PRINT 'entry not found' /* Prints the string */
OUTPUT:
EXISTS statement evaluates to false, since the entry is not found in the member table.
Thus, does not print the statement following the IF statement i.e. entry found does not get printed.
The message entry not found is displayed.
entry not found
Example 3
IF EXISTS ( SELECT * FROM member where first_name='BILL')
PRINT 'entry found for BILL'
/* EXISTS statement is evaluated
for True/False.
Checks the existence of the
first_nameBILL in the
member table.
Prints entry found for BILL
if condition satisfied */
ELSE
IF EXISTS ( SELECT * FROM member where first_name='BETTY')
PRINT 'entry found for BETTY'
/* EXISTS statement is evaluated
for True/False.
Checks the existence of the
first_nameBETTY in the
member table.
Prints entry found for BETTY
if condition satisfied */
SQL SERVER 6.5
Chapter-7/25
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OUTPUT:
EXISTS statement in the IF part evaluates to false, since the entry is not found in the member table.
Thus, does not print the statement following the IF statement i.e. entry found for BILL does not get
printed.
Executes the ELSE part.
Displays the string entry found for BETTY, since the IF condition in the ELSE part is satisfied.
entry found for BETTY
Example 4
IF EXISTS ( SELECT * FROM member where first_name='BETTY')
BEGIN
PRINT 'Printing block'
PRINT 'entry found for BETTY'
END
ELSE
IF EXISTS ( SELECT * FROM member where first_name='BILL')
PRINT 'entry found for BILL'
OUTPUT:
EXISTS statement in the IF part evaluates to true, since the entry is found in the member table.
Thus, all the statements following the IF statement i.e. the statements in the statement block get
printed.
Printing block
entry found for BETTY
SQL SERVER 6.5
Chapter-7/26
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CLASSROOM EXERCISE
What will be the output of the following:
1.
IF EXISTS ( SELECT * FROM member where first_name='BILL')
PRINT 'entry found for BILL'
ELSE
IF EXISTS ( SELECT * FROM member where first_name='BETTY')
PRINT 'Printing block'
PRINT 'entry found for BETTY'
2.
IF EXISTS ( SELECT * FROM member where first_name='BILL')
PRINT 'entry found for BILL'
PRINT Printing IF part
ELSE
IF EXISTS ( SELECT * FROM member where first_name='BETTY')
PRINT 'Printing ELSE part'
PRINT 'entry found for BETTY'
SQL SERVER 6.5
Chapter-7/27
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
WHILE construct
The WHILE construct defines a condition for the repeated execution of a SQL
statement or a statement block.
The statements continue to execute as long as the condition tested is true.
Syntax:
WHILE expression
SQL statement | statememt block
EXAMPLE
declare @a int /* Declares a variable a of
datatype int */
select @a=1 /* Initialises the variable a
with the value 1 */
while @a<3 /* Specifies the condition in the
WHILE construct */
begin /* Begin of the block */
print'a still less than 3' /* Prints the statement */
select @a=@a+1 /* Increments the value of a */
end /* End of the block */
OUTPUT:
The control goes inside the WHILE construct twice.
The statement enclosed in quotes is printed twice.
(1 row(s) affected)
a still less than 3
(1 row(s) affected)
a still less than 3
(1 row(s) affected)
Using BREAK and CONTINUE
The execution of statements in the WHILE loop can be controlled from inside the loop
with BREAK and CONTINUE keywords.
SQL SERVER 6.5
Chapter-7/28
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
BREAK
BREAK causes an exit from the WHILE loop.
The execution of a BREAK results in the first statement following the end of the
block to begin executing.
EXAMPLE
declare @a int
select @a=1
while @a<3
begin
print'a still less than 3'
select @a=@a+1
break /* Breaks out of the WHILE loop
*/
end
print'Has come out of WHILE'
OUTPUT:
The control goes inside the WHILE construct once.
When the BREAK is encountered, it exits the WHILE construct
The control goes to the next statement following the WHILE construct, thus the last statement is
printed.
(1 row(s) affected)
a still less than 3
(1 row(s) affected)
Has come out of WHILE
SQL SERVER 6.5
Chapter-7/29
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SQL SERVER 6.5
Chapter-7/30
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CONTINUE
CONTINUE causes WHILE loop to restart the loop.
EXAMPLE
declare @a int
select @a=1
while @a<3
begin
print'a still less than 3'
select @a=@a+1
continue /* Sends the control to the begin
of the loop */
print'This statement will not print'
end
OUTPUT:
The control goes inside the WHILE construct twice.
When the CONTINUE is encountered, the control goes to the first statement of the WHILE construct
after the condition check.
Thus, the statement right after the CONTINUE doesnt get printed
(1 row(s) affected)
a still less than 3
(1 row(s) affected)
a still less than 3
(1 row(s) affected)
SQL SERVER 6.5
Chapter-7/31
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Using WHILE, BREAK and CONTINUE together
EXAMPLE
DECLARE @a int, @b int /* Declares two variables a and b of
datatype int */
SELECT @a=0, @b=1 /* Initialises the variable a to 0 and b
to 1 */
WHILE @a=0 /* Sets an infinite loop, since value
of a will always be 0 */
BEGIN
PRINT'Inside loop'
SELECT @b=@b+1 /* Increments the value of b*/
IF @b>3
BREAK /* If the value of b becomes greater
than 3, exits out of the infinite
loop */
ELSE
CONTINUE /* If the value of b is lesser than 3,
executes the WHILE loop */
END
PRINT'Out of While loop' /* Prints the string */
OUTPUT:
The WHILE loop is infinite, since the value of the variable a will always be zero.
The WHILE loop is exited only when the value of the variable b becomes greater than 3.
Otherwise the WHILE loop is executed repeatedly.
(1 row(s) affected)
(1 row(s) affected)
Inside loop
(1 row(s) affected)
Inside loop
(1 row(s) affected)
Inside loop
(1 row(s) affected)
Out of While loop
SQL SERVER 6.5
Chapter-7/32
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXECUTE statement
The EXECUTE statement can be used to execute the following:
A system procedure, a user-defined stored procedure or an extended stored procedure
can be executed.
EXAMPLE
EXEC user_def_stor_proc
A command composed of character string within a Transact-SQL batch can be
executed.
A string can be created with variables that are resolved at execution time.
EXAMPLE
declare @var char(20)
select @var = table1
exec(select * from + @var)
Guidelines for EXECUTE statement
All items within the EXECUTE string must consist of character data.
Functions cannot be used to build the string to be executed.
Any valid Transact-SQL statements, including functions are available to be passed
within the Transact-SQL string.
Nested execute statements are permitted.
String literal, string local variable, concatenation of string literals and string local
variables can be included in the EXECUTE statement.
Syntax:
EXECute ({@string_var | TSQL_string}+[{@string_var | TSQL_string}...])
SQL SERVER 6.5
Chapter-7/33
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SQL SERVER 6.5
Chapter-7/34
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
CREATE PROC a2
as
set nocount on
SELECT '*** Database : ' + db_name()
DECLARE @var char(30)
SELECT @var = ' '
WHILE @var is not null
BEGIN
SELECT @var=min(name) FROM sysobjects WHERE type='U' AND name
>@var
/* sysobjects is a system table which stores information about all the
objects in the database. U in the field type indicates,that the
object is a user-defined table */
IF @var is not null
begin
exec ('select * from ' + @var)
end
END
exec a2
OUTPUT:
A stored procedure is created that issues an EXECUTE statement that iterates through all the user-
defined tables in the database and shows all the fields and rows of each table in the database.
This eliminates the need to issue the EXECUTE statement explicitly for every table.
---------------------------------------------
*** Database : newdatabase
rollno Eng maths science grade
------ ------ ------ ------- -----
01 77 90 97 a
02 10 30 97 b
01 67 56 78 b
01 67 56 78 b
rollno name Class
------ ---------- -----
01 HARY 1
02 MARY 1
RETURN statement
It returns from a query or procedure unconditionally.
Statements following the RETURN are not executed.
SQL Server reserves 0 to indicate a successful return and different negative value for
different reasons of failure. (-1 to 99).
If no user-defined value is provided, the SQL Server value is used.
SQL SERVER 6.5
Chapter-7/35
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Syntax:
RETURN [integer_expression]
EXAMPLE
CREATE PROC a1 @param char(2)
AS
IF (SELECT eng_marks FROM detail WHERE roll_no = @param) <= 50
RETURN 1
ELSE
RETURN 2
To capture a returned integer value, execute the stored procedure in the following
format.
EXECUTE @return_status = procedure_name
EXAMPLE
DECLARE @status int
EXEC @status = a1
WHILE @status = 1
BEGIN
PRINT Query successful
BREAK
END
Note: The variable @status must be declared in the batch or stored procedure before it is used in an
EXECUTE statement
CASE Expression
Provides a means of returning a value based on whether a specific expression is true.
A CASE statement is like a nested IF statement within a SELECT statement
A CASE statement lists one or more predicates and gives a value for each.
The predicates are then tested in the order listed.
As soon as one is found to be true, the CASE expression returns the corresponding
value to the SELECT statement that contains it.
Within a SELECT statement, a simple CASE expression allows only an equality
check; no other comparisons are made.
SQL SERVER 6.5
Chapter-7/36
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Syntax:
CASE expression
WHEN expression THEN expression
[[WHEN expression2 THEN expression2] []]
[ELSE expression]
END
EXAMPLE
SELECT name, division =
CASE department
WHEN sales THEN Sales and Marketing
WHEN Field Service THEN Support group
ELSE Other department
END,,
Badge FROM company
OUTPUT:
Name division badge
---------- ---------------- ------
Fred Sales and Marketing 8367
Jin Support group 8363
Sally Sales and Marketing 6763
Stan Other department 3535
( 4 row(s) affected )
CASE-related system functions
The NULLIF function
It relates two values or expressions.
If the two are equal, returns NULL.
SQL SERVER 6.5
Chapter-7/37
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Syntax:
NULLIF (expression1, expression2)
EXAMPLE
SELECT NULLIF(3, 3)
OUTPUT:
Returns NULL.
------
NULL
(1 row(s) affected )
The COALESCE function
Returns a replacement value for any NULL or NOT NULL values that are present
Syntax:
COALESCE (expression1, expression2,expressionN)
EXAMPLE
SELECT badge, Weekly pay = COALESCE(hour_worked * rate,0) FROM tab1
OUTPUT:
Displays either the product of hours_worked times rate or a zero if the columns hour_worked and rate
are null.
CLASSROOM EXERCISE
For the following CASE expression write the NULLIF function.
SELECT AVG( CASE
WHEN col1 = 100 THEN col1
END) AS Average
FROM table1
SQL SERVER 6.5
Chapter-7/38
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
GOTO label
Alter the flow of execution to a label.
SQL statement following GOTO are slipped and processing continues at the label.
Can be used anywhere within a procedure, batch or statement block
Label names must follow the rules of identifier.
Defining the label
label:
Altering the execution
GOTO label
WAITFOR statement
Specifies a time, time interval that triggers execution of a statement block, stored
procedure or transaction.
Syntax:
WAITFOR { DELAY time | TIME time }
DELAY - Instructs SQL Server to wait until specified amount of time has passed, upto a
maximum of 24 hours.
TIME - Instructs SQL Server to wait until a specified time.
time - One of the acceptable formats for datetime data. Date portion of datetime data is
not allowed.
SQL SERVER 6.5
Chapter-7/39
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CURSORS
Cursors allow individual row operations to be performed on a given result set.
They are used to provide a scrolling facility allowing the batch to retrieve the next
row, prior row, nth row, last row and so on from the result set.
When working with cursors following steps are required:
Declare the cursor to create and define it.
Open the declared cursor.
Fetch the information from the cursor and perform operations with it.
Close the cursor.
Remove the cursors definition.
Generally a cursor is called from a stored procedure or a trigger on a client computer.
The stored procedure should contain DECLARE, OPEN, FETCH, CLOSE and
DEALLOCATE statements.
DECLARE statement creates the cursor definition.
OPEN statement opens the cursor and returns the result set to the tempdb database.
(tempdb is a system database which is used for temporary working needs and
temporary tables. For details refer to session 9.)
FETCH statement moves through result set in the temdb database.
When fetch is completed, CLOSE statement removes the result from tempdb.
DEALLOCATE statement removes the cursor definition.
DECLARE statement
Creates and defines the attributes of a cursor.
Syntax:
DECLARE cursor_name [INSENSITIVE | SCROLL] CURSOR
FOR select_statement
[FOR [READ ONLY | UPDATE [ OF col_list]
cursor_name - Name of the cursor being defined.
INSENSITIVE - A cursor defined with the INSENSITIVE option operates on a
temporary copy of the underlying table, so no changes are reflected in the cursors result
set.
SQL SERVER 6.5
Chapter-7/40
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Use insensitive cursors when you do not need to see changes to the data of underlying
table as you move through your cursor result set. This cursor does not allow
modifications.
SCROLL - Specifies that all methods of fetching data are available.
select_statement - Standard SELECT statement used to identify a set of rows from a
given table or tables within the database.
The keywords COMPUTE, COMPUTE BY and INTO are not allowed within this select
statement.
READ ONLY - Prevent updates from occurring against any row within the cursor. This
option overrides the default capability of a cursor to be updated.
UPDATE [OF col_list] - Defines updatable columns within the cursor. If no list is
supplied, all columns can be updated unless the cursor has been defined as READ
ONLY.
OPEN statement
Opens the cursor and creates temporary tables of necessary.
Syntax:
OPEN cursor_name
After a cursor has been opened, use the global variable @@CURSOR_ROWS to receive
the number of qualifying rows in the last opened cursor.
The @@CURSOR_ROWS global variable returns:
-m If the cursor is being populated asynchronously. The value returned refers
to the number of rows currently in the key set.
n If the cursor is fully populated. (n) refers to the number of rows.
0 If no cursor is open.
SQL SERVER 6.5
Chapter-7/41
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
FETCH statement
Fetches or retrieves a row from the cursor.
Syntax:
FETCH [[NEXT | PRIOR | FIRST | LAST | ABSOLUTE n | RELATIVE n]
FROM ] cursor_name
[INTO @var1, @var2]
NEXT - Returns first row of the result set if this is the first fetch, otherwise it moves
cursor one row within the results set. This is the default cursor fetch.
PRIOR - Returns previous row.
FIRST- Returns the first row within the results set.
LAST - Returns the last row within the results set .
ABSOLUTE n - Returns nth row within the result set. If n is negative, returned row will
be the nth row counting backward from the last row of the result set.
RELATIVE n - Returns the nth row after the currently fetched row.
FROM cursuor_name - Defines the cursor from which the fetch should be made.
INTO @var1,@var2... - Allows data returned within a fetch to be placed into local
variables.
The global variable @@FETCH_STATUS will be updated at every execution of
FETCH.
At successful FETCH, @@FETCH_STATUS will be set to 0.
If no data was fetched, -1 will be returned.
If the row returned is no longer a member of the result set ( for example, the row was
deleted from the base table after the cursor was opened), will return 2.
SQL SERVER 6.5
Chapter-7/42
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CLOSE statement
It closes the cursor and releases any memory being used for buffering.
Syntax:
CLOSE cursor_name
DEALLOCATE statement
It removes the definition of the cursor and releases all the data structures associated
with the cursor.
Different from CLOSE statement in that a closed cursor can be reopened.
Syntax:
DEALLOCATE cursor_name
EXAMPLE
Example 1
CREATE PROC proc1
AS
SET NOCOUNT ON
SELECT *** Database: + db_name() + ***
DECLARE @tablename char(20)
DECLARE c1 INSENSITIVE CURSOR
FOR
SELECT name FROM sysobjects WHERE type = U
OPEN c1
FETCH NEXT FROM c1 INTO @tablename
WHILE (@@fetsch_status = 0)
BEGIN
EXEC (UPDATE STATISTICS + @tablename)
SELECT Statistics updated on: + @tablename
FETCH NEXT FROM c1 INTO @tablename
END
SET NOCOUNT OFF
DEALLOCATE c1
OUTPUT:
A cursor is used to build a key set of all user defined tables in the database.
It iterated through the list of tables to update the statistics.
SQL SERVER 6.5
Chapter-7/43
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Example 2
USE db1
go
SET NOCOUNT ON
go
DECLARE c2 SCROLL CURSOR
FOR
SELECT fname,lname FROM table1 WHERE state = UP
OPEN c2
/* Next select statement shows a listing of fname and lname in the
table table1 with which cursor results can be compared */
SELECT fname, lname FROM table1 WHERE state = UP
go
fname lname
----------- ------------
Alton John
Tina Turner
Bryan Adams
Celine Dion
Billy Joel
/* All fetches that follow are written in separate batches to allow the
results to follow immediately */
FETCH NEXT FROM c2
SELECT fetch_status = @@fetch_status
go
fname lname
----------- -----------
Alton John
fetch_status
--------------
0
FETCH LAST FROM c2
SELECT fetch_status = @@fetch_status
go
fname lname
----------- -----------
Billy Joel
fetch_status
--------------
0
SQL SERVER 6.5
Chapter-7/44
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
FETCH FIRST FROM c2
SELECT fetch_status = @@fetch_status
go
fname lname
----------- -----------
Alton John
fetch_status
--------------
0
FETCH NEXT FROM c2
SELECT fetch_status = @@fetch_status
go
fname lname
----------- -----------
Tina Turner
fetch_status
--------------
0
FETCH ABSOLUTE 200 FROM c2
SELECT fetch_status = @@fetch_status
go
/* Requested row is outside the cursor,no row is returned. Notice the
fetch_status */
fetch_status
--------------
-1
CLOSE c2
DEALLOCATE c2
go
SQL SERVER 6.5
Chapter-7/45
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
TRANSACTION LOG
Every database has a Transaction log associated with it.
The transaction log is a reserved storage area where SQL Server writes all the
database transactions, before writing them to the database.
The reserved storage area is the system table syslogs .

Creation of transaction log

When a database is created, a transaction log for that database is also created. Each
database has its own transaction log that is shared by all the users of the database.

Step 1 :
Data modifications are executed.( INSERT, DELETE or UPDATE statements)

Step 2:
When a modification is executed , the affected data pages are loaded from disk to data
cache.

Step 3:

As each data modification statement is made, it is recorded into the system table
called syslogs.
The change is always recorded in this log on the disk before the change is made on
the database on the disk. This type of log is called write-ahead log.
Data pages reside in cache memory and log pages are recorded on the disk on system
table called syslogs.

Step 4:

An automatic checkpoint process activates at certain intervals and cycles through
each database to determine if a checkpoint is needed.
The next checkpoint is determined based on the recovery interval configuration
option and the number of rows added to the log since the last checkpoint.
The checkpoint process writes all completed transactions to the database on the disk
from the log pages.
When a COMMIT TRANSACTION command is executed explicitly, transaction log
pages are immediately written to the disk irrespective of whether the checkpoint has
been reached or not.
SQL SERVER 6.5
Chapter-7/46
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

DIAGRAM




















Purpose of the transaction log

Transaction logs allow an application to ensure database consistency based on the
process that is going on in an application.

It is a form of checkpoint in the application that makes sure that everything is done
that is expected for a specific operation.

The information written to the transaction log is the before and after picture of the
information in the database when operations are performed on it.

EXAMPLE

When a row is updated , the before and after values of the row are stored in the transaction log



Transaction log is used to recover the database, when a roll-back or roll-forward
of the information is required, for example, in the cases of system failure.


cache memory
data page
Execution of the
modification
Data pages are read into the data cache
modifications are
recorded into the
transaction log.
syslogs
Checkpoint writes committed
transactions to the database.
database
STEP 1
database
STEP 2
STEP 3
STEP 4
SQL SERVER 6.5
Chapter-7/47
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
TRANSACTION MANAGEMENT
A transaction is a logical unit of work.
Any single SQL statement is considered to be a single unit of work whether it affects
only a single row or multiple rows within the table.
In SQL Server a transaction is implicit.
Explicit transactions can be defined by the user by including the SQL statements
enclosed within BEGIN TRANSACTION and COMMIT TRANSACTION.
In creating explicitly defined transactions, the following statement are used.
a) BEGIN TRANSACTION
b) COMMIT TRANSACTION
c) ROLLBACK TRANSACTION
d) SAVE TRANSACTION
All transactions must be enclosed within BEGIN TRANSACTION...COMMIT
TRANSACTION statements.
BEGIN TRANSACTION statement
Marks the starting point of a user-defined transaction.
Syntax:
BEGIN TRANsaction [transaction_name]
COMMIT TRANSACTION statement
Marks the end of a user-defined transaction.
Syntax:
COMMIT TRANsaction [transaction_name]
ROLLBACK TRANSACTION statement
Rolls back a user defined transaction to the last savepoint inside a transaction or to
the beginning of the transaction.
Syntax:
ROLLBACK TRANsaction [ transaction_name | savepoint_name ]
SQL SERVER 6.5
Chapter-7/48
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
transaction_name - Name assigned to the transaction. Use transaction name only on the
outermost pair of nested BEGIN...COMMIT or BEGIN...ROLLBACK statements.
savepoint_name - Name assigned to the savepoint.Use savepoint names only when a
conditional rollback should affect only the part of transaction.
ROLLBACK TRANSACTION, without transaction_name or savepoint_name will
rollback to the beginning of the transaction.
When nesting transactions, a ROLLBACK TRAN statement without a
transaction_name or savepoint_name rolls back statement to the outermost BEGIN
TRAN .
A transaction cannot be rolled back after a COMMIT TRAN statement is executed.
ROLLBACK TRAN doe not produce any message. If needed, use PRINT or
RAISERROR statement.
SAVE TRANSACTION statement
Sets a savepoint within a transaction.
Syntax:
SAVE TRANsaction savepoint_name
Savepoint can be set within a transaction.
It defines a location to which a transaction can return if part of the transaction might
be conditionally canceled.
Transaction rules
The outermost pair actually creates and commit the transaction, the inner pair tracks
the nesting level. When a nested transaction is encountered, the global variable
@@TRANCOUNT is incremented.
Naming nested transactions with a transaction_name has little effect on the outermost
transaction, because only the first transaction name is registered with the system and a
rollback to any other name (other than a valid savepoint_name) generates an error.
Do not use the following statements inside a user-defined transaction.
ALTER DATABASE statement, CREATE statements, DROP statements, DISK INIT, SELECT
INTO, TRUNCATE TABLE, UPDATE STATISTICS.
Grouping a large number of statements into one long-running transaction can
decrease the performance.
It is best if the COMMIT statement is in the same batch as the BEGIN statement.
Transaction processing guarantees database consistency and recoverability by
ensuring that either the entire transaction is completed and all changes are reflected in
the database, or the transaction is rolled back.
SQL SERVER 6.5
Chapter-7/49
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
BEGIN TRAN tran1
UPDATE member
SET last_name = MARY WHERE last_name = BARR
SAVE TRAN memupdated
/* After the updation in the member table, a save point called
memupdated has been inserted */
UPDATE member
SET last_name = JOHN WHERE last_name = M
ROLLBACK TRAN memupdated
COMMIT TRAN
/* The transaction is rolled back upto the save point i.e. the second
update is rolled back. */
CLASSROOM EXERCISE
1. Explain the difference between a batch and a script.
2. Which SQL statements can be combined in a single batch.
3. How do you define a transaction?
4. Why do you use ROLLBACK in a transaction?
SQL SERVER 6.5
Chapter-7/50
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DATABASE CONSISTENCY AND CONCURRENCY
When two or more users access the database concurrently, SQL Server uses locking
to ensure that their actions dont interfere each other.
Locking prevents one user from reading the data which is being changed by the other
users.
It also prevents users from making more than one change to a record at any one time.
Locks are held on pages that are read or modified during a transaction to prevent the
problems that might arise from the concurrent use of resources by multiple
transactions.
Locks can be minimized by committing transactions as they are completed.
Types of locks
SQL Server can hold several types of lock
Lock Type Description
Shared Used for operations that do not change or update data, such as SELECT
statement.
No data can be modified
If there is a shared lock already applied to a page by a transaction, a
second shared lock can also be applied, even though the first transaction
has not completed.
Released as soon as page(s) is no longer needed.
Exist at the page level or table level.
Update Used when SQL Server intends to modify a page i.e. when the pages are
being read for the updation.
Later promotes the update page lock to an exclusive page lock before
actually making the changes.
Created at the page level.
Exclusive Used for the data modification operations UPDATE, INSERT or
DELETE.
Only one transaction can lock the page.
No transaction can acquire an exclusive lock until all shared locks on the
required pages have been released.
Exist at the page level or table level.
SQL SERVER 6.5
Chapter-7/51
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Locking items
Different types of items can be locked by SQL Server:
Item Description
Page A 2K data page or index page. (Common)
Extent Contiguous 8 2K data pages or index pages. This lock is only used for
allocation.
Table An entire table including indexes
Intent A special type of lock to indicate the type of page locks currently placed on the
table. (An intent lock indicates that SQL Server wants to acquire a shared or
exclusive lock on a data page.)
Compatibility of locks
While a particular type of lock is held on a specified page, only compatible lock types
can be placed on the same page.
Shared Update Exclusive
Shared Yes Yes No
Update Yes No No
Exclusive No No No
System lock escalation thresholds
The SA can customize locking for all users by setting the SQL Server lock escalation
level.
When a query requests rows from a table, SQL Server automatically generates page-
level locks.
If a query requests a large percentage of rows, SQL Server escalates the locking from
page level to table level. This process is called lock escalation
It makes table scans and operations against a large results set more efficient because it
reduces locking overhead.
SQL SERVER 6.5
Chapter-7/52
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LE Threshold percent
Specifies the percentage of page locks needed on a table before a table lock is
requested.
The default (0) causes a table lock to occur only when the LE Threshold Maximum
has been reached.
EXAMPLE
If LE threshold percent is 50% that means if more than half of the data pages are locked, whole table
should be locked. This is reasonable when there is a small table with few pages.
LE Threshold Maximum
Determines the maximum number of page locks to hold before escalating to table
level lock.
If number of page locks is greater than the escalation maximum, a table lock will
occur regardless of whether or not the LE threshold percent has been exceeded.
Default is 200 page locks.
LE Threshold Minimum
Determines the minimum number of page locks to hold before escalating to table
level lock.
A table lock will occur only if this minimum is reached and the LE Threshold percent
is exceeded.
LE Threshold Minimum prevents the server from escalating to a table lock for small
tables where the LE Threshold percentage is reached quickly.
Default is 20 page locks.
SQL SERVER 6.5
Chapter-7/53
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Table locking options
In a SELECT statement, one or more locking options for a table can be specified.
Option Description
NOLOCK Directs SQL Server not to issue shared locks or honor exclusive locks.
When this option is in effect it is possible to read a non committed
transaction.
HOLDLOCK Instructs SQL Server to hold a shared lock until completion of the
transaction in which HOLDLOCK is used.
Does not determine if the shared lock is a table level or page level lock.
UPDLOCK Directs SQL Server to use update page locks instead of shared locks
while reading a table and holds the lock until the end of the command or
transaction.
Allows to read data without blocking other readers and update it later on
with the assurance that the data has not changed since you read it.
TABLOCK Directs SQL Server to use a shared table lock.
Allows others to read a table, but prevents updates on the table. The
lock is held until the end of the command. On specifying HOLDLOCK,
the lock is held until the end of the transaction.
PAGLOCK Directs SQL Server to use shared page lock. This is default.
TABLOCKX Directs SQL Server to use and exclusive table lock. This lock prevents
others from reading or updating a table.
EXAMPLE
SELECT count(*) FROM member (TABLOCK HOLDLOCK)
Insert row-level locking
By default, the locking level in SQL Server is a page, which can contain several rows.
Insert row-level locking provides performance in situations where areas of high
access occur.
When concurrent users try to insert data into the tables last page and contend for
exclusive page access, a hotspot results.
Insert row-level locking increases the speed of multi-user INSERT operations.
Row-level locking is off by default.
It can be enabled on individual tables or on an entire database by using
sp_tableoption stored procedure.
SQL SERVER 6.5
Chapter-7/54
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
EXECUTE sp_tableoption table1, insert row lock , true
OUTPUT:
Insert row lock option is turned on for the table table1.
SQL SERVER 6.5
Chapter-7/55
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LAB EXERCISES
1. Declare a variable called var1, assign the string Hello World to the variable
and display the contents of the variable.
2. Store the phone number of the author whose first name is Ann from the table
authors of the pubs database, to a variable and display it.
3. Display the version number of the current SQL Server along with the
servername in the following format:
The version is version_number and the server name is
server_name.
4. Calculate the average price of all the books from the titles table and display it
using the PRINT statement in the following format.
The average price for the books is price.
5. Raise an error with severity level of 11 and state 1 with the following message:
This is an error message.
6. Try the examples of RAISERROR given in the book.
7. Use the pubs database for the following:
If the average price of books is less than $30, only then following should be
performed:
a) the price of the books should be doubled.
b) select the maximum price and if maximum price less than 50, double the rice
again for all the books. Continue this until the price is greater than 50.
8. Create a cursor to drop all the views in a database.
9. Try out the relevant examples in the book.
SQL SERVER 6.5
Chapter-7/56
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
A batch is a set of SQL statements submitted together and executed as a group
A group of batches form a script.
Flow-Control language - Controls the flow of execution of SQL statements within a set of
statements such as statement blocks and stored procedures
Cursors - Allow individual row operations to be performed on a given result set.
Transaction log is a reserved storage area where all the changes to the database are
stored.
Transaction - A logical unit of work.
BEGIN TRAN marks the start of the transaction.
COMMIT TRAN marks the end of a transaction.
ROLLBACK TRAN cancels transaction.
SAVE TRAN rolls back to a transaction point.
Types of locks
Shared, Update, Exclusive
Locking items
Page, Extent, Table, Intent
SQL SERVER 6.5
Chapter-8/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Implementation of Triggers and Stored procedures
SCOPE
Triggers
Creation of triggers
Enforcing data integrity through triggers
Stored procedures
Creating and executing stored procedures
Remote and system stored procedures
How stored procedures are processed
SQL SERVER 6.5
Chapter-8/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
TRIGGERS
About triggers
A trigger is a special kind of stored procedure that is invoked whenever an attempt is
made to modify the data in the table it protects.
Modifications to a table are made using INSERT, UPDATE, or DELETE statements.
Triggers are used to enforce business rules and data integrity such as automatically
updating summary data.
Triggers allow to perform cascading delete or update actions, if a referential integrity
violation occurs.
If constraints exist on the trigger table, they are checked prior to the trigger execution.
If constraints are violated, the statement does not execute, hence trigger will not run.
Characteristics of trigger
Are associated with tables.
Are automatic; they work irrespective of the cause of the data modification.
Are automatically invoked by SQL Server.
Cannot be called directly and do not have parameters.
Can nest up to 16 levels.
This allows a trigger that changes a table on which there is another trigger to invoke
the second trigger, which can fire a third trigger and so on.
Are conceptually advanced form of rules, used to enforce more elaborate restrictions
on data. They prevent incorrect, unauthorized, or inconsistent changes to the data.
Creation of triggers
Triggers are created with the CREATE TRIGGER statement.
Statement specifies
(a) the table on which a trigger is defined.
(b) the events for which trigger will invoke.
To prevent a trigger from firing , DROP TRIGGER statement is used.
SQL SERVER 6.5
Chapter-8/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Syntax:
CREATE TRIGGER [ owner.] trigger_name
ON [owner.] table_name
FOR [ INSERT | UPDATE| DELETE ]
AS
IF UPDATE (column_name)...
[ { AND | OR } UPDATE (column_name)...]
sql_statements }
Trigger rules and guidelines
A table can only have three trigger actions per table: one UPADTE, one INSERT and
one DELETE trigger.
Each trigger applies to only one table only. A single trigger can process all three
actions (UPDATE, DELETE, INSERT) .
Only table owners can create and drop triggers for the table. This permission cannot
be transferred.
A trigger cannot be created on a view or a temporary table, although triggers can
reference them.
A trigger should not include SELECT statements that return results to the user,
because the returned results would have to be written into every application in which
modifications to the trigger table are allowed.
Triggers can be used to help ensure the relational integrity of the database.
Triggers should be used only for the data integrity enforcement and business rules
processing.
If a trigger is defined for an operation (INSERT, UPDATE or DELETE) that already
has a trigger association, the existing trigger is replaced with the new trigger.
On dropping a table all triggers associated to the triggers are automatically dropped.


The system stored procedure sp_depends can be used to find out which tables have
trigger on them.




SQL SERVER 6.5
Chapter-8/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Following SQL statements are not allowed in a trigger:

All CREATE statements.
All DROP statements.
ALTER TABLE and ALTER DATABASE.
TRUNCATE TABLE.
GRANT and REVOKE.
UPDATE STATISTICS.
RECONFIGURE.
LOAD DATABASE and LOAD TRANSACTION.
All DISK statements.
SELECT INTO (because it creates table).


INSERT trigger

When an INSERT trigger statement is executed, new rows are added to the trigger table
and to the inserted table at the same time.

The inserted table is a logical table that holds a copy of the rows that have been inserted.

DIAGRAM

inserted

FRANCIS MARY POND VILLA


APPLICANT
LAST_NAME FIRST_NAME ADDRESS
BARR PETER CHURCH ROAD
ALLEN SAM PARK STREET
FRANCIS MARY POND VILLA



The inserted table can be examined by the trigger, to determine whether or how the
trigger actions should be carried out.

The inserted table allows to compare the INSERTED rows in the table to the rows in the
inserted table.

The rows in the inserted table are always duplicates of one or more rows in the trigger
table.

With the inserted table, inserted data can be referenced without having to store the
SQL SERVER 6.5
Chapter-8/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
information in the variables.

DELETE trigger

When a DELETE trigger statement is executed, rows are deleted from the table, and are
places in a special table called deleted table.


DIAGRAM




APPLICANT
LAST_NAME FIRST_NAME ADDRESS
BARR PETER CHURCH ROAD
ALLEN SAM PARK STREET
FRANCIS MARY POND VILLA

deleted

FRANCIS MARY POND VILLA




When using the DELETE trigger statement consider the following:

The deleted table and the database tables will not have any rows in common.
When a row is appended to the deleted table, it no longer exists in the database table.
Space is allocated the deleted table from the databases allocated space. The deleted
table is always in cache.
The DELETE trigger does not execute for the TRUNCATE TABLE statement.
Deleted and inserted tables are conceptual tables. They are structurally like the table
on which the trigger is defined. They hold the rows of information modified by the
user.

SQL SERVER 6.5
Chapter-8/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

UPDATE trigger

When an UPDATE statement is executed on a table that has an UPDATE trigger, the
original rows are moved into the deleted table, while the update row is inserted into the
inserted table and the table being updated

DIAGRAM


TABLE






inserted





deleted









When using the UPDATE trigger statement, consider the following:

After all rows are updated, deleted and inserted tables are loaded, and then the
UPDATE trigger executes.
The deleted and inserted tables, as well as the updated table can be examined by the
trigger to determine whether multiple rows have been updated or how the trigger
actions should be carried out.
UPDATE on a column
UPDATE trigger can be defined
(a) to protect data in a specific column.
(b) to test modifications of a specified column.
Original record that is being updated
goes to the deleted table.
Updated row is
inserted into the
inserted table and the
table is updated
SQL SERVER 6.5
Chapter-8/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Syntax:
IF UPDATE < column_name>
EXAMPLE
CREATE TRIGGER trigger1
ON member
FOR UPDATE
AS
IF UPDATE (last_name)
BEGIN
RAISERROR (Transaction cannot be processed)
ROLLBACK TRANSACTION
END
OUTPUT:
Prevents the user from modifying the last_name field of the table member.
Enforcing data integrity through triggers
Triggers are used to enforce:
(a) Data integrity
(b) Referential integrity
Can take actions or cascade actions.
Can define custom error message.
(c) Business rules
Enforce restrictions that are more complex than those defined with CHECK
constraints.
Enforcing data integrity
Triggers can be used to enforce data integrity by cascading changes to affected tables
throughout the database.
The following example shows, how a trigger cascades to change affected tables
throughout the database.
SQL SERVER 6.5
Chapter-8/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
CREATE TRIGGER del_trig
ON fine
FOR DELETE
AS
UPDATE member
SET fine_amt = 0
FROM member, deleted
WHERE member.mem_no = deleted.mem_no
OUTPUT:
Enforces data integrity by changing the status of fine_amt to 0 in the member table when a fine record
for that member is deleted from the fine table.
Note: The record is fetched in the member table for updation on the basis of the record in the deleted
table.
Enforcing referential integrity
Database accuracy

Assures vital data in database remains accurate and useable as database changes

Maintains Primary and Foreign keys
Keeps the values of foreign keys in line with those in primary keys.
Allows actions to be taken when a key is inserted, updated or deleted.
Triggers can be used to enforce referential integrity.
Referential integrity can be defined by using FOREIGN KEY and REFERENCE
constraints with the CREATE TABLE statement.
Triggers are useful to ensure appropriate actions when cascading deletions or updates
need to occur.
EXAMPLE
CREATE TRIGGER adult_insert
ON adult
FOR INSERT
AS
IF (SELECT COUNT(*)
FROM member, inserted
WHERE member.mem_num=inserted.mem_num)=0
BEGIN
PRINT Transaction cannot be processed
PRINT No entry for member for this adult.
ROLLBACK TRANSACTION
END
SQL SERVER 6.5
Chapter-8/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OUTPUT:
When a user inserts a record in the table adult, the trigger adult_insert is fired.
The mem_num inserted in the adult table should be present in the member table.
The existence of the mem_num inserted into the adult table is checked against the member table
using the inserted table.
The trigger works when a single row is inserted. If multiple rows are inserted as with
(SELECT statement), the trigger will not work correctly.
Multi-row trigger
A multi-row insert can occur from an INSERT with a SELECT statement. Multirow
considerations can also apply to multi-row updates and multi-row deletes.
EXAMPLE
CREATE TRIGGER adult_insert
ON adult
FOR INSERT
AS
DECLARE @rcnt int
SELECT @rcnt = @@rowcount
IF (SELECT COUNT(*)
FROM member, inserted
WHERE member.mem_num=inserted.mem_num)=0
BEGIN
PRINT Transaction cannot be processed
PRINT No entry for member for this adult.
ROLLBACK TRANSACTION
END
IF (SELECT COUNT(*)
FROM member, inserted
WHERE member.mem_num=inserted.mem_num)<> @rcnt
BEGIN
PRINT Not all adults have an entry in the Member table
PRINT Multi-row insert transaction has been rolled backed..
ROLLBACK TRANSACTION
END
SQL SERVER 6.5
Chapter-8/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Business rules
The following example involves a member who is discontinuing membership. A
member with outstanding loans can be prevented from being deleted from the database.
If there are no outstanding loans, member can be deleted.
EXAMPLE
CREATE TRIGGER mem_withdraw
ON member FOR DELETE
AS
IF (SELECT books_on_issue FROM member, deleted
WHERE member.mem_no = deleted.mem_no) > 0
BEGIN
PRINT Transaction not processed
PRINT Member has books with him
ROLLBACK TRANSACTION
END
ELSE
PRINT Member deleted
Nested and non-nested triggers
Any trigger can contain an UPDATE, INSERT or DELETE statement that affects another
table.
With nesting enabled, a trigger that changes a table can activate a second trigger, which
can in turn activate a third trigger and so on.
Nesting is enabled at installation, but can be disabled or enabled using the sp_configure
system stored procedure.
Triggers can be nested up to 16 levels.
If any trigger in a nested chain sets off an infinite loop, the nesting level is exceeded and
the trigger terminates.
Nested trigger can be used to perform functions such as storing a backup copy of rows
affected by a previous trigger.
SQL SERVER 6.5
Chapter-8/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CLASSROOM EXERCISES
1. What are the ways in which you can display the information about triggers?
2. Will the trigger work if you change the name of the object referenced by a trigger?
If no, what should be done to make the trigger work?
3. What is nesting of triggers?
SQL SERVER 6.5
Chapter-8/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
STORED PROCEDURES
Stored procedures enhance the power, efficiency and flexibility of SQL Server and
improves the performance of SQL statements and batches.
About Stored Procedures
Stored procedures are a way to create routines and procedures that are run on the
server, by the server processes.

These are pre-complied SQL statements and control-of-flow language stored on the
server that execute very quickly.

These routines can be started by an application calling them, or called by data
integrity rules or triggers.
Using Stored Procedures
Stored Procedure can:
Return values ( the values which are part of the table and also the values that are not
the part of the table but are calculated during the running of stored procedures ) or
modify values
Compare a user-supplied value against the pre-requisites for information in the
system.
Take parameters
Call other procedures
Return a status value to a calling procedure or batch to indicate success or failure
Permissions for creating a stored procedure
A stored procedure can only be created in the current database.
Permission to execute the procedure that is created is set by default to the owner of
the database, who can transfer it to the other users.
SQL SERVER 6.5
Chapter-8/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Creating stored procedures
Stored procedures are created using the CREATE PROCEDURE statement.
Syntax:
CREATE PROCedure [owner.] procedure_name[ ;number]
[@parameter_name datatype [ = default] [ OUTPUT]
...
[FOR REPLICATION] | [WITH RECOMPILE], ENCRYPTION
AS sql_statements
EXAMPLE
CREATE PROCEDURE all_members
AS SELECT * FROM members
OUTPUT:
A procedure called all_members has been created that contains a SELECT statement to display all
rows of the table member
.
Execution
After a procedure is created, its name is entered on a line to execute the procedure.
If the name of the stored procedure is preceded with other statements, the keyword
EXEC needs to precede the name of the stored procedure.
EXAMPLE
The procedure all_members created in the previous example can be executed as follows:
all_members /* Executes procedure when not preceded
by any other statements */
SQL SERVER 6.5
Chapter-8/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OUTPUT:
All records of the member table will be displayed.
OR
SELECT * FROM applicant /* When preceded by other statement
EXEC insert_procedure such as SELECT. */
OUTPUT:
All records of the applicant table will be displayed first.
Then, all records from the member table will be displayed.
;number option
The semicolon and an integer after the name of the stored procedure enables to create
multiple versions of a procedure with the same name.
When the procedure is executed, the version number determines the version of the
procedure to be executed.

If no version is specified, the first version is executed.

A single DROP PROCEDURE statement will drop all the versions of the stored
procedure.

After procedures have been grouped, individual procedures within the group can not
be dropped.
EXAMPLE
CREATE PROCEDURE pr;1 /* Creates version 1 of the
AS procedure pr */
PRINT Version 1
CREATE PROCEDURE pr;2 /* Creates version 2 of the
AS procedure pr. */
PRINT Version 2
OUTPUT:
When the procedure pr;1 is executed, it prints Version1.
When procedure pr;2 is executed, it prints Version 2.
When procedure the group name is specified to execute the procedure ,the first version gets executed
and Version 1 is printed.
SQL SERVER 6.5
Chapter-8/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Execution of procedure Output
pr;1 Version 1
pr;2 Version 2
Pr Version 1
Using parameters with procedures
If a procedure is executed that calls another procedure, the called procedure can
access objects created by the calling procedure.
Parameters can be used to pass the information into a procedure from the command-
line.
This is done by defining the parameters with the CREATE PROCEDURE statement
using the following options.
@parameter_name
It specifies a parameter in the procedure.
One or more parameters can be declared in the CREATE PROCEDURE statement.
When the procedure is executed the user must supply the value of each declared
parameter.
Parameter name is always preceded by the symbol @.
datatype
It specifies the datatype of the parameter.
All system-supplied and user-defined datatypes are supported except the image
datatype.
default
It specifies the default value of the parameter.
If a default is default is defined a user can execute the procedure without specifying ,
a value for that parameter.
SQL SERVER 6.5
Chapter-8/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
CREATE PROCEDURE insert_proc /* A procedure insert_
(@p1 char (10), @p2 char (20) , @p3 int) proc is created
AS which defines 3
INSERT INTO table1 parameters */
VALUES (@p1, @p2, @p3)
insert_proc Harry, Gill, 222 /* Using INSERT
statement three
values are supplied
from the command
line to the
procedure which
inserts the values
into the table
table1 */
SELECT * FROM table1 WHERE code = 22 /* Lists the record just
inserted into the
table through the
procedure */
OUTPUT option
EXAMPLE
Creation of a stored procedure
CREATE PROCEDURE p1
@a1 smallint,
@a2 smallint,
@result smallint OUTPUT
AS
SELECT @result = @a1 * @a2
GO
Executing store procedure
DECLARE @var smallint
SELECT @var = 40
EXEC p1 3, 4, @var OUTPUT
SELECT The result is :, @var
GO
OUTPUT:
The result is: 12
SQL SERVER 6.5
Chapter-8/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
In the above example, a stored procedure is created which calculates the product of
two numbers.
Then a batch calls this procedure to obtain the product of the number 3 and 4.
The batch first loads a value in the @var just to verify that it will be replaced but the
correct result during the call to p1.
If the keyword OUTPUT were omitted from the procedure call, the call would still
execute but the value of @var would be unchanged by the execution of the procedure.
If the OUTPUT keyword were omitted from the procedure definition but left in the
procedure call then an error condition would exist because the batch would be asking
the stored procedure for output that the stored procedure was not written to produce.
RECOMPILE option
Should be used when you are executing stored procedures with atypical parameters
for example, where the plan stored for the procedure might not be optimal for that
parameter.
EXAMPLE
Example 1
CREATE PROC testproc @title_no title_no WITH RECOMPILE
AS SELECT * FROM loan
WHERE title_no= @title_no
OUTPUT:
Recompiles and optimizes every execution of the stored procedure and creates a new query plan.
Example 2
EXEC sp_help WITH RECOMPILE
OUTPUT:
Creates new query plan during the execution of the stored procedure. The new execution plan is stored
in the cache.
Example 3
sp_recompile title
The option causes any stored procedures and triggers that use the named table to be recompiled the
next time it runs.
SQL SERVER 6.5
Chapter-8/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
ENCRYPTION option
Encrypts the syscomments table entry that contains the text of the CREATE
PROCEDURE statement.
Stored procedure rules and guidelines
The name of the stored procedure should follow the rules of naming an identifier.
An object can not be referenced in the stored procedure definition if it does not exists.
Except CREATE statements, any number and any type of SQL statements can be
included in stored procedures.
The CREATE PROCEDURE statement can not be combined with other SQL
statements in a single batch.
The maximum number of parameters in a stored procedure is 255.
Temporary tables can be referenced within a procedure.
If a procedure is executed that calls another procedure, called procedure can access all
objects except temporary tables created by the first procedure.
If a private temporary table is created inside a procedure, the temporary table exists
only for the purposes of the procedure; it disappears when you exit the procedure.
Private and public temporary stored procedures analogous to temporary tables can be
created.
# prefix to the procedure name denotes a private temporary stored procedure.
## prefix to the procedure name denotes a public temporary stored procedure.
Information on stored procedure
To list the definition of the procedure, the system stored procedure sp_helptext is
executed.
Procedures created with the ENCRYPTION option can not be viewed with
sp_helptext.
For a report on the objects referenced by the stored procedure, use the sp_depends
system stored procedure.
sp_help system stored procedure can be used to list information about the procedure
Auto execution stored procedure
It is possible to have one or more stored procedures execute automatically when SQL
Server starts.
Execution of the stored procedure starts when the last database has been recovered at
startup.
Infinite number of start up procedures can be present.
Each startup procedure consumes one connection when executing.
SQL SERVER 6.5
Chapter-8/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
If multiple procedures need to be executed at startup and you dont need to execute
them in parallel only one procedure can be made as the startup procedure and that
procedure can call other procedures.
This will use only one connection.
System stored procedure Description
sp_makestartup Makes an existing stored procedure a startup procedure.
sp_unmakestartup Stops a procedure from executing at startup
sp_helpstartup Provides a list of all procedures that will execute at startup.
EXAMPLE
CREATE PROCEDURE testproc /* Creates a procedure called
INSERT t1 DEFAULT VALUES testproc, which inserts default
values into the table t1 */
sp_makestartup testproc /* Makes the procedure testproc as
startup procedure. */
sp_helpstartup /* Lists all the startup procedures
defined. */
Executing a Stored Procedure on a remote server
Stored procedures residing on a remote server are called remote stored procedures.
Remote stored procedures can be executed from the local server.
To use remote stored procedures, you must have remote servers established.
A remote server on a SQL Server network is a server that a user can access through
the local server.
When servers are configured to allow remote stored procedures, this information is
stored in sysservers and sysremotelogins system tables in the master database.
A client connected to one SQL server, when executes the remote stored procedure on
another SQL Server, client connection to that SQL server is not established.
The server to which the client is connected accepts the clients request and send it to
the remote server on clients behalf.
Remote server processes the request and sends the results to the original server.
The original server, then, in turn passes the results to the client.
Remote stored procedures request can also be initiated by the server.
SQL SERVER 6.5
Chapter-8/20
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Syntax:
EXECUTE servername.dbname.owner.stored_procedure_name
Client includes the EXECUTE statement as part of a normal batch submitted to the
local server.
EXAMPLE
EXEC sp_addlogin user1
EXEC server2.master.sa.sp_addlogin user1
OUTPUT:
The login name user1 is added to both the servers i.e to the local server as well as the remote server
server2.
Conditions for implementing remote store procedures
A server must allow remote access from other servers. By default, access is allowed.
To turn off this feature, use sp_configure to turn off the Remote Access
configuration option.
Each server must store both its own name as the local server (stored by default) and
the name of the other server in the sysservers table.
The login ID that the local server uses when opening the connection must exist on the
remote server.
SQL SERVER 6.5
Chapter-8/21
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Processing of Stored Procedures
DIAGRAM
Parsing
Stored Procedure
Resolve names
Normalize
Resolve views
Resolve
aggregates
Protection Map
Name stored in sysobjects table
Text stored in syscomments table
Decision Compile
Query tree stored in sysprocedures
table
Execute
Execution plan held temporarily in
procedure cache
SQL SERVER 6.5
Chapter-8/22
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Creation
When a stored procedure is created, it is analysed by the query processor.
It prepares an internal normalized structure for the procedure called as query tree. The
stored procedure is placed in the following system tables:
Stored procedures Name sysobjects
Text syscomments
Query tree sysprocedures

Execution

When a stored procedure is executed for the first time, the procedure is brought into
the memory and compiled
The fully compiled form called as execution or procedure plan is then stored in the
procedure cache - SQL Servers temporary memory buffer.
The execution plan is not stored permanently in a system table.
The execution plan remains in the procedure cache unless other memory needs force
it out so that the next request for execution can be processed without any compilation
overhead.
CLASSROOM EXERCISES
1. Can a trigger contain a stored procedure?
2. How can the text of a stored procedure and a trigger be viewed?
SQL SERVER 6.5
Chapter-8/23
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LAB EXERCISES
1. Create a trigger called warn which prints a message to the user when he tries to add or
change the data in the table titles of pubs database.
2. Create a trigger that updates the ytd_sales column in the titles table every time a new
row is added to the sales table. Update the ytd_sales column in the titles table such that
ytd_sales is equal to its previous value plus the value added to the qty field of sales
table.
3. Create a trigger that updates ytd_sales column in the titles table every time one or more
sales rows are deleted.It updates the ytd_sales column in the titles table so that
ytd_sales is equal to its previous value minus the value subtracted from sales.qty.
4. Display the information about all the available triggers in the database.
5. Drop the triggers.
6. Create a stored procedure which shows the list of tables available in the database.
7. Create a stored procedure such that if authors first name and last name are given, it
displays the title and publisher of each of that authors books. (Use pubs database)
8. Create a procedure which displays the name of all authors who have written a book
published by the publisher given as a parameter. If no publisher name is supplied, the
procedure should show the authors published by Algodata Infosystems.
9. Create a procedure that performs division of two integer variables . The third variable
should be defined as an output parameter. If the divisor is 0, value 100 should be
returned, otherwise 0 should be returned. Check by displaying the return value as well
as the third variable defined as output parameter.
SQL SERVER 6.5
Chapter-8/24
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
Trigger is a special kind of stored procedure that is invoked whenever an attempt is made
to modify the data in the table it protects.
Triggers are created using CREATE TRIGGER statement.
A table can have only three trigger actions UPDATE, INSERT and DELETE.
When INSERT trigger is executed, new rows are added to the trigger table as well as a
logical table called inserted.
When a DELETE trigger statement is executed, rows are deleted from the table and are
placed in table deleted.
When an UPDATE trigger statement is executed, original rows are moved to deleted
table and update row is inserted into the inserted table and the table being updated.
Stored procedures are pre-compiled SQL statements stored on the server.
Stored procedures are created using CREATE PROC statement.
Auto execution stored procedure are created using the system stored procedure
sp_makestartup.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/1
OBJECTIVE
Managing devices and databases
SCOPE
System devices and System databases
System tables
Database Components
System Stored Procedures
Storage Allocation
Managing database devices
Creating
Dropping
Expanding
Managing database
Creating
Altering size
Dropping
Database Configuration Options
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/2
SYSTEM DEVICES AND SYSTEM DATABASES
Device
Device is an Operating System file in which databases are stored. These are physical files
that SQL Server creates on disk.
DIAGRAM
DEVICE, DATABASES AND TABLES
Devices must be created before databases can be created.

One device can store more than one database.

However, better performance is achieved with a single database per device because
each device is managed by a single I/O thread from the Operating System.

By allocating only a single database per device, the system can service each database
with a different I/O thread, instead of sharing these threads between databases.






DEVICE
DATABASE
TABLES
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/3

DIAGRAM





















One database can be stored on several devices. This can be an optimizing method
which gives two advantages:

(a) Different devices can be placed on different physical drives so that different
disk drives are allowed to service the device, effectively giving more than one
set of read/write heads working on database request.
(b) Each device being managed by different I/O thread, system can allocate more
than one I/O thread to support the database.

DIAGRAM













DEVICE
Sharing of thread by the two databases being on the same device
Thread1
DB1 DB2
Each database is receiving one thread being on different devices
OS
Thread2 Thread1
DEVICE1 DEVICE2
DB1
Database extending on two devices and managed by two
individual threads
DB1 DB2
OS
DEVICE1 DEVICE2
OS
Thread1 Thread2
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/4

There are two types of devices:

Database Devices
Dump Devices


Database Device Dump Device

1. Stores databases and transaction logs Stores backups of databases and
transaction logs.
2. Stored on disk files Can be stored on disk files, diskettes or
tapes


System devices

When SQL Server is installed, following system devices are automatically created:

(a) Three Database devices:
MASTER
MSDBDATA
MSDBLOG

(b) Three Dump devices:
DISKDUMP
DISKETTEDUMPA
DISKETTEDUMPB


Databases

There are two types of databases:

(a) User databases
(b) System databases


User databases

Databases created by the users are called User databases.
A sample database, called pubs database, comes with the SQL Server product, which
is also an example of a user database.
It is installed automatically during the installation.

SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/5


System databases

When SQL Server is installed, the setup program installs four system databases. SQL
Server uses system databases to operate and manage the system. These are :

(a) master
(b) model
(c) tempdb
(d) msdb


SYSTEM DEVICES AND DATABASES STORED ON THESE DEVICES

System devices Databases

1 MASTER master, model, tempdb, pubs
2 MSDBDATA msdb
3 MSDBLOG msdb transaction log
4 DISKDUMP, DISKETTEDUMPA,
DISKETTEDUMPB
Backups of databases


Note : Devices created by the system should be avoided to be used for other databases.


System databases

master database

When SQL Server is installed after the creation of MASTER device, master database
gets created and is placed on MASTER device.
It controls all the databases created by the users.
It keeps track of all activities and operations of the Server like :
(a) User accounts
(b) Ongoing processes
(c) System error messages
(d) Databases and storage area allocated to each database
(e) Active locks
(f) System stored procedures used primarily for system administration
(g) Tapes and disks available on the system
Creating or altering any database object in this database should be discouraged since
it should be used for the administration of the system as a whole .
Thus, it is important to have an up-to-date backup of the master database.
The default size is 25 MB.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/6

DIAGRAM













dev1

dev2



master database


model database

When SQL Server is installed, model database is also one of the databases that is
created and placed on MASTER device, after the creation of the MASTER device.
It acts as a template or prototype for all new user databases.
Each time a user creates a new database, server makes a copy of the model database
first, and then expands it to the specified size.
The new databases created will be thus, based on model database.
It contains the system tables required for each user database.
A new database can never be smaller than model database.
Customization of the model database can be done. Then, all new databases that users
create will contain those changes.

Some commonly made changes are:
(a) User-defined datatypes, rules, defaults, stored procedures are added.
(b) Default privileges for accounts ( guest account in particular) are established in
model database.
(c) Users to be given access to all databases on a SQL Server are added.
(d) Database configuration options are set in the model database.
The default size is 1 MB.
master database having system tables
userdb1
database
userdb2
database
sysdatabases sysdevicves
userdb1 dev1
userdb2 dev2

syslogins sysmessages sysconfigures
--------- --------- ---------
-------- --------- --------
sysobjects sysindexes syslocks
----- -------- -------
C:\
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/7


DIAGRAM


model database











model database


tempdb database

When SQL Server is installed, after the MASTER device is created, tempdb database
is one of the databases that is created and is placed on MASTER device.
It is a storage area for all temporary tables and other temporary working needs.

EXAMPLE

Intermediate results of GROUP BY, ORDER BY, DISTINCT and cursors etc. are stored
in tempdb database.


All temporary tables are stored in tempdb regardless of the database being currently
used.
Temporary tables are not stored indefinitely.
They are automatically dropped from the database when the user closes connection to
the SQL Server.









Userdatabase 1
Userdatabase2
System tables
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/8



DIAGRAM












tempdb database


No special permissions are required to use tempdb.
It can be placed in RAM by setting the SQL Server configuration option tempdb in
RAM (MB).
Placing tempdb in RAM dramatically decreases the amount of time required for
processing.
The default size is 2 MB.


msdb database

During server software installation two devices ( MSDBDATA and MSDBLOG) of 2
MB and 1 MB respectively are created on the same drive as the master database.
msdb database is placed on MSDBDATA and its transaction log on MSDBLOG.
It supports the SQL Executive Services.
SQL Executive Service is a scheduler that enables activities like :
(a) scheduling of tasks which help in automating server activities (backing up data)
(b) replication of data
SQL Executive Service stores all scheduled and replication tasks in the msdb
database.
Contains system-defined tables, which are specific to this database.

SELECT * FROM member
ORDER BY mem_no
Temporary table
tempdb
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/9


Table name Function

sysalerts Stores information about all user-defined alerts
sysbackupdetail Specifies a summary of the devices used to backup
sysbackuphistory Specifies a summary of each backup operation
syshistory Stores historical information about success/failure of tasks , date
and time of execution
sysnotifications Keeps tracks of which operators are associated with what alerts
and notification method used to notify those operators ( for e.g.
e-mail, pager etc.)
sysoperators Stores information about all the operators such as work
schedules, e-mail names, pager numbers etc.
sysrestoredetail Specifies a summary of devices used to restore
sysrestorehistory Specifies a summary of each restore information
sysservermessages Contains all messages about server-related. information
systasks Stores information about all user defined tasks



DIAGRAM












msdb database











sysalerts

sysbackupdetail

sysbackuphistory

syshistory

sysnotifications
sysoperators

sysrestoredetails

sysrestorehistory

sysservermessages

systasks
msdb
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/10


SYSTEM TABLES

All the SQL Server-supplied tables are considered as System Tables.
System tables are used to store information about the system and individual
databases.

System tables have been categorised by the types of related information as follows:

Database catalog
System catalog
Replication tables
SQL Executive

Database catalog

Master database has 31 system tables out of which, 18 system tables are found in
every database, collectively known as Database Catalog.
These tables store information about individual databases.
DATABASE CATALOG
System tables Function
sysalternates Has one row for each SQL Server user mapped to a database user.
syscolumns Has one row for each column in table or view and for each
parameter in a stored procedure
syscomments Has one or more rows for each view, rule, default , trigger and
stored procedure with a SQL definition statement
sysdepends Has one row for each procedure, view , table that is referenced by
a procedure, view or trigger
sysindexes Has one row each for clustered index, non clustered index, table
with no indexes and table that contains image or text datatype.
syskeys Has one row each for foreign, primary or common key
syslogs Contains the transaction log used for recovery and roll forward.
sysobjects Has one row for each object (table, view, stored procedure, rule ,
trigger, log and temporary object created within a database.)
sysprocedures Has one row for each view, rule, default, trigger and stored
procedure
sysprotects Contains user permissions information
syssegments Has one row for each segment.
systypes Has one row for each default system-supplied and user-defined
datatype
sysusers Has one row for each user allowed in the database
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/11
DATABASE CATALOG (contd.)
System tables Functions
sysreferences Has one row for each reference constraint created
sysconstraints Contains information on all constraints created
sysarticles Contains article information for each article created for replication
syspublications Contains one row for each publication created by publication
server.
syssubscriptions Contains one row for each subscription from a subscribing server
System Catalog
13 system tables are stored only in master database, collectively known as System
Catalog.
These table store information about the system.

SYSTEM CATALOG

System tables Functions

syscharsets Contains one row for each character set or sort order defined for
use by SQL Server.
sysconfigures Contains one row for each configurable environmental variable
syscurconfigs Contains one row for each of the configuration option as in
sysconfigures, but contains the current values and entries that
describe the configuration structure.
sysdatabases Contains one row for each database on SQL Server
sysdevices Contains one row for each available database and disk device
syslanguages Contains one row for each language known to the server
syslocks Contains information about active locks
syslogins Contains one row for each valid user account
sysmessages Contains one row for each system error
sysprocesses Contains information about ongoing processes
sysremotelogins Contains one row for each remote user account who is allowed to
call remote stored procedures o this SQL Server.
sysservers Contains one row for each remote server
sysusage Contains one row for each disk allocation piece assigned to a
database

SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/12


DIAGRAM


















User databases



Replication tables

These are the system tables that store the replication related information.
These system tables are found in the databases which are involved in the replication.

SQL Executive system tables

These tables contain the scheduling information.
These tables are present in the msdb database ( Covered earlier )


Permissions for System Tables

A permission is security authorization that allows a user to perform certain actions on
certain database objects.
Permissions for using system tables are controlled by the database owner.

Querying the System Tables

System tables can be queried as any other tables.

master
model
system tables
tmpdb
system tables
msdb
system tables
System databases
user db
system tables
user db
system tables
Database catalog
(Server wide system
tables)
System catalog
(Specific system
tables)
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/13


EXAMPLE

SELECT name FROM sysobjects WHERE type = U

OUTPUT:
Displays all the names of user tables present in the current database.
name field of the table sysobjects stores the name of the object.
type indicates the type of the object, for example U indicates that the objects are user tables.

name
--------------------
master
detail

( 2 row(s) affected )





CLASSROOM EXERCISE

1. What is the difference between the system defined table of the msdb
database, sysservermessages, and system defined table of the master
database, sysmessages.

2. What is the purpose of the master and the msdb database.

3. What can be the implications of using tempdb in Ram configuration option.


SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/14

DATABASE COMPONENTS

Database Components System tables

Objects ( table, view, default, rule, stored procedure, triggers) sysobjects
Indexes sysindexes
Datatypes systypes
Constraints Sysconstraints
Sysreferences

Objects
Objects of the database such as tables, views and stored procedures can be determined
by querying the sysobjects table of the database.

Objects Description

Table Collection of rows and tables
View An alternate way to look at data in one or more tables
Default Value that SQL Server inserts into a column if the user doesnt
enter a value.
Rule Specifies and controls what data can be entered into a table
Stored procedure Pre-compiled collection of SQL statements
Trigger Special form of stored procedure that executes automatically
when a user modifies a table

Indexes
An index is a table structure that SQL Server uses to provide fast access to rows of a
table based on values of one or more columns.
Indexes in the database can be determined by querying the sysindexes table of the
database.

Datatypes
A datatype specifies what type of information a column holds (char, int or any other
datatype) and how the data is stored in these columns.
Datatypes in the database can be determined by querying the systypes table of the
database.

Constraints
A component used to help maintain the data integrity.
Places restriction on a column or table, controlling the value that is to be entered.
All created constraints can be viewed by querying the sysconstraints and
sysreferences table of the database .
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/15


SYSTEM STORED PROCEDURE

A System stored procedure is a precompiled collection of SQL statements.

System stored procedures are an easy way to query the system tables for
administration and management activities of SQL server.

They can be used for displaying information on databases and users.

System stored procedures are created in the master database during installation.

The name of a system stored procedure begins with sp__.

User written pre-compiled collection of Transact-SQL statements are called stored
procedures, that can be executed from any database.

Permissions for using System Stored Procedure

System stored procedures are owned by the System Administrator.
Some system stored procedures can be run only by the database owner.
Other system stored procedures can be executed by any user who has been granted
EXECUTE permission on them.
Being located in the master database, the EXECUTE permission must be granted in
the master database.
A user can have permission to execute a system stored procedure either in all or in
none of the databases.
The owner of a user database cannot directly control permissions on the system
stored procedures within his or her own database.


EXAMPLES

sp_help system stored procedure

Syntax:

sp_help [objname]

sp_help reports information about a database object (listed in sysobjects) or SQL Server supplied or user
defined datatypes (listed in systypes).




SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/16


Example 1

sp_help

OUTPUT:

Lists information about each object in database.

name owner object_type
----------- ----------- ---------------
master dbo user table
detail dbo user table
detail_insert dbo trigger
syscolumns dbo system table
: : :



Example 2

sp_help mastertable

OUTPUT:

Displays information about the mastertable table..

name owner object_type when_created
----------- --------- -------------- ---------------------
mastertable dbo user table Dec 24 1997 11:30 AM


data_located_on_segment
------------------------
default


column_name type length prec scale .....
------------- ------- -------- ----- ----- .....
roll_no char 2 .....
name varchar 10 .....
class char 2 .....


identity seed increment
------------------------- ------- ----------
no identity value defined (null) (null)


Object does not have any indexes.
No constraints have been defined for this object.
No foreign keys reference this table.

sp_helpdb system stored procedure

SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/17

Syntax:

sp_helpdb [dbname]

sp_helpdb provides information about the specified database or all databases (i.e. the name of the device
the database is stored on , the size of the database, the date created, the owner and special database
options).

Example 1

sp_helpdb

OUTPUT:

Shows information about all the databases.

name db_size owner dbid created status
-------- ---------- ----- ----- ----------- ----------------
master 25.00 MB sa 1 Nov 17 1997 trunc. log on chkpt.
model 1.00 MB sa 3 Nov 17 1997 no options set
msdb 8 MB sa 5 Nov 17 1997 trunc. log on chkpt.
pubs 3 MB sa 4 Nov 17 1997 trunc. log on chkpt.
tempdb 2 MB sa 2 Nov 17 1997 select into/bulkcopy
library 4 MB sa 6 Dec 13 1997 no options set


Example 2

sp_helpdb library

OUTPUT:

A database is supplied and more detailed information about the database is displayed.

name db_size owner dbid created status
-------- ---------- ----- ----- ----------- ----------------
library 4 MB sa 6 Dec 13 1997 no options set


device_fragments size usage
----------------- -------- ----------
libdevice 3.00 MB dataonly
libdevice 1.50 MB logonly












SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/18


STORAGE ALLOCATION

When creating a database, the amount of space allocated to it is specified.
Allocating too much space is wastage of device space that could be used by other
databases.
Allocating too little space can result in run out of storage space for that database.
SQL Server allocates the space requested in a fixed way based on a hierarchy.

DIAGRAM










Allocation units

When a database is created, space is allocated in 1/2 MB increments (256 contiguous
2K blocks) known as Allocation units.

Extents

An Extent is 16K ( 8 contiguous 2K blocks).
An extent is allocated when a table or an index is created .
Each object is allocated its own extent i.e. extents are not shared.
Because their are 32 extents per Allocation unit, there can be upto 32 objects (table or
indexes) stored in that Allocation unit.

Pages

The basic unit of storage is 2K blocks (2048 bytes).

If a database is created larger than the available space, SQL Server will allocate as much
space as it can, rounding to nearest 0.5 MB.
Allocation Unit (256
2K blocks)
Extent (8 2K blocks)
Page (2K block)
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/19



CLASSROOM EXERCISE

1. Define defaults and rules with the help of an example.
2. What are extended stored procedures.
3. If a size of a device is 2K blocks is 2048, then what will be the size in MB?
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/20


MANAGING DATABASE DEVICES

About database devices

Only a System Administrator can create a device.

When a database device is created, both a logical and a physical name is provided.


DIAGRAM













Logical name

Used by SQL Server to identify the database device.
The logical name follows the SQL Server rules for identifier
The name must be enclosed in single quotes.
Naming conventions for identifiers are as follows:
(a) Identifies are from 1-30 characters in length.
(b) Firs character must be a letter or the following symbols : -, @, #
(c) After the first character identifiers can include letters, digits or symbols #,
$ or _.
(d) Embedded spaces are not allowed unless quoted identifier are used.
(e) Transact-SQL keywords should not be used.
When using SQL Enterprise Manager (and Transact-SQL statements ) , database
device is referred to by its logical name.

Disk c:\
Device
PHYSICAL NAME
C:\MSSQL\DATA\CUST.DAT
LOGICAL NAME
customer_list
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/21

Physical name

An Operating System file name which includes full path ( drive letter, path, filename
of the database device)
Operating System refers to this filename which represents the device.
By default physical name uses the logical name as part of the path.


EXAMPLE

Logical name Physical name

Database
device
Customer_list C:\MSSQL\DATA\CUST
.DAT
Database
device
Reservations D:\DATA\RES.DAT


Creating Database devices

Disk devices can be created in two ways in SQL Server
(a) Graphically by using SQL Enterprise Manager
(b) Transact-SQL using ISQL command line utility or ISQL/w Windows-based
interface.

Transact-SQL method is performed using DISK INIT command

DISK INIT

Creates a device on which a database or multiple databases can be placed.
Enters the logical and physical name of the device in the sysdevices table in the
master database.
Preallocates the storage to size specified (in 2K blocks)

Syntax:

DISK INIT
NAME = logical_name,
PHYSNAME = physical_name,
VDEVNO = virtual_device_no,
SIZE = number_of_2K_blocks
[, VSTART = virtual_address]



SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/22


DISK INIT parameters

Parameter Description

logical_name logical name of the database device
physical_name full path and file name of the file to be used on the hard disk
to store the data
virtual_device_no Unique system identifier for the device.
Valid device no are 0-255.
0 is reserved for the master database.
number_of_2K_blocks This is how a device is sized, which is the
minimum value of 512, equivalent to 1M.
virtual_address Starting offset in 2K blocks.



EXAMPLE

Example 1

DISK INIT
NAME = NewDevice,
PHYSNAME = C:\MSSQL\DATA\NewDevice.DAT,
VDEVNO = 6,
SIZE = 2048

OUTPUT:

Creates a 4 MB (2048 2K blocks) device called NewDevice on C drive using the physical file
C:\MSSQL\DATA\NewDevice.DAT.


Example 2

DISK INIT
NAME = DemoDevice,
PHYSNAME = C:\MSSQL\DATA\DemoDevice.DAT,
VDEVNO = 2,
SIZE = 512

Creates a 1 MB (512 2K blocks) device called DemoDevice on C drive using the physical file
C:\MSSQL\DATA\DemoDevice.DAT.






SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/23

General guidelines

Being in a master database is a must to create a device. Each time DISK INIT is
executed a row is added to master..sysdevices table.

Before running the DISK INIT command , the stored procedure sp_helpdevice can
be used to determine the device nos. already used.


Device options

There are two options that can be considered for the devices which are created .

Mirroring - Gives fault tolerance option
Default device - Saves time when databases are created on system

These options are helpful depending on the environment setup. The options control how
devices are used after their creation and provide information about how SQL Server can
apply special processing to the devices.

Mirroring

When a device is setup for mirroring , it is indicated to the SQL Server that it should
write transactions to the database on the device twice.
This is done once on the primary device defined for the database and once on the
mirror device.
Mirroring is used to ensure full recovery and continued operation in the event of
media failure.
Mirroring a device continuously duplicates the information from one SQL Server
device to another.
In the event one device fails , the other contains an up-to-date copy of all transactions.

Mirroring can be handled by Windows NT or can be accomplished by Enterprise
Manager, using Transact-SQL.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/24


Mirroring using Transact-SQL

DISK MIRROR

Syntax:

DISK MIRROR
NAME = logical_name,
MIRROR = physical_name

DISK MIRROR parameters


Parameter Description

logical_name Name of the device that will be mirrored
physical_name Full path and filename of the mirror device .
Use MIR as the extension for compatibility with SQL Enterprise
Manager

EXAMPLE

DISK MIRROR
NAME = NewDevice,
MIRROR = C:\MSSQL\DATA\NewDevice.MIR

OUTPUT:
Creates a mirror device for the device NewDevice on C drive, of name NewDevice.MIR


Default devices

When a database is created, the device on which the database is to be created is
specified.
Default devices are used by SQL Server when the device on which database is to be
created is not specified .
Many devices can be specified as default.
SQL Server uses them alphabetically until each device is filled.
Only database devices can be default devices . Dump devices can not be set as
default devices.
When SQL Server is installed MASTER device is the only default device.
The SA should remove master as a default database.
Default devices are specified using sp_diskdefault or through SQL Enterprise
Manager .
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/25
Using sp_diskdefault
Syntax:
sp_diskdefault database_device, { defaulton | defaultoff }
EXAMPLE
Example 1
sp_diskdefault master , defaultoff
OUTPUT:
Makes the master device a non-default device.


Example 2

sp_diskdefault DemoDevice, defaulton

OUTPUT:

Makes the newly created DemoDevice device, the new starting default device.




Displaying device information

There are two ways to find information about the devices that are installed / active on a
SQL Server.

Using SQL Enterprise Manager
Using system stored procedure or querying the sysdevices table

sp_helpdevice system stored procedure can also be run to view the information regarding
the database devices.

Syntax:

sp_helpdevice [logical_name]

logical_name is the name of the device that is to be inspected. If no device is specified, it
reports information on all devices on the SQL Server.


SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/26

Dropping database device

Dropping a device frees up storage space associated with that device for other uses by
the operating system or the server, by freeing the file handle and the device number .

There are two ways to drop a device
(a) Using SQL Enterprise Manager
(b) Using System Stored Procedure

Using Enterprise Manager does not actually make space . The file has to be deleted
manually in this case.

Using SQL Enterprise Manager to drop a device, all databases on it are also dropped.

Using System Stored Procedure with DELFILE option , physical file can be deleted
from the hard disk, which allows to immediately create a new device with the same
device no and logical name.

Syntax:

sp_dropdevice logical_name [, DELFILE]

Parameters Description

logical_name Name of the device to be removed
DELFILE If included, physical file created on the server is also removed.

EXAMPLE

Example 1

sp_dropdevice DemoDevice

OUTPUT:

Drops the device called DemoDevice.
The databases must be dropped before the devices can be dropped.
Physical file is not deleted.

File: C:\MSSQL\DATA\DEMODEVICE.DAT closed.
Device dropped.

Thus when DISK INIT command is executed following error is displayed.

Msg 5123, Level 16, State 1

DISK INIT command encountered an error while attempting to open/create
the physical file....
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/27

Example 2

sp_dropdevice DemoDevice, DELFILE

OUTPUT:

Drops the device called DemoDevice.
The databases must be dropped before the devices can be dropped.
The physical file gets deleted.
DISK INIT command can be used having the same name and vdevno.

File: C:\MSSQL\DATA\DEMODEVICE.DAT closed.
Device dropped.

( 0 row(s) affected )

Physical file deleted


Expanding database device

If additional space is needed for a database device , and if there is adequate space on
the storage media, the space allocated to that device can be expanded.

A database device cab be expanded using the DISK RESIZE statement.

DISK RESIZE can be used on any database device including the MASTER device.
It can not be used to shrink the devices.
DISK RESIZE can not be used for dump devices or when tempdb is in RAM.

Syntax:

DISK RESIZE
NAME = logical_device_name
SIZE = final_size

Parameters Description

logical_device_name Name of the device to be resized
final_size New size of the device in 2K
blocks
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/28


EXAMPLE

Example 1

DISK RESIZE
NAME = master,
SIZE = 16384

OUTPUT:

This resizes the master database device to be a total size of 32 MB.


Example 2

DISK RESIZE
NAME = master,
SIZE = 15360

OUTPUT:

This resizes the master database device to be a total size of 30 MB.
CLASSROOM EXERCISE
1. DISK INIT
NAME = lib_dev,
PHYSNAME = C:\MSSQL\DATA\lib.dat,
VEDEVNO = 3,
SIZE = 6144
a) What is the logical name and the physical name of the device?
b) What is the size of the device in 2K blocks and MB?
2. Write a Transact-SQL statement to increase the size of device Device1
from its initial size of 12 MB to 20 MB.
3. How can you determine what device numbers are available.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/29
MANAGING DATABASES
Creating a database
A database exists one or many database devices.
Correspondingly, a database device can have one or many databases on it.
The portions of the database on different devices are called fragments.
When a new database is created , SQL Server uses the model database as the
template.


Rights for creating the database

Only, System Administrator (SA) for the SQL Server can create a database.
User who has been granted rights by the SA in order to create the database, can create
a database.
One must be in the master database to create a database.



Two ways of creating a database:

(a) Using SQL Enterprise Manager
(b) Using Transact-SQL


Using Transact-SQL to create a database


Syntax:


CREATE DATABASE database_name
[ ON { DEFAULT | database_device } [ = size ]
[, database_device [ = size ] ... ]
[LOG ON log_device [ = size ]
[, log_device [ = size] ... ]
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/30


CREATE DATABASE parameters


Parameter Description

database_name Name of the database to be created.
database_device Device or list of devices that this database is to be created on and
how much disk space ( in MB ) is to be reserved on each.
DEFAULT If DEFAULT is specified, SQL Server chooses the next free
default database device to use.
LOG ON This parameter allows the log device to be specified
log_device Specifies the database device to be used for the log.
Like database device, its possible to specify more than one device
to be used for the logging of the database being created


Consider the following, when using CREATE DATABASE commands.

The minimum size of the database is 1 MB.
When the database is created larger than the available space, SQL Server will allocate
as much space as it can, rounding it to nearest .5 MB.
If the database device is left unspecified, SQL Server will put the database onto one
or more of the default database devices.

EXAMPLES

Example 1

Creating a Single database on default device

CREATE DATABASE db1


OUTPUT :

Creates the database db1 on default database device with the default database size of 2 MB ( the size of
model)


SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/31

Example 2

Create a Single Database on default Device


CREATE DATABASE Demodatabase

ON DEFAULT = 256


OUTPUT :

Creates the 256 MB Demodatabase on default database device



Example 3

Creates a Single Database on Two Devices


CREATE DATABASE Library

ON DEFAULT = 50, DemoDevice = 25

OUTPUT :

Creates the Library database .
Allocates 50 MB on the default database device and 25 MB on the DemoDevice database device.
Allows database to be stored on two devices.



Example 4

Create a Single Database and the log on Single device


CREATE DATABASE NewDatabase

ON NewDevice = 3

LOG ON NewDevice = 2

OUTPUT :
Creates the database called NewDatabase.
Allocates 3 MB on the device called NewDevice
Places 2 MB transaction log on the same device


SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/32


Example 5

Create a Single Database on two devices ( separate Data and Log )


CREATE DATABASE sales
ON NewDevice = 30
LOG ON DemoDevice = 2

OUTPUT :

Creates the database called sales.
Allocates 30 MB on the device called NewDevice.
Places 2 MB transaction log on the device called as DemoDevice.



Using a separate database device for the transaction log

By default transaction log is placed on the same database device as the database. Placing
the transaction log on the different device is always better.

Justification

If the data and log are on the same device, then, in case of media failure, transaction
log dumps can not be saved, so up-to-date recovery will not be possible.
Physical movement of the read write heads on the disk drive is minimized , since I/O
requests for a database are divided between two devices.
If frequent modifications are made to log it can become large and compete for space
with the database.This can reduce the performance of the database, if the database is
heavily used.
Backups are faster and convenient because logs can be backed up separately from the
database.


Assigning the size to the transaction log


10-25 percent of the space allocated to the database, should be allocated to the
transaction log.

Apart from using the LOG ON with CREATE DATABASE statement, the stored
procedure sp_logdevice in conjunction with CREATE DATABASE statement can
also be used for creating a transaction log.



SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/33

Syntax:

sp_logdevice database_name, database_device


sp_logdevice parameters

Parameters Description

database_name Specifies which database has the log (syslogs) table to put on a
specific database device.
database_device Name of the database device on which to put the syslogs table.


EXAMPLE


CREATE DATABASE sales
ON NewDevice = 3, DemoDevice = 2
EXEC sp_logdevice sales, DemoDevice

OUTPUT:

Creates the sales database .
Allocates 3 MB on the NewDevice
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/35

Decreasing the size of the database


DBCC SHRINKDB command allows to shrink the size of the database.

The resulting size of the database cannot be less than the size of the model database or
default database sizes.

Syntax:

DBCC SHRINKDB ( database_name [, new_size])


DBCC SHRINKDB parameters

Parameters Description

database_name The name of the database whose size is to be decreased.
new_size The database is shrunk to the size specified as new_size ( size
specified in 2K blocks)
If the size is not specified DBCC will return the minimum size to
which the database can be shrunk.

EXAMPLE

DBCC SHRINKDB ( sales, 4096)

OUTPUT:

size of the sales database is shrunk to 8 MB.


General guidelines for shrinking the database

DBCC may shrink both log and data portions of the database.
To change size of only the database or the log, shrink entire database and then use
ALTER DATABASE statement to increase the size of the database or log portion of
the database.
DBCC statement doesnt move data, it only moves completely empty allocation units
starting at the end of the database and continues backwardly.
Thus a database dump of master database should taken prior to shrinking the
database.
To shrink a user database, the database must be set to single user mode using
sp_dboption system stored procedure.

Note : sp_dboption covered in detail later.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/36


Dropping databases

Dropping a database frees up any space that it used on any database devices and
removes any objects it contains.

The user accounts that had their default database as the database that is being
dropped, will have their default database changed to the master database.

Only the SA or the database owner has the rights to drop a database.

The master, model, tempdb databases cant be dropped by any user account.

Databases that are involved in replication or have active users cant be dropped until
the replication is suspended or until the users have disconnected from the database.


Dropping the database using the Transact-SQL


Syntax:

DROP DATABASE database_name, [database_name ...]

database_name is the name of the database to be dropped.

EXAMPLE

DROP DATABASE Newdatabase

OUTPUT:
The database Newdatabase gets dropped.



SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/37


DATABASE CONFIGURATION OPTIONS

A number of database options can be configured using the system stored procedure
sp_dboption.
It can be used to display or change the database options.

Database options Description

ANSI null default Allows the user to control the database default nullability
dbo use only Sets a database for use only by the database owner
no chkpt on
recovery
Defines whether or not a checkpoint record is added to the
database after it is recovered during a SQL Server startup.
offline Used for removable media
published Allows the database to be published for replication
read only Defines a database as read only
select into/bulkcopy Allows a database table to accept non-logged operations.
single user Restricts database access to a single user.
subscribed Allows the database to be subscribed for replication
trunc. log on chkpt Causes the transaction log to be truncated ( committed
transactions are removed) every time the CHECKPOINT
process occurs.

For master database only last option can be set.
sp_dboption with no parameters, displays the list of all available database options.
To list all the configured options for a particular database, sp_helpdb system stored
procedure can be executed.

Syntax:

sp_dboption [ dbname,optname,{ true | false }]

Parameter Description

dbname Specifies the database in which the option is to be set.
optname Name of the option to set or turn off. Option name is enclosed in quotes
if it includes embedded blanks or is a keyword.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/38

EXAMPLE

sp_dboption library, single user, true

OUTPUT:

After the option is set, library database can be used by only a single user.
CLASSROOM EXERCISE
1. Create a database called personnel with data portion spanning three
devices ( D1, D2, D3) and log portion on D4. The total database size is
200 MB composed of 150 MB for data and 50 MB for log.

2. Alter the database called sales by adding 5 MB of space. The fragment
should be made log only.
3. Write any two methods that can be used for the situation such that a
database is too large for a database device.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/39
LAB EXERCISES
1. Query the sysobjects table and analyze the output.
2. Display information about all the databases.
3. Display the detailed information about the pubs database.
4. Create the database devices as given in the examples in the book using
both SQL Enterprise Manager and ISQL/w.
5. Make the MASTER device the non-default device and the newly
created device as the default device.
6. Display the device information first for all the devices and then for
one device.
7. Expand the size of the MASTER database device to a total of 30 MB.
8. Create a database called base1 on the default device.
9. Create another database using SQL Enterprise Manager, called base2 on
the default device of size 256 MB.
10. Create a single database called base3 on two devices, on default device
of size 25 MB and on some other device of 30 MB.
11. Create a database called base4 on the device of your choice . Allocate
3MB for the database and 2 MB for the transaction log on the same
device.
12. Increase the size of the database base4 by 3 MB .
13. Shrink the size of the database base2 to 8 MB.
14. Try out the examples given in the book.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Chapter-9/40
SUMMARY
Device is an Operating System file in which databases are stored.
There are two types of devices:
(a) Database devices
(b) Dump devices
Databases are of two types :
(a) User databases
(b) System databases
System databases are
master
model
tempdb
msdb
SQL Server supplied tables are called System tables.
Objects, Indexes, Datatypes and Constraints are Database Components.
System Stored Procedure is a precompiled collection of SQL statements.
Database can be created using DISK INIT statement and can be expanded by using DISK
RESIZE command.
CREATE DATABASE statement is used to create database and transaction log.
ALTER DATABASE statement is used to increase the size of a database or a transaction
log.
DBCC SHRINKDB is used for shrinking the size of the database.
Database options can be configured by using the system stored procedure sp_dboption.
SQL SERVER 6.5
Chapter-10/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Distributed Data Overview
SCOPE
Distributed data
Implementing distributed data
Distributed Transaction Coordinator
Replication
Remote stored procedures
Bulk Copy Program
Distributing data on WWW
SQL SERVER 6.5
Chapter-10/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
IMPLEMENTING DISTRIBUTED DATA
The goal of distributed data is to make data more readily available to the users. With the
distributed data, component partitions of data are distributed over various nodes of the
network.
Depending on the specific update and retrieval traffic, distributing data can significantly
enhance overall performance.
In many situations it is necessary to distribute data across a geographically dispersed
client/server environment. Distributing data does not in any way reduce the need to
ensure consistency, concurrency, adequate performance and security of data.
In fact, it makes it more difficult to provide these capabilities. For example, when
multiple copies of same information exist, there is always the possibility that they might
contradict each other.
The challenge of RDBMS is to provide these capabilities in a multiserver environment
while maintaining performance and security.
The challenge to the implementor/administrator is to determine the method of distributing
the information in the multiserver environment.
Some of the methods which SQL Server uses to implement the distributed data are:
Distribution Transaction Coordinator
Replication
Remote stored procedures
Bulk Copy Program
Distributed Data on World Wide Web
SQL SERVER 6.5
Chapter-10/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DISTRIBUTED TRANSACTIONS
Understanding Distributed Transactions
Many times more than one source of information need to be updated and transaction
technologies need to be applied to the update to ensure that a transaction is valid
before it occurs and all or none of the changes are made against the database table.
The transactions that span more than one server i.e. update data on two or more
network-connected computer systems are referred as Distributed Transactions.
Distributed transactions must be self-contained, autonomous or able to be reversed
without affecting other processes. .
Microsoft Distributed Transaction Coordinator (MS DTC) is a tool that provides the
utility functions that help manage the process.
It addresses the challenges of processing transactions over a distributed set of
software components that exist on a single computer or on a system of networked
computers.
MS DTC is fully integrated with Microsoft SQL Server and provides a transaction
manager in SQL Enterprise Manager at each computer, which is MS DTC user
interface, that manages distributed transactions.
With MS DTC, running transactions and their status can be viewed and transaction
changes can be forced manually.
Two Phase commit
MS DTC utilizes two-phase commit in its implementation
Two phase commit allows an application to coordinate updates among multiple
servers.
This implementation treats transactions on separate SQL Servers as a single
transaction.
It requires one SQL Server to be the commit server which serves as a record keeper
that helps the application determine whether to commit or to rollback transaction.
This commit process runs as a separate process from the transaction.
The role of commit service is to provide a single place where the commit / rollback
status is maintained.
The SQL Servers communicate with the commit service only if a failure happen
during the two-phase commit.
Thus, the two-phase commit guarantees that either all the databases on the
participating servers are updated or that none of them are updated.
First phase
After all servers participating in the distributed transaction have been updated, the
two phase commit begins when all servers agree that they are ready to commit.
SQL SERVER 6.5
Chapter-10/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Second Phase
All servers commit.
A COMMIT TRANSACTION statement is executed to all servers.
Application tells the commit server that the transaction is complete, and connections are
closed. If any errors occur between phases one and two, all servers coordinate with the
commit server to see if the transaction should be canceled or committed.
Processing of Distributed Transactions by DTC
The participants in distributed transactions include:
Application : Application requests the transactions. It can be SQL Server or a client
application.
Transaction Manager : It is responsible for overall coordination of the transactions. This
role is played by MS DTC, installed on either a client or server within the network.
Resource Managers : These contain the resources being operated on. They are the
computers the databases reside on.
Step 1:
MS DTC, SQL Server and client applications communicate by means of methods-
functions that control transaction objects.

An application begins a transaction by calling the transaction manager with a
BeginDistributedTransaction method.

This method creates a transaction object that represents the transaction.
The application then includes the transaction object with execution request to the
resource managers.

When the resource manager receives an execution request with a new transaction
object, the resource, manager enlists in the transaction by calling the transaction
manager.

As the transaction progresses, the transaction manager keeps track of each of the
resource managers enlisted in the transaction.
SQL SERVER 6.5
Chapter-10/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DIAGRAM
Step 2:
The resource manager performs the transactions request.(insert, delete or update).
The resource manager keeps information to allow it to either undo or redo the
transactions work on those resources.
Step 3:
When the application complete the transactions work it calls the MS DTC
CommitTransaction method.
MS DTC goes through a two-phase commit protocol with all enlisted resource
managers. It ensures that all managers commit the transaction or all abort it.
In first phase, MS DTC asks each resource manager if it is prepared to commit. If all
resource managers are prepared, then in second phase it broadcasts the commit
message.
If a failure occurs, resource manager is not sure about the outcome of the transaction.
It then keeps locks on the data that is modified by the transaction.
Once the transaction has successfully committed, the resource managers and the
transaction manager will ensure that the transactions effects are durable.
Application Transaction
Manager
Transaction Object
Begin Transaction
Application Transaction
Manager
Resource Manager
enlist
enlist
SQL SERVER 6.5
Chapter-10/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Using Distributed Transactions
Server must be instructed to participate in a distributed transaction and MS DTC should
be informed be informed of the participation.
SQL Servers participation in an MS DTC transaction can be started by either of the
following:
By a client application calling APIs from DB-Library or ODBC. SQL Server acts as a
resource manager.
By using BEGIN DISTRIBUTED TRANS statement. SQL Server uses remote stored
procedures to specify the transaction work on different database on different servers..
The COMMIT TRANSACTION marks the end of the distributed transaction.
Syntax:
BEGIN DISTRIBUTED TRAN [tran_name]
EXAMPLE
BEGIN DISTRIBUTED TRAN
EXEC sp_addlogin user1
EXEC server1.master.sa.spaddlogin user1
COMMIT TRAN
OUTPUT:
SQL Server login name user1 is either added to both the local and remote server or none.
SQL SERVER 6.5
Chapter-10/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
REPLICATION
Replication overview
Replication is provided as an integral element of Microsoft SQL Server 6.5.
It allows automatic distribution of read-only copies of transactional data from a single
source server to one or more destination servers at one or more remote locations.
This brings with it the ability to synchronize information sources for multiple domains
even in the cases where they are physically separated by distance and poor
communication links.
At its most fundamental level, replication recognizes changes made to the database and
sends these changes to the remote system or systems for their use.
There are two basic replication models:
(a) Tight consistency
(b) Loose consistency
Microsoft has employed loose integration in its replication model.
It allows a time lag between the moment when original data is altered and when the
replicated copies of that data are updated i.e. the information will flow across the system
of servers not in real-time but as quickly as it can.
Tight consistency Vs Loose consistency
Tight consistency Loose consistency
1. Guarantees that all copies will be
constantly identical to the original
Does not guarantee that all copies will be
identical to the original.
2. Requires high speed LAN Supports LANs, WANs, fast and slow
communication links.
3. Reduces database availability Better database availability.
4. Less scaleable model than Loose
Consistency.
More scaleable than tight consistency.
Few ways where replication might be used:
To maintain several decision support servers, removing the report generation and ad-
hoc query impact from the source server.
SQL SERVER 6.5
Chapter-10/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
To distribute and update read-only copies of changes from a master price list on a
source server to several regional servers supporting field offices.
To distribute location specific data from a centralized master table.
To support order processing during a communications outage.
Server roles in replication
Publication server
When data is made available for replication, it is published. The server that provides
the information to other systems i.e. the server that contains the source databases and
makes data available for replication is called publisher or publication server.
The information provided to the other systems by the publisher is called publication.
Publication consists of articles, the basic unit of replication. Articles are the items
provided to the other systems, which are discrete pieces of information that range
from the entire contents of the database to a single row or the result of a query.
Subscription server
A server requesting for the publication is called a subscription server or subscriber.
The subscriber can be Microsoft SQL Server, Microsoft Access database or some
ODBC database whereas the publisher must be Microsoft SQL Server.
Distribution server
Receives data from the publisher, stores in the distribution database, and then
forwards it to the appropriate subscription servers.
Replicated data moves in only one direction - from publication server to subscription
servers.
Each server can act as both a subscriber and a publisher.
EXAMPLE
If server A publishes Publication 1, and server B publishes Publication 2, Server A could act as a
publication server (of Publication 1) and a subscription server ( to Publication 2).
In most cases, the publication server and the distribution server are combined in one
computer.
Types of replication models
There are four distinct replication models
SQL SERVER 6.5
Chapter-10/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Central publisher
DIAGRAM
One server is defined as the publisher.
It distributes data to any number of servers that are setup as subscribers.
This is default option for replication in SQL Server.
Publication server is the primary owner or source of all replicated data.
Subscription sites treat replicated data as read-only.
Example - This scenario might be used to distribute master data, lists or reports from a
central server to any number of subscription server.
Central Publisher using a remote distributor
DIAGRAM

Publisher /
Distributor
Subscribers
Publisher Distributor
Subscribers
SQL SERVER 6.5
Chapter-10/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
A separate distribution server is established to store the data before it is published to
the subscribing server.
Example - Useful when publication server is a heavily used online transaction processing
server and should be freed from the distribution role because of performance and storage
considerations.
Central subscriber
DIAGRAM

Multiple publishers replicate data to a single subscriber.
It addresses the need for consolidating data at a centralized site and providing the
local site with an overview of all the data.
Multiple publishers are writing to the same subscription table, hence precautions must
be taken to ensure that all data remain in synchronization.
Example - Useful for rolling up inventory data from a number of servers at local
warehouses into a central subscriber at headquarters.
Multiple publishers of one table
DIAGRAM
Distributor /
Publisher
Distributor /
Publisher
Distributor /
Publisher
Distributor /
Publisher
Subscriber
Publisher / Distributor /
Subscriber
Publisher / Distributor /
Subscriber
SQL SERVER 6.5
Chapter-10/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Multiple publication servers and multiple subscription servers each potentially play a
dual role.
It is closest to the implementation to fully distributed data processing.
Each server controls its own data and has a view of the other data.
Example - Useful for maintaining common information at regionally dispersed centres.
Guidelines for implementing replication
It is important to replicate only the necessary data and not the whole database.
If sites are read only and only need specific information from the database, replication
can be used.
If sites must have update capabilities, do not consider replication.
The database server that serves as the central point for data modification is the best
candidate for distributing information.
CLASSROOM EXERCISES

1. What is the difference between a distributed and a replicated
information?
2. What could be the advantages and disadvantages of using the
loose consistency model?
Publisher / Distributor /
Subscriber
SQL SERVER 6.5
Chapter-10/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
REMOTE STORED PROCEDURES
Remote stored procedure allows a client who is connected to one SQL Server to
execute a stored procedure on another SQL Server without establishing a connection
to the second server.
The server to which the client is connected accepts the request and sends the request
to the remote server on the clients behalf.
The remote server processes the request and returns any results to the original server,
which in turn passes those results to the client.
Requests can be initiated by the clients on the server.
Syntax:
EXEC server_name.dbname.owner.stored_procedure_name
Remote execution does not require a client to open the connection to the remote
server.
Client executes the stored procedure using EXEC statement as part of normal batch
submitted to the local server.
The name of the remote server must be included.
EXAMPLE
EXEC sp_who
EXEC remote_server.master.sa.sp_who
Both stored procedures are returned to the client in a identical manner.
Server to server connection information must be available to both the servers before
the connection can be opened.
This information is stored in master database, and is added using system stored
procedure.
System stored procedures used in server administration are:
sp_addremotelogin
sp_addserver
sp_dropremotelogin
sp_dropserver
sp_helpremotelogin
sp_helpserver
sp_remoteoption
sp_serveroption
SQL SERVER 6.5
Chapter-10/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Implementing remote stored procedures
A server must be willing to participate in this network. Remote Access configuration
option is turned on to enable participation.
Each server must store both its own name as the local server and the name of the
server in the sysservers table.
The login id that the local server uses when opening the connection must exist on the
remote server.
SQL SERVER 6.5
Chapter-10/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
BULK COPY PROGRAM
Command line utilities are executable programs which are rum from a command prompt.
Bulk Copy Program (BCP) is a command line utility that copies SQL Server data to or
from an Operating System file in a user specified format.
The utility can be used to transfer:
large amount of data to and from SQL Server through an intermediate file.
data into SQL Server database from another program usually another DBMS.
data for use with other programs for example spreadsheets. Data is moved from SQL
Server into an Operating System file or onto a diskette, from there, the other program
can import data.
Guidelines for copying data
The table structures of the source and destination tables need not be identical.
Data copied into SQL Server is appended to existing contents of table.
Data copied to a file overwrites any previous contents of file.
Permissions for copying data
To copy data from an Operating System file into a table, a user must have INSERT
permission on the table.
To copy a table or a view to an Operating System file, the user must have SELECT
permission on
table or view being copied
sysobjects
syscolumns
sysindexes
For transferring data to and from SQL Server, following information is provided
The name of the database
Name of the table or view
name of the Operating System file or diskette drive
The direction of transfer (in/out)
In addition , other parameters like length, datatype and terminator of the column can also
be specified.
SQL SERVER 6.5
Chapter-10/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
EXAMPLE
bcp library..member out mem_out /n /Sservername /Usa /Ppassword
Copies the member table from library database to mem_out file.
out option copies to a file from the database table or view.
/n uses the database datatypes as default (does not prompt for each field).
Server name, sa and password specify the name of the server and the login to connect to transfer data.
Note: See Appendix C for details
Copying tables with or without indexes
Tables without indexes Tables with indexes
bcp utility is fastest if the database table
has no indexes,or constraints that use
indexes.
bcp utility is slow if database table has
indexes, or constraints that use indexes.
For fast bcp, sp_dboption system stored
procedure is used to set the select
into/bulkcopy option for that database
true.
sp_dboption databasename, select
into/bulkcopy, true
For a table that has indexes,or constraints
that use indexes, there is no need to set
the option.
Fast bcp does not log data insert in
transaction log.
Inserts into the tables with indexes are
always logged.
By default, the select into/bulkcopy option is off.
Integrity issues
Any defaults defined for the columns,and datatypes in the table are always enforced
when data is copied into a table.
Rules and triggers are not enforced so as to load the data at maximum speed.
bcp out is static i.e. any updates made to the data during the bcp processes will not
be reflected in the bcp data file.
bcp in is dynamic i.e. all rows of a batch become available after the batch has
finished.
SQL SERVER 6.5
Chapter-10/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CLASSROOM EXERCISES
1. Why bcp defaults to slow bcp?
2. How can you make sure that no one else can access the database while
exporting the data?
SQL SERVER 6.5
Chapter-10/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DISTRIBUTING DATA ON THE WORLD WIDE WEB
World Wide Web (WWW) pages
World Wide Web is one of the most visible Internet services. It presents information
textually and graphically and turns Internet into an information resource and marketing
tool.
The (HyperText Markup Language) HTML files, also known as web pages, are resources
for displaying information on World Wide Web.
HTML commands are added to the document file using a text editor, or using a
specialised web page editor like Microsoft Word Internet Assistant. These commands are
used to present and format the simple text, tables and database query results.
These HTML pages can be viewed by using any HTML ( or web page) browser.
Distribution models
There are two ways in which data can be distributed on the Internet.
(a) Data push model
(b) Data pull model
Data push model
A web page is built and posted on the Internet.
The web users accessing the information through the Web Browser can not
manipulate the data, since it is read-only.
DIAGRAM
SQL
Server
Internet Server
Web Browser
HTML
files
Browser
reviews data
SQL SERVER 6.5
Chapter-10/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Data pull model
A client opens a web page posted on the Internet server and interacts with the page.
Internet server queries SQL Server for the requested information.
The information is pulled, a new web page is generated and send to client.
DIAGRAM
The SQL Server Web Assistant
The SQL Server Web Assistant, an easy-to-use interface, assists in the process of
publishing Microsoft SQL Server data on the World Wide Web. This tool is used to
implement the data push model.
It allows to define a set of data (a query) which is automatically merged into an HTML
document and pushed to the Internet Server.
The pages can be generated on one-time basis or as a regularly scheduled SQL Server
task. A web page can also be updated using a trigger when the supporting data changes.
In order to use SQL Server Web Assistant, one must have:
(a) CREATE PROCEDURE privileges in the database.
(b) SELECT privileges on the columns accessed by the query.
Options for creating a web page
After connecting to the SQL Server Web Assistant from the SQL Server 6.5 program
group, certain information is supplied and selections are made for other options in a
series of dialog boxes.
SQL Server
returns data
Internet Server
requesting data from
SQL Server
Web
Browser
SQL
Server
Query
Receiving
data
Internet
Server
SQL SERVER 6.5
Chapter-10/19
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Providing login
An appropriate login id is provided to access tables and databases that need to be used in
providing content for the required web page.
Selecting the contents for the web page (Specifying the query)
Queries in SQL Server Web Assistant can be built using one of the three options shown
by the Query dialog box:
Queries from a graphical database/table hierarchy - Allows to use the point-and-click
interface and indicate the tables and other items to be included in the query that will
be used to generate the page.
Free form query option - Allows to specify the database and directly enter (typing in)
the query
Query by using an existing stored procedure.

The query page asks you to select how to apply the query and then to type the query.
Scheduling
Creation of web pages can be scheduled as follows:
Scheduling option Description
Now Immediate, one time execution
Later One time execution for a specified date and time.
When data changes Automatic triggered execution. Changes to certain
tables and columns cause the web page to be updated.
On certain days of the week Execution at a day and time, for example, Wednesday
at noon.
On a regular basis Execution every n minutes, hours, days or weeks for
example every 5 minutes.
File options
The file name and path of the web page is created.
This is either on local or remote computer.
An optional template file can be used as a template for the web page. The template
can contain any static text, URL links or other features.
The title of the web page is specified and a title for the results set is also specified.
One or more URL links can be specified or a data query can be specified that returns
the formatting and presentation of the data with the additional HTML pages.
SQL SERVER 6.5
Chapter-10/20
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Formatting options
HTML offers a limited variety of fonts and formatting options.
HTML heading styles to be used for the titles of the web page and data sections can
be specified.
Timestamp and column headers can be included.
If a template file is used, several of these options will already be determined.
After an HTML page is generated, it can be viewed by any web browser.
DIAGRAM
Implementation of data pull model
Web users can initiate dynamic queries from an HTML document to a SQL Server,
through the Microsoft Internet Information Server (IIS).

IIS provides the software necessary to publish information on Internet.

Integration of SQL Server with IIS, including its built-in Internet Database
Connector (IDC) which is an Internet Server API, modifies and retrieves the
information from the SQL Server as well as create new web pages and send these
back to the Web users.
DIAGRAM
Web
Browser
IDC
Internet
Server
SQL
Server
Query
IIS requesting
data from SQL
S
SQL Server
returns data
Receiving
data
SQL
Server
( Web
Assistant)
Internet Server
Web Browser
HTML
files
Browser
reviews data
IIS
SQL SERVER 6.5
Chapter-10/21
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
The IIS provides access to the ODBC layer with the use of IDC.
IDC acts as a go between for system, providing the interface between HTML and
how the information is queried at database level.
An HTX file is returned to the user, which indicates how the resulting data is
displayed.
DIAGRAM
Thus, there are three components:
Initial source HTML document containing form fields and other options.
The IDC file for making and carrying out the database commands.
The HTX file for presenting the information returned.
Building form to prompt for values
A form is presented to the user which allows them to select what information they
need.
Forms can be created which allow input that can be used to form the SQL statements
that are passed to the data source.
Incoming HTTP request
IDC document
The IDC source indicates the ODBC
DSN, SQL statement and applicable
parameters to use to retrieve
information.
Internet Information Server
ODBC
ODBC datasource
HTX document
The HTML extension file indicates
how the output data should be
provided to the users browser.
To browser for display to the user
SQL SERVER 6.5
Chapter-10/22
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
A sample HTML file (form.htm)
<HTML>
<HEAD>
<TITLE>
Demonstration form
</TITLE>
</HEAD>
<h1>sample form for database access</h1>
<FORM METHOD=POST ACTION=/scripts/form1.idc>
Enter name to find : <INPUT NAME=au_lname>
<p>
<INPUT TYPE=SUBMIT VALUE=Run query>
</FORM>
</BODY>
</HTML>
In this example, form1.idc is called and passed parameters. Notice, that the variable name
au_lname is used to reference the value provided by the user. Thus, a user is allowed to
type a name that can be used to search the authors table in the pubs database.
The browser opens a new URL on the server with the following specification:
http://scripts/form1.idc?au_lname=<name>
Building server query source file
When the URL is accessed, the server will run the indicated IDC file.
IDC file contains the SQL statements and directives necessary to carry out the
commands needed.
A sample IDC file (form1.idc)
Data source: web sql
Username: sa
Template: form1.htx
SQLstatement:
+SELECT au_lname, phone, address from authors
+ where au_lname like %au_lname%%
The user will not see this file or output from it directly. The IDC calls the Template
indicated and passes in the results to be returned as a Web page.
Notice, that the variable is placed between percentages.
The data source indicated in the IDC relates to the ODBC data source established with
the ODBC manager.
SQL SERVER 6.5
Chapter-10/23
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
After the values have been retrieved that you want to display, the results can be moved on
to the results set source files.
Building Results Source file
The HTML extension files with the extension .HTX are referenced in the Template
entry in the IDC file.
These files need to be created to dictate how the information is presented.
SQL SERVER 6.5
Chapter-10/24
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
There are various methods which SQL Server uses to implement the Distributed Data.
Distributed Transaction Coordinator - Tool that provides the utility functions that help
manage the transactions that span more than one server.
Replication - Allows automatic distribution of read-only copies of transactional data from
a single source server to one or more destination servers at one or more remote locations.
There are three server roles:
Publication server
Subscription server
Distribution server
Types of replication models:
Central publisher
Central publisher using a remote distributor
Central subscriber
Multiple publishers of one table
Remote stored procedures - Allow a client connected to one SQL server to execute a
stored procedure on another SQL Server without establishing a connection to the second
server.
Bulk Copy Program - A command line utility that copies SQL Server data to or from an
Operating System file in a user specified format.
Distributing data on WWW - Two types of models
Data push model- Implemented by SQL Server Web Assistant.
Data pull model - Through IIS.
SQL SERVER 6.5
Chapter-11/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Extensibility of SQL Server 6.5
SCOPE
SQL Executive Managers
Extended Stored Procedures
Messaging Application Programming Interface (MAPI)
Using OLE with SQL Server
SQL Distributed Management Objects (SQL-DMO)
Open DataBase Connectivity (ODBC)
SQL SERVER 6.5
Chapter-11/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SQL EXECUTIVE MANAGERS
SQL Server is capable of extending beyond its environment i.e.
a) Certain tasks and statements can be scheduled and automated. (Using SQL
Executive Managers)
b) Their are components of SQL Server which enable to develop sophisticated
client/server applications that tap the power of SQL Server. ( Using Extended
stored procedures, OLE, ODBC, DB-LIB)
SQL Executive Managers
SQL Executive is a component of SQL Enterprise Manager.

It is a Microsoft Windows NT service that provides :

(a) Scheduling capabilities
(b) Event alerting capabilities
(c) Replication capabilities

These capabilities allow the scheduling and administration of SQL Server events.



DIAGRAM











SQL Executive
Alert Manager Event
Manager
Task Manager Replication
Manager
SQL SERVER 6.5
Chapter-11/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Following table defines the services of SQL Executive Managers:

Services Definition

Alerts Notifications that are automatically invoked when events occur.
Designated administrators are notified by means of e-mail or pagers.
Events Anything that posts events to the Windows NT Event Log with a
source of SQL Server ( either directly from SQL Server or using
xp_logevent extended stored procedure or RAISERROR.
Tasks Corrective measures that are automatically fired when events occur.
Can be implemented as Transact-SQL scripts or Windows NT
command-shell scripts.
Can be scheduled for regular execution as well as being tied to an
event.
Replication Ability to transfer data across multiple servers.


Event, Alert and Task Managers

Using SQL Enterprise Manager, server events, alerts and tasks can be created.

Event Manager

Event Manager processes and responds to SQL Server events which are posted to
Windows NT Event Log.
Windows NT log is the central location for application event processing.
It notifies the SQL Executive Service about an event.

Alert Manager

Alerts provide an early warning mechanism for administrators.
Alerts can be defined on any SQL Server event.
They can be associated with the operator or a group of operators who will receive
notifications by e-mail or pager. ( Operators along with their e-mail or pager are
created using Alert Manager.) To support this, Microsoft Mail (provided with
Window NT) must be configured.
Tasks can also be automatically invoked in response to the alert.

Task Manager

Task Manager allows an administrator to define, build and automate administrative
tasks that can be scheduled for:

(a) Execution at a specified time and date
(b) Executed on demand
SQL SERVER 6.5
Chapter-11/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Many administrative functions can be automated such as:


(a) Database/Log backups
(b) Index rebuilds
(c) Data loads etc.

After the creation of a task, it can be scheduled by the SQL Executive.

Administrators control the :

(a) Occurrence ( Daily, Weekly, Monthly and so on)
(b) Frequency ( Once only, Once every day, Once every hour and so on)
(c) Duration of the task.


SQL Alert Engine

DIAGRAM























The following steps are involved in processing an alert.

SQL Server

msdb

system tables
msdb
Windows NT Event
Log

SQL Executive
1.
3.
Send Page or
e-mail to operator
Fire:
Transact-SQL
Window NT
Cmd Shell
4.
5.
2.
SQL SERVER 6.5
Chapter-11/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


SQL Executive starts up and registers itself as a callback application for the Windows
NT Event Log Service.
When an event occurs ,the SQL Server records the error information in the Windows
NT Event Log using xp_logevent or RAISERROR.
When an error is recorded in the Window NT Log, SQL Executive is notified that an
error from the SQL Server has occurred.
SQL Executive retrieves the error information from the Window NT Event Log.
SQL Executive then reads the sysalerts table of the msdb database to determine if any
alerts and tasks are defined for this event.
It matches the Windows NT Event Log to the sysalerts table. The match is based on
the following:

Windows NT Event Log msdb..sysalerts

Event Source sysalerts..Even_Source
Event Description sysalerts..Message_ID
Event Description sysalerts..Severity


The Event Source and the Event Description information in the Windows NT Event
Log must match sysalerts..Event_source and either Message_ID or Severity
information.
If a matching alert is found, the defined action takes place ( sending e-mail, page or
firing off associated task)
If no alerts are defined for this event, the event can be forwarded to the Alert Server
for processing.
SQL SERVER 6.5
Chapter-11/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

EXTENDED STORED PROCEDURES

Extended Stored Procedures provide a way to dynamically load and execute a
function within a Dynamic Link Library (DLL).
Actions outside the SQL Server can be easily triggered.
External information can be easily returned to SQL Server.
Extended Stored Procedures are external to SQL Server, so they must be specified in
the case ( lowercase) in which they were designed.
Return Status Codes and Output parameters are supported which are identical to their
counterparts in regular stored procedures .
Extended stored procedures are categorised by their use as follows:

Integrated Security - Used for security purposes. Some examples are xp_logininfo and
xp_grantlogin.

Extended Stored Procedure Description

xp_logininfo Reports the account,its type, privilege level and the
permission path by which the account has to access
SQL Server.
xp_grantlogin Grants SQL Server access to a Windows NT based
group or user.

SQL Mail - Used for sending and receiving mails. For example, xp_sendmail and
xp_readmail.

Extended Stored Procedure Description

xp_sendmail Sends a message or a query results set or an
attachment to the specified recipient.
xp_readmail Reads a mail message from the SQL Server inbox.
Used by the sp_processmail system stored
procedure to process all mail in the SQL Server
inbox.

General - For example xp_cmdshell and xp_logevent.

Extended Stored Procedures Description

xp_cmdshell Executes a given command string as an Operating
System command shell and returns any output as
row of text.
xp_logevent Logs a user defined message in he SQL Server Log
file or in the Windows NT Event Viewer.
SQL SERVER 6.5
Chapter-11/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Internal - A number of extended procedures exist for internal use by other stored
procedures. For example, xp_readmail.

User-defined - Additional extended procedures can be created by programmers using
Microsoft Open Data Services.

SQL Server can call an extended stored procedure as the result of a trigger or a user
can issue an EXECUTE command, specifying the name of the extended stored
procedure and supplying any parameters required.


EXAMPLES

Example 1

xp_logevent, error_number message, [severity]

DECLARE @tabname varchar(20)
DECLARE @username varchar(20)
DECLARE @message varchar(230)
SELECT @tabname = member
SELECT @username = USER_NAME()
SELECT @message = The table + @tabname + is not owned by the user +
@username
EXEC xp_logevent 60000, @message, Informational

OUTPUT:
The message ( with variables passed to the message ) is logged in the Windows NT Event Viewer.
60000 is a user defined error number greater than 50000.
Severity is specified as one of the three : Informational, Warning, or Error.


Example 2

xp_cmdshell command [, no_output]


EXEC master..xp_cmdshell dir *.exe

OUTPUT:

Returns a list of Executable files.


SQL SERVER 6.5
Chapter-11/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Managing Extended Stored Procedures

Registering new extended stored procedures

Once an extended stored procedure is created using ODS,it must be added to SQL
Server by using the system stored procedure sp_addextendedproc.
It adds entries to the sysobjects table to register the name of the new extended
procedure in the master database.
It adds the name of the DLL as an entry into the syscomments table.
Only the SA can add extended stored procedures.
They must be in the master database.

Syntax::

sp_addextendedproc function_name, dll_name

EXAMPLE
sp_addextendedproc xp_diskfree, xp

OUTPUT:

xp_diskfree is the name of the function to call within the DLL.
xp is the name of the DLL.
Extended stored procedure called xp_diskfree gets registered.



Dropping an extended stored procedure

The system stored procedure sp_dropextendedproc is used to drop the extended
stored procedure.

Syntax:

sp_dropextendedproc function_name

EXAMPLE
sp_dropextendedproc xp_diskfree

OUTPUT:
The extended stored procedure xp_diskfree is dropped from the sysobjects table.



SQL SERVER 6.5
Chapter-11/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Displaying help on an extended stored procedure

The system stored procedure sp_helpextendeproc displays the currently defined
extended functions and the name of the DLL to which the function belongs.
If a function name is given, only information about that function is displayed.
Syntax:
sp_helpextendedproc [ function_name]
EXAMPLE
sp_helpextendedproc xp_diskfree
OUTPUT:
The name and DLL of the extended stored procedure is displayed.


name dll
----- ------
xp_diskfree xp.dll



Messaging Application Programming Interface (MAPI)

SQL Server includes extended stored procedures that allow SQL Server to send and
receive mail messages through a built-in messaging application programming interface
(MAPI) in Window NT. This capability is called SQLMail.

SQLMail can be used to send and receive messages when
A SQL Server alert occurs
A SQL Server Performance Monitor Threshold is exceeded.
A scheduled task succeeds or fails

SQLMail messages can consist of short text strings, output from a query or an attached
file.

Using SQLMail extended stored procedures, messages can be sent from a trigger or
stored procedure. For example, a trigger can be set to send a message when changes
occur in a database.

The server must be configured as a mail client, before it can send or receive messages
through MAPI.
SQL SERVER 6.5
Chapter-11/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


EXAMPLE
xp_sendmail @recipient = recipient [; recipient2; [...; recipientn]]

[, @message = message ]
[, @query= query ]
[, @attachments= attachments ]
[, @copy_recipients = recipient [; recipient2;[...;recipientn]]]
[, @subject= subject ]
[, @type = type ]
[, @attach_results = {true | false}]
[, @no_output = {true | false}]
[, @no_header = {true | false}]
[, @width= width]
[, @separator = separator]
[, @echo_error = {true | false}]
[, @set_user = user]
[, @dbuse = dbname ]

xp_sendmail @recipient = user1;user2
@query = SELECT * FROM sysobjects,
@subject=SQL Server Report,
@message=The contents of sysobjects:,
@attach_results=TRUE

OUTPUT:
Results of the query SELECT * FROM sysobjects are sent as a text file attachment to user1.
It includes a subject line for the mail and a message that will appear before the attachment.


The system stored procedure sp_processmail incoming mail messages, which can be
only a single query, from the inbox for SQL Server. It uses the extended stored
procedures xp_findnextmsg, xp_readmail, xp_deletemail.

It uses xp_sendmail to return the results set back to the user.



CLASSROOM EXERCISE

1. For an alert, what can be the two types of responses?

2. Write the extended stored procedure to send a message to a user called
user1 that the master database is full.





SQL SERVER 6.5
Chapter-11/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

USING OLE WITH SQL SERVER


OLE Automation

OLE is a programming technology that exposes objects, properties, and methods of
an object application (SQL Server in this case) to other controller applications (like
VB).

Controller applications can then program the object application.

It allows applications to share objects for either administration or data access.

Thus, OLE Automation Controllers are applications and programming tools that
access OLE Automation Objects.

OLE Automation controllers can create OLE Automation objects that reside in
another application, and can manipulate those objects using properties and methods
that the OLE Automation Object supports.

An OLE Automation Server is an application that exposes OLE Automation objects
for use by OLE Automation Controllers.

An OLE Automation server is not capable of application programming.

DIAGRAM










OLE Automation has 2 main functions:
(a) Expose objects - OLE Automation exposes objects.
(b) Manipulate objects - After exposing objects, something must be done with the
object. An OLE Automation Controller program uses OLE Automation objects
exposed by other applications. Microsoft Visual Basic is an example of OLE
Automation Controller.




VB
SQL SERVER
OLE Automation
Server
OLE Automation
Controller
DMO
SQL SERVER 6.5
Chapter-11/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SQL Distributed Management Objects (SQL-DMO)
Distributed Management Objects (DMO) was developed using OLE architecture.

DMO makes it possible for the developers to directly access SQL Server database
objects.

Though system data can be accessed by referencing these objects, they are not
designed for full data management.

The key is to expose interfaces for all SQL Server Management functions.

SQL-DMO are 32-bit OLE automation objects for the Windows 95 and Windows NT
Operating Systems.

SQL Enterprise Manager, a tool that simplifies managing multiple server
environment utilizes the OLE service, which provide easier administration of tasks
since relationship between the objects are known.
DIAGRAM
OLE AND SQL SERVER
The complete SQL-DMO type library is contained in the SQLOLE65.TLB file,
located by default in the C:\MSSQL\BINN directory.

It contains information abut all SQL-DMO objects , properties and methods, and is
usually used by the OLE Automation Controllers such as Visual Basic.
SQL Enterprise Manager VBA, VC++, etc.
SQL OLE
SQL Server Object application
Controller
application
SQL SERVER 6.5
Chapter-11/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
In providing a consistent OLE interface to all SQL Server administration functions
and services, DMO includes commands and tasks that are implemented in many
ways, some are:
SQL Server system stored procedures (sp_addtype,)
Open Data services Extended Stored Procedures (xp_sendmail,)
Transact-SQL statements
SQL Performance Monitor scheduled events
SQL Server system catalog contents
SQL Server DMO Model
The following define the components of the SQL Server Object Model:
Object and Collection Multiple objects of the same type. (For examples all databases in
a server.
Object only The primary component of SQL Server. ( For example, Server, database,
table, views and so on)
Collection only A group of related objects associated with a higher ranking object in the
hierarchical structure.
For example, database is an object that contains a collection of tables associated with the
database.
A collection implies ownership between an object and its collection.
For example, in Server.databases, the server owns the collection of databases.
Database Object properties
Object properties are single-named pieces of information maintained for an object.
For example, Server.name, Server.Version and so on.
These are generally simple datatypes.
For example, a column in table is a property of the table, but is also an object in itself.
Database Object methods
Object methods are actions that are associated with objects.
For example, Server.Start, Server.Stop.
SQL SERVER 6.5
Chapter-11/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OPEN DATABASE CONNECTIVITY
SQL Server driver enables applications to access data in SQL Server through ODBC
interface.
The ODBC driver is installed automatically when SQL Server client software is installed
on Win NT, Win 95 or Win 3.1 computers.
ODBC has following characteristics:
It is a call level interface for accessing many databases from Windows applications.
It allows to write one application that can access many different data sources by
using different ODBC drivers.
It is a layer of abstraction between the application and the underlying database
system.
It is responsible for taking your request for information and changing it into the
language the database engine will understand and use for retrieving the information
in the database.
Thus, a common set of calls and methodologies can be developed without having to
worry about the subtleties of the underlying database.
DIAGRAM
DBase SQL Server
Dbase driver
SQL Server
driver
ODBC DLL
Application
Network
Client
SQL SERVER 6.5
Chapter-11/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
CLASSROOM EXERCISE
1. Define the term OLE Automation

2. What is the function and purpose of ODS?
3. What is Open DataBase connectivity?
SQL SERVER 6.5
Chapter-11/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
SQL Executive is a Microsoft Windows NT service that provides :

(a) Scheduling capabilities
(b) Event alerting capabilities
(c) Replication capabilities
Extended Stored Procedures provide a way to dynamically load and execute a function
within a Dynamic Link Library (DLL).
SQL Mail - SQL Server includes extended stored procedures that allow SQL Server to
send and receive mail messages through a built-in messaging application programming
interface (MAPI) in Window NT.
OLE is a programming technology that exposes objects, properties, and methods of an
object application to other controller applications .
OLE Automation Controllers are applications and programming tools that access OLE
Automation Objects.
DMO makes it possible for the developers to directly access SQL Server database
objects.
ODBC allows to write an application that can access many different data sources by
using different ODBC drivers.
SQL SERVER 6.5
Chapter-12/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Overview of administration
SCOPE
Security concepts
Types of security
Types of login IDs
Permissions
Backing up and restoring
Using removable media for the databases
SQL SERVER 6.5
Chapter-12/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SECURITY CONCEPTS
SQL Server security protects the server and the data stored on that server.
SQL Server security determines who can logon to the server; the administrative tasks
each user is allowed to perform; which databases, database objects and data each user can
access.
Types of security
SQL Server security can be implemented in three ways:
Standard security
Integrated security
Mixed security
Standard security
SQL Server is wholly responsible for managing and maintaining accounts on the
server.
SQL Server is responsible for authenticating a user and for enforcing password/login
restrictions.
To log into a SQL Server, each user must provide a valid login ID and password.
Integrated security
Because SQL Server runs only on Windows NT, Microsoft could take advantage of ,
and integrate into, Windows NTs excellent security system.
This allows a network user to log in to a SQL Server without supplying a separate
login ID or password.
Users can maintain one login ID and password for both Windows NT and SQL
Server.
A login to the Windows NT server is either granted or denied connection to the SQL
Server based on attributes of the users login account to the NT server.
Login security integration operates over network protocols that support authenticated
connections between clients and servers. Such connections are referred to as trusted
connections.
Once the login process is complete, all other SQL Server security checks are handled
as usual. Access to individual SQL Server tables, for example, is managed through
the permissions granted within a SQL Server database.
SQL SERVER 6.5
Chapter-12/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Mixed security
It is a combination of both standard and integrated security.
It means that users can log into the server in either way.
When a user connects to SQL Server in mixed security mode, the server validates the
login by first checking whether the login name has already established a trusted
connection to the NT server.
If no connection is found, SQL Server then performs its own validation of the login
name and password supplied.
If the requested login is not a known SQL Server login, access is denied.
SQL Server login IDs
By creating a login ID a user is enabled to attach to the SQL Server.
A login ID is a name by which a user is known to the SQL Server.
Login IDs are administered and created from the Manage Logins dialog box of the SQL
Enterprise Manager.
Only a System Administrator (SA) can manage login IDs.
When SQL Server is installed, two login IDs are automatically created; sa and probe.
When a server is configured to participate in replication, one or both these IDs are
automatically created: repl_publisher and rep_subscriber.
The sa login ID
Responsible for administrative tasks.
Anyone who knows the SA password can log in using the sa login ID and act in the
role of system administrator.
The system administrator is responsible for setting up and maintaining SQL Server.
The tasks include:
a) Installing SQL Server
b) Creating devices and databases
c) Managing disk space, memory and connections.
d) Authorizing SQL Server users and granting permissions to them.
e) Transferring data in and out of SQL Server databases.
f) Backing up and restoring databases.
g) Configuring the server for replication
h) Diagnosing system problems and fine tuning SQL Server to achieve best
performance.
SQL SERVER 6.5
Chapter-12/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
The probe login ID
A special login ID that is installed by the setup program.
Used as the security context within which administrative applications (for example,
SQL Performance Monitor ) connect to a SQL Server that is configured for standard
security.
User should not log in using this login ID.
The repl_publisher ID
Created automatically when a server is set as a subscription server.
It allows replication processes on the distributor / publisher server to connect to a
subscription server and replicate table schema and data to destination databases.
The login ID should not be modified and users should not users this to log in.
The repl_subscriber ID
Created automatically when a server is set as a publication server.
It allows replication processes on a subscription server to connect to a publication
server.
This login ID should not be modified and should not be used for logging into SQL
Server.
Database users
A user is allowed to access a database by assigning a database username to the users
login ID.
The username can be :
One created specifically for that login ID
Someone elses username in the database (alias)
When a user is added to the database, the group to which a user belong can be specified.
A group is a collection of users and is a convenient way to provide common permissions
to those users.
There is a built-in group called public, that users belong to by default.
SQL SERVER 6.5
Chapter-12/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Usernames
A database username is a name known to a database, and assigned to a login ID for
the purpose of allowing a user to have access to a database.
A database username is simply called as user.
The abilities a user has within a database depends on the permissions granted to the
username, and the permissions granted to any groups the username is a member of.
Since usernames are separate from login Ids, user preferences can be accommodated.
For example, if there are three users called John, all the three will be having different
login Ids. However, if they are using different databases, each John might prefer to be
known simply as John inside a particular database.
Aliases
An alias is a database username that is shared by several login Ids.
It allows to treat more than one person as the same user inside a database, giving all
of them same permissions.
Allows several users to assume the role of database owner.
Groups
A group is a collection of database users.
The users receive database permissions granted to the group.
Using group simplifies management of a large number of database users who share
common requirements.
Owners
Within each database SQL Server recognizes two types of owners:
Database owners
Database object owners
Database Owner
The database owner (DBO) is the creator of the database.
The authority to create a database is granted to users by the SA.
The DBO has full privileges inside a database that he owns.
The DBO can do the following:
a) Allow user access to the database.
b) Grants users permissions to create objects and execute commands within the
database.
c) Setup groups.
SQL SERVER 6.5
Chapter-12/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
In his own database, the user is recognized as DBO,in other databases he is known by
his database username.
When SQL server is installed, the SA is the DBO of the master database and also for
the databases he uses.
Only one login ID can be DBO, others login IDs can be aliased to DBO.
Database Object Owner
The user who creates a database object (tables, indexes,views, defaults, triggers,
rules, and procedures) is the database object owner.
The DBO first grants to the user, permission to create a particular object.
The creator of a database object is automatically granted all permissions on that
object.
A database object owner must explicitly grant permissions to other users before they
can access the object.
Even the DBO cannot use an object unless the object owner has granted the
appropriate permission.
Permissions
Permissions are used to enforce the data security.
SQL Server permissions specify which users are authorized to use which Transact-SQL
statements, views, stored procedures.
The ability to assign permissions depend on each users status. (As SA, DBO or database
object owner.)
Permissions are set on database users or groups, not on login Ids.
SQL Server has two categories of permissions:
Object permission
Statement permission.
Some statement permissions are handled as object permissions because these statements
apply to the database objects. (For example, SELECT, UPDATE, DELETE, INSERT and
EXECUTE)
SQL SERVER 6.5
Chapter-12/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Object permissions
Regulate the use of certain statements on certain database objects.
They are granted or revoked by the owner of the object.
Object permissions apply to the following statements and objects:
Statement Object
SELECT Table, views, columns
UPDATE Table, views, columns
DELETE Table, views
INSERT Table, views
REFERENCE Table
EXECUTE Stored procedure
To grant or revoke object permissions, either SQL Enterprise Manager is used or
GRANT and REVOKE statements are used.
Statement permissions
These are not object-specific .
They can be granted only by the SA or the DBO.
These permissions apply to the following statements:
a) CREATE DATABASE (can be granted only by the SA and only to users of the
master database.)
b) CREATE DEFAULT
c) CREATE RULE
d) CREATE PROCEDURE
e) CREATE TABLE
f) CREATE VIEW
g) DUMP statements
Being granted permission to use a certain statement in one database has no effect in
other databases i.e. each database has its own independent permission system.
To grant or revoke statement permissions, either SQL Enterprise Manager is used or
GRANT and REVOKE statements are used.
SQL SERVER 6.5
Chapter-12/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
GRANT and REVOKE statements
GRANT statement
Assigns permissions to users.
Syntax:
Statement permissions:
GRANT { ALL | statement_list}
TO { PUBLIC | name_list}
Object permissions:
GRANT { ALL | permission_list}
ON { table_name [(col_lit)] | view_name [(ciol_list)] | stored_proc }
TO { PUBLIC | name_list }
EXAMPLE
Statement permission
Example 1
GRANT CREATE DATABASE,CREATE TABLE
TO mary, john
OUTPUT:
Permissions for creating database and table is granted to multiple users.
Object permission
Example 2
GRANT SELECT ON authors
TO PUBLIC
OUTPUT:
Grants SELECT permission to the group PUBLIC on authors table.
SQL SERVER 6.5
Chapter-12/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
REVOKE statement
Revokes permissions from users.
Syntax:
Statement permissions:
REVOKE { ALL | statement_list}
FROM { PUBLIC | name_list}
Object permissions:
REVOKE { ALL | permission_list}
ON { table_name [(col_lit)] | view_name [(ciol_list)] | stored_proc }
FROM { PUBLIC | name_list }
EXAMPLE
Statement permission
Example 1
REVOKE CREATE DATABASE,CREATE TABLE
FROM mary, john
OUTPUT:
Permissions for creating database and table is revoked from the users mary and john.
Object permission
Example 2
GRANT SELECT ON authors
FROM PUBLIC
OUTPUT:
Revokes SELECT permission from the group PUBLIC on authors table.
SQL SERVER 6.5
Chapter-12/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Permissions of SA
There are no restrictions on what SA can do within SQL Server.
Permissions of Database Owners
Has full permission to do anything inside his database.
DBO must grant permissions to other users explicitly.
Permissions on certain statements are automatically granted to the DBO and cannot
be transferred to other users like DROP DATABASE, GRANT and REVOKE,
DBCC.
On other statements DBO can grant permission to other users like CREATE
DEFAULT, CREATE RULE, CREATE TABLE, CREATE VIEW, CREATE PROC,
DUMP statements.
Permissions of database object owners
A user who creates a database object is its owner and is automatically granted all
object permissions on it.
Other users, even the DBO are automatically denied all permissions on that object
unless explicitly allowed by the database object owner.
On certain statements permission cannot be transferred to other users:
ALTER TABLE
CREATE and DROP INDEX
CREATE and DROP TRIGGER
DROP and TRUNCATE TABLE
UPDATE STATISTICS
SQL SERVER 6.5
Chapter-12/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
BACKING UP AND RESTORING
Backing up a database
Backing up is creating a copy of the database or transaction log on a dump device which
is accomplished by either using Enterprise Manager or the DUMP statement.
Backing up a database backs up both the database as well as transaction log.
In large databases, the data portion and the transaction log are usually stored on different
devices, so that transaction logs can be backed up separately. Dumping only the
transaction log uses less storage and takes less time than dumping the database, which
backs up both the transaction log and the database.
Regular backups of all the databases should be maintained to ensure smooth recovery in
case of database or media failure.
Immediate and scheduled backups
SQL Enterprise Manager (Backup and restore ...option) allows to set and maintain a
schedule of automatic backups. Manual backup can also be taken any time.
Backup can be performed immediately in two ways:
As a foreground task that occupies SQL Enterprise Manager until the backup
completes.
As a background task that allows SQL Enterprise Manager to remain available to you.
Scheduled backups can be set to occur one time or on a recurring basis. Recurring
backups can be set to occur hourly, daily, weekly or monthly.
Backup task options
Scheduling a backup creates a backup task. While scheduling the backups task option can
be set that will:
Send an e-mail to an operator when the backup fails or succeed.
Write an entry in Windows NT Application log when the backup fails or succeed.
Specify the number of retry attempts when a backup fails and also the delay between
each retry.
SQL SERVER 6.5
Chapter-12/12
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Monitoring, modifying or canceling a scheduled backup
By using the option Backup and restore of the Enterprise Manager the scheduled
backups cannot be monitored, modified or canceled.
The Task Scheduling window is used for the purpose. But, this window displays all the
tasks defined on the server; not just the backup tasks.
For a selected task, the task history can be viewed which provides information about the
last run date of the task, time and duration of last run, status of that run, whether an e-
mail was sent.
A scheduled backup task can be edited. The task name, the database the task is run
against, the command that is run, task schedule and task options can be changed.
A scheduled backup task can be suspended without canceling the task and it can be re-
enabled.
Restoring a database
Restoring is to load a database from the backup of that database and of its transaction
log.
If the device that a database reside on fails and the database is damaged, the database can
be restored by reloading the most recent database backup.
A database backup can be reloaded over the old database, if it is found that there is some
corrupt data on the database.
A load overwrites the information in the database with the backed up information.
Restore is accomplished by using Enterprise Manager or the LOAD statement.
When a database is restored from a backup, the database must not be in use.
Loading a transaction log results in reexecution of the changes it contains and in rolling
back any transactions that were uncommitted when the transaction log was backed up.
Automatic recovery
Automatic recovery occurs every time SQL Server is restarted. This protects the database
in the event of system failures.
When SQL Server is restarted recovery is performed automatically on each database.
This does the following:
SQL SERVER 6.5
Chapter-12/13
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Rolls back uncommitted transactions- those transactions that were ongoing when the
SQL Server was shut down.
Checks the transactions that had been committed between the last checkpoint and the
failure, and rolls them forward.
In each database, the automatic recovery looks at the transaction log. If the log has
committed transactions not yet written to the database, it performs those transactions
again. This is called rolling forward.
Importing and exporting data
Two SQL Server utilities can be used to transfer data. The Bulk Copy Program which has
already been discussed and the other is the transfer management interface in SQL
Enterprise Manager (Database/ Object Transfer .... option).
The transfer management interface is used to transfer all or some objects from one
database to another. In addition to transferring objects from one SQL Server to another,
transferring objects from following server applications to SQL Server 6.5 is supported:
SQL Server 4.x
SQL Server 6.0
Sybase system 10
Transferring objects from server other than SQL Server 6.5 requires that a script be run
first.
Scripts for other applications are available on SQL Server 6.5 CD.
SQL Server 4.x - SQLOLE42.SQL
SQL Server 6.0 - SQLOLE65.SQL
Sybase system 10 - SYSSYS.SQL
SQL SERVER 6.5
Chapter-12/14
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DATABASES ON REMOVABLE MEDIA
Using Removable Media for databases

This feature enables databases to be placed on removable media, such as CD-ROMs,
magneto opticals, floppy disks, etc.

It is possible to read and write from databases on floppy disks, optical drives but CD-
ROM based database is truly read-only, which aid in securing data integrity.

Creating a removable database

The stored procedure sp_create_removable is used to create the databases on the
removable media.
The removable database has to be created in such a way that three devices are use;
one for system catalog tables, one for the transaction log, and one or more for the data
tables.

Syntax:
sp_create_removable database_name, syslogical, sysphysical, syssize,
loglogical, logphysical, logsize,
datalogical1, dataphysical1, datasize1
[..., datalogical16,dataphysical16, datasize16]
sp_create_removable parameters

Parameter Description

database_name Name of the database that will be created for use on removable media.
syslogical Logical name of the device that will contain he system catalog tables
and the transaction log
sysphysical Physical name including a fully qualified path of the device holding the
system catalog and transaction log
syssize size in MB of the above device
loglogical Logical name of the device that will contain the transaction log
logphysical Physical name including a fully qualified path of the device holding the
transaction log
logsize size in MB of the above device
datalogical Logical name of the device that will contain data tables
dataphysical Physical name including a fully qualified path of the device holding the
data tables
datasize size in MB of the above device

SQL SERVER 6.5
Chapter-12/15
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


EXAMPLE

sp_create_removable inventory ,invsys, C:\MSSQL\DATA\invsys.dat, 2,

invlog, C:\MSSQL\DATA\invlog.dat, 4,

invdata , C:\MSSQL\DATA\invdata.dat, 10

OUTPUT:

The database called inventory is created as a removable database.
It creates a 2MB system catalog database device, 4MB Transaction Log database device and 10 MB of
data device.



Using the removable database

After the database development is complete, the system stored procedure
sp_certify_removable is used to prepare the database for distribution on removable
media.

Syntax:

sp_certify_removable database_name [, AUTO]

database_name - the name of the database to be certified.

AUTO - If specified, any problems encountered are corrected automatically.

EXAMPLE
sp_certify_removable inventory, AUTO

OUTPUT:
Inventory database is certified and brought offline.


All the devices that have been created for use in the removable database are taken offline
by this system stored procedure.
SQL SERVER 6.5
Chapter-12/16
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Installing the Removable database


Use sp_dbinstall to install a removable media database.

The removable media installation process copies a database device containing the system
catalog tables and transaction log onto the servers disk.

This allows to create or administer users, permissions, views and stored procedures for
the database, while keeping the data on read-only removable media.

Databases are installed as offline (unavailable). The newly installed database is placed
online by using sp_dboption.
To install a database and place it online
Place the removable media into the drive.
Run sp_dbinstall system stored procedure:

Syntax:

sp_dbinstall database_name,device_name, physical_device, size, device_type [,
location]

Options Description
database_name Name of the database to be installed.
device_name Name of the database device to be installed.
physical_device path information for device on removable media
size size of the device being created
device_type type of the device being created on target SQL Server [SYSTEM /
DATA]
location Location to use on the local drive for the device being installed.
EXAMPLE
sp_dbinstall inventory, invsys, e:\invsys.dat, 2, SYSTEM,
c:\MSQL\DATA\invsys.dat
sp_dbinstall is run again to install the data device.

SQL SERVER 6.5
Chapter-12/17
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LAB EXERCISES
1. Create a database in which create the tables designed for the library system given id
session 1 with all the required constraints, rules, defaults etc.
SQL SERVER 6.5
Chapter-12/18
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
SQL Server security can be implemented in three ways:
Standard security
Integrated security
Mixed security
When SQL Server is installed, two login IDs are automatically created;
sa and probe.
When a server is configured to participate in replication, one or both these IDs are
automatically created: repl_publisher and rep_subscriber.
A user is allowed to access a database by assigning a database username to the users
login ID.
The username can be :
One created specifically for that login ID
Someone elses username in the database (alias)
A group is a collection of users and is a convenient way to provide common permissions
to those users.
Within each database SQL Server recognizes two types of owners:
Database owners
Database object owners
SQL Server has two categories of permissions:
Object permission
Statement permission
Backing up is creating a copy of the database or transaction log on a dump device .
Restoring is to load a database from the backup of that database and of its transaction
log.
Two SQL Server utilities can be used to transfer data.
Bulk Copy Program
Database/ Object Transfer .... option.
Using removable media for databases enables databases to be placed on removable
media, such as CD-ROMs, magneto opticals, floppy disks, etc.
SQL SERVER 6.5
Chapter-13/1
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
OBJECTIVE
Understanding the DB-Library Interface
SCOPE
Introduction to DB-Library
Required components for DB-Library
Communication with SQL Server
DB-LIB for C and Net-Library interaction
Net-Library Architecture
Programming with DB-Library for C
SQL SERVER 6.5
Chapter-13/2
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
INTRODUCTION TO DB-LIBRARY
Microsoft SQL Server is a powerful SQL database server.
It allows clients running the Windows NT, Windows 95, Windows or MS-DOS operating
systems to access its services.
When developing applications to work with SQL Server, the approach which enters
queries from the ISQL or ISQL/w utilities doesnt prove very useful.
Through client application, which is responsible for information formatting, presentation
and other user interaction, the power of SQL Server is presented to the user.
Developing applications for SQL Server can take many forms. DB-Library is one of the
most common methods of working with SQL Server.
Understanding the DB-Library interface
Developers can write applications for SQL Server by programming with DB-Library for
C.
DB-Library for C is the C language version of the communication library for SQL
Server.
DB-Library or DB-LIB for C is an application programming interface consisting of C
functions and macros that allow to work directly with SQL Server.
The API provides different tools that are needed for sending queries to and receiving
information from SQL Server.
DB-LIB offers a set of functions which are responsible for:
Opening connections
Formatting queries
Sending query batches to the server and retrieving the resulting data.
Using scrollable cursors
Bulk-copying data
Controlling Two-Phase Commit operations
Executing stored procedures or remote stored procedures
SQL SERVER 6.5
Chapter-13/3
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.


Required components for DB-LIB

To use DB-LIB, some files need to be included with the project.

WINDOWS.H
SQLDB.H
SQLFRONT.H
NTWDBLIB.DLL ( A Dynamic Link Library which stores the DB-LIB functions.
The DLL is included in the same directory as your application )
NTWDLIB.LIB ( An import library containing function definitions that your
application use. This file need to be created )
To create DB-Library applications for Windows NT, following software is needed.
Microsoft Windows NT Workstation / Server version 3.5 or later .
Microsoft Visual C++ version 2.0 or later, or 100% compatible compiler and linker.
Determining the DB-LIB for C version
For Windows and Windows NT, run the SQL Client Configuration Utility to
determine which version of DB-LIB is installed on your computer.
This utility searches the path for the appropriate DLL to load.
Run the utility from the same working directory as your application.
Communicating with SQL Server
Two structures are used to establish connection to SQL Server.
a) DBPROCESS
b) LOGINREC
DB-LIB functions communicate with SQL Server through the DBPROCESS
structure.
dbopen function allocates and initialises a DBPROCESS when it logs on to the SQL
Server.
DBPROCESS serves as the connection between the application and SQL Server.
An application can have more than one DBPROCESS if, for instance, it needs to
update a database while still processing the results of a previous query.
Each DBPROCESS is completely independent of any other.
Another structure, LOGINREC, allocated by dblogin, is the login record that contains
information that dbopen function uses to log on to SQL Server. It contains typical
login information, such as the user name and the password.
In Windows NT, each connection is a separate execution thread that is spawned when
the connection to SQL Server is established with dbopen and terminated when the
connection is closed using dbclose.
SQL SERVER 6.5
Chapter-13/4
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DB-LIB for C and Net-Library interaction
When a call is made to open a connection to SQL Server (dbopen), DB-LIB
determines which client-side Net-Library should be loaded to communicate with SQL
Server.
Net Libraries are implemented as Dynamic Link Libraries, and multiple Net-Libraries
can be loaded simultaneously.
Net Library Architecture
Microsoft SQL Server Net Library architecture for client/Server applications is based
on the Net-Library concept that abstracts the client and server applications from the
underlying network protocols used.
Tabular Data Stream (TDS) is the data stream protocol used by Microsoft SQL Server
to transfer requests and responses between the client and the server.
TDS is a logical data stream protocol and must be supported by a physical network
interprocess communication mechanism.
The Net-Library architecture provides a method of sending TDS across a physical
network connection, and it provides a transparent interface to DB-Library for C.
Programming with DB-Library for C
Programming with DB-Library involves following steps:
Connect to the SQL Server.
Put Transact-SQL statements into buffer and send them to SQL Server.
Process the results returned from SQL Server, one statement at a time and one row at
a time.
Results can be put in the program variables, where applications can manipulate them.
Handle DB-Library errors and SQL Server messages.
Disconnect from SQL Server.
EXAMPLE
#define DBNTWIN32
#inlude <stdio.h>
#include <windows.h>
#include <sqlfront.h>
#include <sqldb.h>
/* Declarations for the message and error handlers. */
int err_handler(PDBPROCESS, INT, INT, INT, LPCSTR, LPCSTR);
int msg_handler (PDBPROCESS, DBINT, INT, INT, LPCSTR, LPCSTR, LPCSTR,
DBUSMALLINT);
SQL SERVER 6.5
Chapter-13/5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
main()
{
PDBPROCESS dbproc; /* connection with SQL Server */
PLOGINREC login; /* The login information */
DBCHAR fname[100];
DBCHAR lname[100];
DBCHAR address[100];
/* Installing user-supplied error and message handling functions */
dberrhandle (err_handler);
dbmsghandle (msg_handler);
/* Initialize DB-Library */
dbinit();
/* Get a LOGINREC */
login = dblogin();
DBSETLUSER(login, my_login);
DBSETLPWD(login, my_password);
DBSETLAPP(login, example);
/* Get a DBPROCESS structure for communication with SQL Server */
dbproc = dbopen(login, my_server);
/* Retrieves some columns from the member table in the library
database. First put the command into the command buffer */
dbcmd(dbproc, select first_name, last_name, address FROM
library..member);
dbcmd(dbproc, WHERE first_name = ARCHIE);
/* Send the command to SQL Server and start execution */
dbsqlexec(dbproc);
/* Process the results */
if (dbresults(dbproc) == SUCCEED)
{
/* Bind column to program variables */
dbbind(dbproc, 1, NTBSTRINGBIND, 0, fname);
dbbind(dbproc, 2, NTBSTRINGBIND, 0, lname);
dbbind(dbproc, 3, NTBSTRINGBIND, 0, address);
/*Retrieving and printing the result rows */
while(dbnextrow(dbproc) != NO_MORE_ROWS)
{
printf(%s %s %s\n, fname, lname, address);
}
}
/* Closing the connection */
dbexit();
return(0);
}
SQL SERVER 6.5
Chapter-13/6
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
int err_handler(PDBPROCESS dbproc, INT severity, INT dberr, INT oserr,
LPCSTR dberrstr, LPCSTR oserrstr)
{
printf(DB-Library error %i: %s\n, dberr, dberrstr);
if(oserr != DBNOERR)
{
printf(Operating system error %i: %s \n, oserr, oserrstr);
}
return(INT_CANCEL);}
int msg_handler(PDBPROCESS dbproc, DBINT msgno, INT msgstate, INT
severity, LPCSTR msgtext, LPCSTR server, LPCSTR procedure, DBUSMALLINT
line)
{
printf(SQL Server Message %1d: %s\n, msgno, msgtext);
return(0);
}
Header files
All source files that contain calls to DB-LIB functions require two header files:
(a) SQLDB.H
(b) SQLFRONT.H
Before including SQLFRONT.H and SQLDB.H, the operating system must be
defined with #define as follows:
#define DBNTWIN32
WINDOWS.H file must be included for Windows, Win 95 and Win NT Operating
system, before including SQLFRONT.H and SQLDB.H.

SQLFRONT.H must be included before SQLDB.H.
SQLFRONT.H file
It defines symbolic constants, such as function return values and exit values
STDEXIT and ERREXIT.
Exit values can be used as the parameter for the C standard Library function exit.
The file also includes type definitions for datatypes that can be used in the program
variable declarations.
SQL SERVER 6.5
Chapter-13/7
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SQLDB.H file
Contains additional type definitions and DB-Library function prototypes.
They should not be accessed directly by the program.
dberrhandle and dbmsghandle
dberrhandle installs a user-supplied error-handling function.
The function is called automatically whenever the application encounters a DB-
Library error.
dbmsghandle installs a message handling function.
The function is called in response to informational or error messages returned from
SQL Server.
dblogin
Supplies a LOGINREC structure, which DB-LIB uses to log into the SQL Server.
Two functions set entries in LOGINREC.
(a) DBSETLPWD Sets the password that DB-LIB uses when logging in.
(b) DBSETLAPP Sets the name of the application, which appears in SQL Server
sysprocess table.
dbopen
Opens a connection between the application and SQL Server.
It uses LOGINREC supplied by dblogin to log into the server.
Runs a DBPROCESS structure which serves as a conduit for information between the
application and the server.
After this function has been called, application is connected with SQL Server and can
send Transact-SQL statements to SQL Server and process the results.
Simultaneous transactions must have a distinct DBPROCESS.
Serial transactions can use the same DBPROCESS.
dbcmd
It fills the command buffer with Transact-SQL statements.
The statements then can be sent to SQL Server.
Each call, after the first, to dbcmd, adds the supplied text to the end of any text
already in the buffer.
It allows an application to send multiple statements to SQL Server and process each
statements set of results separately.
SQL SERVER 6.5
Chapter-13/8
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
dbsqlexec
Executes the command buffer.
Sends the command in the buffer to SQL Server.
Causes DB-Library to wait until SQL Server has completed execution of the query.
dbresults
Gets the results of current Transact-SQL statement ready for processing.
After dbresults returns SUCCEED, column data of the current results set is available.
dbbind
Binds result columns to program variables.
In the example, the first call to dbbind binds the first result column to the fname
variable.
When the program reads a result row by calling dbnextrow, the contents of the first
column in the result row are placed.
The datatype of the binding is NTBSTRINGBIND, one of the several binding types
available for character data.
The second call binds the second result column to the lname variable.
dbnextrow
Reads a row and places the results in the program variables specified by the earlier
dbbind calls.
Each successive call to dbnextrow reads another result row until the last row has
been read and NO_MORE_ROWS is returned.
Processing of the results must take place inside the dbnextrow loop.
This is because each call to dbnextrow overwrites the previous values in the bound
program variables.
dbexit
Closes all SQL Server connections and frees all DBPROCESS structures created
because of the application.
It is usually the last DB-Library function in the program.
SQL SERVER 6.5
Chapter-13/9
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
DB-Library Datatypes
DB-Library defines datatype tokens for SQL Server data.

These datatype constants begin with SQL (for example, SQLINT4, SQLCHAR).

DB-LIB also provides type definitions for use in program variable declarations.

These type definitions begin with the prefix DB (for example, DBINT, DBCHAR).

By using them, it is ensured that program variables will be compatible with SQL
Server datatypes.

The dbconvert function provides a way to convert data from one SQL Server
datatype to another.
Advantages Vs disadvantages of using DB Library
Disadvantages
DB-LIB is an SQL Server-specific interface layer.
Out of the other methods of working with SQL Server (ODBC and SQL OLE), this
is the least portable between back-end database servers.

Advantages

Out of the other methods of working with SQL Server (ODBC and OLE), this is a
faster way to access the information, because development is directly in the host
language.
The other options, ODBC and SQL OLE offer similar services but impose an
abstraction layer between the application and the calls to SQL Server.
There is complete control over the error trapping associated with the transactions.
SQL SERVER 6.5
Chapter-13/10
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
LAB EXERCISE
1. Write a DB-LIB application which should store the publisher details in the publishers
table.
2. Try the example given in the book after creating the relevant table.
SQL SERVER 6.5
Chapter-13/11
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
SUMMARY
DB-Library or DB-LIB for C is an application programming interface consisting of C
functions and macros that allow to work directly with SQL Server.
Two structures are used to establish connection to SQL Server.
a) DBPROCESS
b) LOGINREC
To use DB-LIB, some files need to be included with the project.

WINDOWS.H
SQLDB.H
SQLFRONT.H
NTWDBLIB.DLL
NTWDLIB.LIB
dblogin supplies a LOGINREC structure, which DB-LIB uses to log into the SQL
Server.
dbopen opens a connection between the application and SQL Server.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
APPENDIX A
THE pubs SAMPLE DATABASE
Other details about the tables can be found out by querying the tables and using system
stored procedures.
au_id (FK)
title_id (FK)
au_ord
royaltyper
title_id
title
type
pub_id (FK)
price
advance
royalty
ytd_sales
notes
pubdate
title_id
lorange
hirange
royalty
titleauthor titles roysched
au_id
au_lname
au_fname
phone
address
city
state
zip
contract
authors
pub_id
pub_name
city
state
country
publishers
pub_id (FK)
logo
pr_info
pub_info
dicounttype
stor_id (FK)
lowqty
highqty
discount
discounts
emp_id
fname
minit
lname
job_id (FK)
job_lvl
pub_id (FK)
hire_date
employee
stor_id (FK)
ord_num
ord_date (FK)
qty
payterms
title_id (FK)
sales
stor_id
stor_name
stor_address
city
state
zip
stores
job_id
job_desc
min_lvl
max_lvl
jobs
Indicates a primary key
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
APPENDIX B
Quick reference for ISQL
isql /U login_id [/e] [/E] [/p] [/n] [/d dbname] [/q query] [/Q query]
[/c cmdend] [/h headers] [/w columnwidth] [/s colseparator]
[/t timeout] [/m errorlevel] [/L] [/?] [r { 0|1}]
[/H wksta_name] [/P password]
[/S servername] [/I inputfile] [/o outputfile] [/a packet_size]
Command line switches Function
/U login_id Specifies a login ID.
/e Echoes input. The editor is defined in the EDITOR
environment variable. Default is edlin.
/E Uses a trusted connection instead of using password.
/p Prints performance statistics.
/n Removes numbering and prompt symbol (>) from input
lines.
/d dbname Issues a USE dbname statement when isql starts.
/q query Executes a query when isql starts. Query statement
should not include go. %variables can be used if a
query is issued from a batch file. Use double quotation
marks around the query and single quotation marks if
anything is embedded in the query.
/Q query Same as above but executes a query and immediately
exits isql.
/c cmdend The command terminator. By default, commands are
terminated and sent to SQL Server by entering go.
/h headers The number of rows to print between column headings.
The default is to print headings only once for each set of
query results.
/w columnwidth Allows to set the screen width for output. Default is 80
characters.
/s colseparator Blank by default. To use characters that have special
meaning to the operating system precede them with a
backslash(\).
/t timeout Number of seconds before a command times out. If no
timeout is specified, a command runs indefinitely;
however, the default timeout for logging in to isql is 60
seconds.
/m errorlevel Customizes display of error messages. The message
number, state, and error level are displayed for errors of
the specified severity level or higher.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Command Line Switches Function
/L Lists locally configured servers and the names of the
servers broadcasting on the network.
[r {0|1}] Redirects message output to stderr. If a parameter is
not specified or 0 is specified, error-level message
severity 17 or higher is redirected. If 1, all are
redirected.
/? Displays the syntax summary of isql switches.
/P password Specifies the password. If /P option is not used, it
prompts for the password.
/S servername Specifies the name of the SQL server to connect to.
/i inputfile Specifies the name of the file that contains a batch of
SQL Statements or stored procedures. The symbol <
can be used instead of /i.
/o outputfile Specifies the name of the file that receives output from
the isql. The symbol > can be used instead of /o. Two
greater than symbols can be used for appending the file
rather than replace it.
Query execution
Interactive mode:
Give the isql command with any of the options at the OS prompt. OS file can be
read into the command buffer with :r filename. Do not include the command terminator
in the file; enter the terminator interactively once editing is finished.
Batch mode:
File containing a query can be read for execution by isql by typing a similar
command as given below.
isql /U sa /I query1.qry
File must include a command terminator.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
APPENDIX C
Quick reference for transferring data with bcp utility
bcp [[database_name.] owner.] table_name { in | out } datafile
[/m maxerrors] [/f formatfile] [/e errfile]
[/F first row] [/L lastrow] [/b batchsize]
[/n] [/c] [/E]
[/t field_term] [/r row_term]
[/i inputfile] [/o outputfile]
/U login_id [/P password] [/S servername] [/v]
Switches Description
database_name Specifies the database name.
owner Specifies the owners name. If you own the table
the name is optional. If no owner is specified and
you do not own the table of that name, the program
will not execute.
table_name Specifies which database table to be copied.
in | out Specifies the direction of copy. in copies from a file
into the database table. out option copies to a file
from the database table.
datafile Full path of an OS file when copying to or from the
hard-disk file or single diskette.
/m maxerrors Maximum number of errors that can occur before
the copy is canceled. Each row that can not be
rebuilt by bcp is thrown out and counted as one
error. Default is 10.
/f formatfile Full path of a file with stored responses from a
previous use of bcp on the same table (creation of
format file is optional). This option is used when a
format file has already been created that you want to
copy in or out. After you answer format questions,
bcp asks whether you want to save your answers in
a format file. The default filename is BCP.FMT.
The bcp utility can refer to a format file when you
copy data, so that you do not have to duplicate your
previous format responses interactively.
SQL SERVER 6.5
Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.
Switches Description
/e errfile Full path of an error file where bcp stores any rows
that it was unable to transfer from the file to the
database. If the option is not used, no error file is
created.
/F firstrow Number of first rows to copy.
/L lastrow Number of last rows to copy.
/b batchsize Number of rows per batch of data copied. (By
default all the rows are copied in one batch)
/n Performs the copy information using the native
datatypes as the default. This option does not
prompt for each field.
/c Performs a copy operation with a character datatype
as the default. Does not prompt for each field.
/E Used when identity values are present within the
table to be imported.
When data is imported an identity column is
temporarily assigned a value of 0. As the rows are
inserted into the table, SQL Server assigns unique
values based on the seed and increment values
specified during table creation.
/t field_term Specifies the default field terminator.
/r row_term Specifies the default row terminator.
/i inputfile Name of the file that redirects input to bcp.
/o outputfile Name of the file that receives output redirected
from bcp.
/U login_id Name of the login_id.
/P password Specifies the password.
/S servername Specifies which SQL server to connect to.
/v Reports the current DB-Library version number.

You might also like