sql server guide

161
Visit: www.gcreddy.com for QTP Information SQL Server Guide For Software Testers Visit: www.gcreddy.net for Testing Information 1

Upload: adchy7

Post on 19-Jul-2016

13 views

Category:

Documents


1 download

DESCRIPTION

DBMS Design

TRANSCRIPT

Page 1: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

SQL Server GuideFor Software Testers

Visit: www.gcreddy.net for Testing Information 1

Page 2: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Index

Introduction 2

Structured Query Language (SQL) 10

Databases 11

Tables 22

Constraints 32

Joins 42

Built-in Functions 47

Sub-Queries 55

Views 61

Indexes 64

Normalization 67

T-SQL 70

Stored procedures 74

Triggers 76

User Defined Functions (UDF) 81

Locks 85

Transactions 89

SQL Server Security 93

Back-up and recoveries 97

Advanced features (SQL 2005) 101

Case Study 126

Visit: www.gcreddy.net for Testing Information 2

Page 3: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

INTRODUCTION

SQL Server is a Client/Server Relational Database Management System (RDBMS) that uses Transact-SQL to send request between a client and SQL Server.

Client/Server Architecture:

SQL Server is designed to be a client/server system. Client/server systems are constructed so that the database can reside on a central computer, know as a Server, and be shared among several users. When users want to access the data in SQL Server, they run an application on their local computer, known as a Client that connects over a network to the server running SQL Server.

SQL Server can work with thousands of client application simultaneously. The server has features to prevent the logical problems that occur if a user tries to read or modify data currently used by others.

While SQL Server is designed to work as a sever in a Client/Server network, it is also capable of working as a stand-alone database directly on the client. The scalability and easy-to-use features of SQL Server allow it to work efficiently on a client without consuming too many resources.

To begin with, a brief overview of the relational database model is provided as the SQL Server database is based on this model.

Overview of RDBMS:

Data:- Information that is been stored and used in the computer system is called as data.

Database:- Collection of meaningful Information stored in an organized manner.

Visit: www.gcreddy.net for Testing Information 3

Page 4: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

DBMS:- It is a collection of interrelated data and a set of programs to access and modify the data.

RDBMS:- It is also DBMS but the relation will be stored into the database.

Differences Between DBMS And RDBMS:-

DBMS RDBMSIn DBMS data is stored in the form of a file and is shown to the user in the form of a two dimensional table.

In the case of RDBMS data is strictly to be stored in the form of table and also shown in the form of table.

In DBMS the relation ship established among the tables will not be stored into the database.

In RDBMS the relationship established will be stored into the database as one of the database objects.

Relationships among Data:A relationship is defined as “an association among entities”. The three

different types of relationships recognized among various data stored in the database are:

One-to-one

In a one-to-one relationship, a row in table A can have no more than one matching row in table B, and vice versa.

One-to-many

A one-to-many relationship is the most common type of relationship. In this type of relationship, a row in table A can have many matching rows in table B, but a row in table B can have only one matching row in table A.

Many-to-many

In a many-to-many relationship, a row in table A can have many matching rows in table B, and vice versa. You create such a relationship by defining a third table, called a junction table.

Data Model:- It is nothing but the structure in which the data is stored in the database.

There are two important data models existing. They are: 1.Object-based data model 2. Record-based data model.

Object – Based Data Model:- It is a collection of conceptual tool for describing the data, data relationships and data constraints.

Record – Based Data Model:- It describes the data structures and access techniques of DBMS. Object –based data model is the concept and Record-base data model is the actual representation of the data in the database.

Of all the different Object-based data models available the most popular model is E/R Diagram and from the various record-based data models the popular and effective model is the Relational model.

Visit: www.gcreddy.net for Testing Information 4

Page 5: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

MS SQL SERVER 2000

SQL SERVER is a Microsoft back-office product that is deployed on windows environment. SQL SERVER is a SQL based client/server, Relational Database Management System. SQL stands for Structured Query Language, which is used in writing queries to retrieve data from databases. SQL Server stores data at a central location known as Server, and delivers it on demand to other locations known as Clients. The server is responsible for manage the database and to allocate available server resources such as disk operations, and memory for multiple requests. The client is responsible for presenting data and business logic to the end-user. Client programming interfaces provide the means for applications to run on separate client computers and communicate to the server over network.

Some of the advantages of SQL client are: Supports multiple hardware platforms Supports multiple software platforms

Some advantages of SQL server are: Reliable Fault tolerant Centralized control Concurrent Sophisticated locking

SQL SERVER is SCALABLE, RELIABLE, INTEROPERABLE, HIGH PERFORMANCE, and CLIENT / SERVER RDBMS.

Scalability: The concept of scalability is supporting parallel processing with more than one server. The necessity for more than one server is the situation where in server is held up with one client request and all the other clients are in waiting for that server relived from that client process, then the client internally requests the other server to take over the activities on the network. The other situation where in we need multiple servers is – if in case the database is extended across the multiple servers and a client requests for a database object which might be on some other servers, then the server to which the request has been passed on searches for that database object and retrieves the data from other servers also.

Reliability: It is recovering the data even in the case of system crash with a minimum loss of data. That is possible by the means that the server will replicate the same data into different memory locations which is called as REPLICATION. Even in the case of loss of data in the primary location also data can get from the secondary locations

Interoperability: It is the ability of SQL SERVER to communicate with other RDBMS like DB2, IMS and ORACLE. This is if the database is already available in other RDBMS that can be getting into SQL SERVER with the help of a concept called IMPORT. Similarly if the database is available is SQL SERVER can be taken into other RDBMS with the help of the concept called EXPORT.

High Performance: Even in the case of bulk databases the SQL SERVER performs inserts, updates from the database with response time to the order of milliseconds. A database is a collection of tables and objects like views, indexes, stored procedures and triggers.

Visit: www.gcreddy.net for Testing Information 5

Page 6: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

EDITIONS OF SQL SERVER

Microsoft SQL Server 2000 comes with different editions. The following are the editions that are available.

SQL Server 2000 Enterprise Edition

Used as a production database server. Supports all features available in SQL Server 2000, and scales to the performance levels required to support the largest Web sites and enterprise online transaction processing (OLTP) and data warehousing systems.

SQL Server 2000 Standard Edition

Used as a database server for a small workgroup or department.

SQL Server 2000 Personal Edition

Used by mobile users who spend some of their time disconnected from the network but run applications that require SQL Server data storage. Also used when running a stand-alone application that requires local SQL Server data storage on a client computer.

SQL Server 2000 Developer Edition

Used by programmers developing applications that use SQL Server 2000 as their data store. Although the Developer Edition supports all the features of the Enterprise Edition that allow developers to write and test applications that can use the features, the Developer Edition is licensed for use only as a development and test system, not a production server.

SQL Server 2000 Windows CE Edition

Microsoft® SQL Server 2000™ Windows® CE Edition (SQL Server CE) is used as the data store on Windows CE devices. Capable of replicating data with any edition of SQL Server 2000 to keep Windows CE data synchronized with the primary database.

Out of all the editions, Enterprise Edition is the most featured one. Enterprise Edition allows 32 processors to be added to the server machine in

support to Symmetric Multi Processing. Developer Edition allows 4 processors to be added to the server. In general Developer Edition is used at the time of developing the application

and Enterprise Edition is used as the Production Server.

Administrative Tools

Visit: www.gcreddy.net for Testing Information 6

Page 7: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Microsoft® SQL Server™ 2000 includes many graphical and command prompt utilities that allow users, programmers, and administrators to:

Administer and configure SQL Server.

Determine the catalog information in a copy of SQL Server. Design and test queries for retrieving data. Copy, import, export, and transform data. Provide diagnostic information. Start and stop SQL Server.

In addition to these utilities, SQL Server contains several wizards to walk administrators and programmers through the steps needed to perform more complex administrative tasks.

The tools that are supported by SQL Server are

Books Online Client Network Utility

Enterprise Manager

Query Analyzer

Import and Export Data

SQL Profiler

Service Manager

Books online:

This tool can be used as help for SQL Server database. Any information regarding SQL Server can be found with this tool. It consists of syntaxes and examples for all topics of SQL Server database.

Client Network Utility:

This tool is used to configure a client machine with a server.

The Client Network utility is used to manage the client Net-Libraries and define server alias names. It can also be used to set the default options used by DB-Library applications.

Most users will never need to use the Client Network utility. To connect to Microsoft® SQL Server™ 2000, users can specify only the network name of the server on which SQL Server is running, and optionally the name of the instance of SQL Server.

In some cases, an instance of SQL Server may be configured to listen on alternate network addresses. If this is done, client applications connecting to that

Visit: www.gcreddy.net for Testing Information 7

Page 8: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

instance must explicitly specify the alternate address. While applications could specify the alternate addresses on each connection request, it is easier to use the Client Network utility to set up an alias specifying the alternate addresses. Applications can then specify the alias name in place of the server network name in their connection requests.

Enterpriser Manager:

SQL Server Enterprise Manager is the primary administrative tool for Microsoft® SQL Server™ 2000 and provides a Microsoft Management Console (MMC)–compliant user interface that allows users to:

Define groups of servers running SQL Server.

Register individual servers in a group. Configure all SQL Server options for each registered server. Create and administer all SQL Server databases, objects, logins, users, and

permissions in each registered server. Define and execute all SQL Server administrative tasks on each registered

server. Design and test SQL statements, batches, and scripts interactively by invoking

SQL Query Analyzer. Invoke the various wizards defined for SQL Server.

Query Analyzer:

SQL Query Analyzer is a graphical user interface for designing and testing Transact-SQL statements, batches, and scripts interactively. SQL Query Analyzer can be called from SQL Server Enterprise Manager.

SQL Query Analyzer offers:

A Free-form text editor for keying in Transact-SQL statements.

Color-coding of Transact-SQL syntax to improve the readability of complex statements.

Object browser and object search tools for easily finding the objects in a database and the structure of the objects.

Templates that can be used to speed development of the Transact-SQL statements for creating SQL Server objects. Templates are files that include the basic structure of the Transact-SQL statements needed to create objects in a database.

An interactive debugger for analyzing stored procedures. Results presented in either a grid or a free-form text window. Graphical diagram of the show plan information showing the logical steps built

into the execution plan of a Transact-SQL statement.

This allows programmers to determine what specific part of a poorly performing query is using a lot of resources. Programmers can then explore changing the query in ways that minimize the resource usage while still returning the correct data.

Visit: www.gcreddy.net for Testing Information 8

Page 9: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Index Tuning Wizard to analyze a Transact-SQL statement and the tables it references, to see if adding additional indexes will improve the performance of the query.

Import and Export Data

The Import and Export Data item in the Microsoft® SQL Server™ program group starts the Data Transformation Services (DTS) Import/Export Wizard. The wizard walks users through the DTS functions of importing, exporting, validating, and transforming data and objects between heterogeneous OLE DB and ODBC data sources.

SQL Profiler

SQL Profiler is a tool that captures Microsoft® SQL Server™ 2000 events from a server. The events are saved in a trace file that can later be analyzed or used to replay a specific series of steps when trying to diagnose a problem. SQL Profiler is used for activities such as:

Stepping through problem queries to find the cause of the problem.

Finding and diagnosing slow-running queries. Capturing the series of SQL statements that lead to a problem. The saved

trace can then be used to replicate the problem on a test server where the problem can be diagnosed.

Monitoring the performance of SQL Server to tune workloads.

SQL Profiler also supports auditing the actions performed on instances of SQL Server. Audits record security-related actions for later review by a security administrator. SQL Server 2000 auditing meets C2 security certification requirements.

SQL Server Service Manager:

SQL Server Service Manager is used to start, stop, and pause the Microsoft® SQL Server™ 2000 components on the server. These components run as services on Microsoft Windows NT® or Microsoft Windows® 2000 and as separate executable programs on Microsoft Windows 95 and Microsoft Windows 98:

SQL Server Service Manager is a taskbar application and follows the standard behavior of taskbar applications. When minimized, the SQL Server Service

Manager icon ( ) appears in the area of the taskbar clock on the right of the taskbar. To get a menu that includes all the tasks SQL Server Service Manager supports, right-click the taskbar item.

To maximize SQL Server Service Manager, double-click the icon. The SQL Server Service Manager Window appears as follows.

When SQL Server Service Manager is maximized, clicking the close button of the SQL Server Service Manager window does not terminate the application; it only minimizes SQL Server Service Manager to the taskbar. To terminate SQL Server Service

Visit: www.gcreddy.net for Testing Information 9

Page 10: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Manager, right-click the SQL Server Service Manager icon on the taskbar, and then select the File/Exit menu item.

STRUCTURED QUERY LANGUAGE

SQL is a standard that every database should follow. That means all the SQL commands should work in all databases. Based on the type of operations we are performing on the database, SQL is divided into three types. They are:

Data Definition Language (DDL) Data Manipulation Language (DML) Transaction Control Language (TCL)

Data Definition Language:

It is used to create an object (e.g. table), alter the structure of an object and also to delete the object created. All these commands will effects the structure of the database object. The commands contained by this language are:

CREATE - used to create an object ALTER - used to modify an existing object DROP - used to delete the object TRUNCATE - used to delete only the data of an object

Data Manipulation Language:

The DML commands are most frequently used SQL commands. They are used to query and manipulate existing objects like tables. They should affect only the data of an existing structure. The commands existing in this language are:

SELECT - used to query the object data INSERT - used to enter the data into the object UPDATE - used to modify existing objects data DELETE - used to delete the data of an object.

Transaction Control Language:

A transaction is a logical unit of work. All changes made to the database can be referred to as a transaction. Transaction changes can be controlled with the use of this language commands. They are:

COMMIT - used to make the changes permanent ROLLBACK - used to undo the changes

Visit: www.gcreddy.net for Testing Information 10

Page 11: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

DATABASES

A database in Microsoft® SQL Server™ 2000 consists of a collection of tables that contain data and other objects, such as views, indexes, stored procedures, and triggers, defined to support activities performed with the data. The data stored in a database is usually related to a particular subject or process, such as inventory information for a manufacturing warehouse.

SQL Server can support many databases. Each database can store either interrelated or unrelated data from other databases. For example, a server can have one database that stores personnel data and another that stores product-related data. Alternatively, one database can store current customer order data, and another related database can store historical customer orders used for yearly reporting.

Before you create a database, it is important to understand the parts of a database and how to design these parts to ensure that the database performs well after it is implemented.

Database ArchitectureMicrosoft® SQL Server™ 2000 data is stored in databases. The data in a database is organized into the logical components visible to users. A database is also physically implemented as two or more files on disk.

Visit: www.gcreddy.net for Testing Information 11

Page 12: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

When using a database, you work primarily with the logical components such as tables, views, procedures, and users. The physical implementation of files is largely transparent. Typically, only the database administrator needs to work with the physical implementation.

Each instance of SQL Server has four system databases (master, model, tempdb, and msdb) and one or more user databases. Some organizations have only one user database, containing all the data for their organization. Some organizations have different databases for each group in their organization, and sometimes a database used by a single application. For example, an organization could have one database for sales, one for payroll, one for a document management application, and so on. Sometimes an application uses only one database; other applications may access several databases.

It is not necessary to run multiple copies of the SQL Server database engine to allow multiple users to access the databases on a server. An instance of the SQL Server Standard or Enterprise Edition is capable of handling thousands of users working in multiple databases at the same time. Each instance of SQL Server makes all

Visit: www.gcreddy.net for Testing Information 12

Page 13: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

databases in the instance available to all users that connect to the instance, subject to the defined security permissions.

Types of Databases:

SQL Server provides two types of Databases.

System Databases User Defined Databases

System Databases:

Along with the installation of SQL Server FOUR databases will be created automatically called as system databases. They are:

master

The master database records all of the system level information for a SQL Server system. It records all login accounts and all system configuration settings. master is the database that records the existence of all other databases, including the location of the database files. master records the initialization information for SQL Server; always have a recent backup of master available.

model

The model database is used as the template for all databases created on a system. When a CREATE DATABASE statement is issued, the first part of the database is created by copying in the contents of the model database, then the remainder of the new database is filled with empty pages. Because tempdb is created every time SQL Server is started, the model database must always exist on a SQL Server system.

msdb

The msdb database is used by SQL Server Agent for scheduling alerts and jobs, and recording operators.

tempdb

tempdb holds all temporary tables and temporary stored procedures. It also fills any other temporary storage needs such as work tables generated by SQL Server. tempdb is a global resource; the temporary tables and stored procedures for all users connected to the system are stored there. tempdb is re-created every time SQL Server is started so the system starts with a clean copy of the database. Because temporary tables and stored procedures are dropped automatically on disconnect, and no connections are active when the

Visit: www.gcreddy.net for Testing Information 13

Page 14: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

system is shut down, there is never anything in tempdb to be saved from one session of SQL Server to another.

User Defined Databases:

The databases that are created by the users are called as user defined databases. While creating a database the user has to specify a name to the database and the details of data files, which are used to specify the location, where the database data is to be stored.

Files and FilegroupsMicrosoft® SQL Server™ 2000 maps a database using a set of operating-system files. All data and objects in the database, such as tables, stored procedures, triggers, and views, are stored within these operating-system files:

Primary Data File (.mdf)

This file contains the startup information for the database and is used to store data. Every database has one primary data file.

Secondary Data File (.ndf)

These files hold all of the data that does not fit in the primary data file. If the primary file can hold all of the data in the database, databases do not need to have secondary data files. Some databases may be large enough to need multiple secondary data files or to use secondary files on separate disk drives to spread data across multiple disks.

Transaction Log File (.ldf)

These files hold the log information used to recover the database. There must be at least one log file for each database.

Filegroups allow files to be grouped together for administrative and data allocation/placement purposes. For example, three files (Data1.ndf, Data2.ndf, and Data3.ndf) can be created on three disk drives, respectively, and assigned to the filegroup fgroup1. A table can then be created specifically on the filegroup fgroup1. Queries for data from the table will be spread across the three disks, thereby improving performance. Files and filegroups, however, allow you to easily add new files on new disks. Additionally, if your database exceeds the maximum size for a single Microsoft Windows NT® file, you can use secondary data files to allow your database to continue to grow.

Creating a Database:

To create a database determine the name of the database, its owner (the user who creates the database), its size, and the files and filegroups used to store it.

Before creating a database, consider that:

Permission to create a database defaults to members of the sysadmin and dbcreator fixed server roles, although permissions can be granted to other users.

Visit: www.gcreddy.net for Testing Information 14

Page 15: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

The user who creates the database becomes the owner of the database. A maximum of 32,767 databases can be created on a server. The name of the database must follow the rules for identifiers.

A database can be created either by using Enterprise Manager or by using Query Analyzer.

Using Enterprise Manger to Create Database:

To create a database using Enterprise Manager use the following steps:

1. Open the Enterprise from START button as follows:

Start -> Programs -> Microsoft SQL Server -> Enterprise Manager

2. Expand a server group, and then expand a server

3. Right-click Databases, and then click New Database.

4. Enter a name for the new database.

The primary database and transaction log files are created using the database name you specified as the prefix, for example newdb_Data.mdf and newwdb_Log.ldf. The initial sizes of the database and transaction log files are the same as the default sizes specified for the model database. The primary file contains the system tables for the database.

5. To change the default values for the new primary database file, click the Data Files tab. To change the defaults for the new transaction log file, click the Transaction Log tab.

Visit: www.gcreddy.net for Testing Information 15

Page 16: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

6. To change the default values provided in the File name, Location, Initial size (MB), and File group (not applicable for the transaction log) columns, click the appropriate cell to change and enter the new value.

7. To specify how the file should grow, select from these options: To allow the currently selected file to grow as more data space is

needed, select Automatically grow file. To specify that the file should grow by fixed increments, select In

megabytes and specify a value. To specify that the file should grow by a percentage of the current file

size, select By percent and specify a value. 8. To specify the file size limit, select from these options:

To allow the file to grow as much as necessary, select Unrestricted filegrowth.

To specify the maximum size the file should be allowed to grow to, select Restrict filegrowth (MB) and specify a value.

Note:   The maximum database size is determined by the amount of disk space available and the licensing limits determined by the version of Microsoft® SQL Server™ you are using.

Using Query Analyzer:

To use the Query Analyzer tool, use the following steps.

1. Open the tool from the start menu as follows:Start -> Programs -> Microsoft SQL Server -> Query Analyzer

2. Specify the details of server from the drop down button.

Visit: www.gcreddy.net for Testing Information 16

Page 17: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

3. Select the authentication type from one of the option buttons.4. click “OK”.5. To execute any command, type the command in the empty area and press

the “Execute Query (F5)” icon on the tool bar.

We can also use the Enterprise Manger tool to open Query Analyzer. To do this, in the Enterprise Manager, Choose Tools -> SQL Query Analyzer menu item and the above steps as it is.

Creating a Database Using Query Analyzer:

Once the Query Analyzer is opened, in the command window we can write any command that has to be executed.

Syntax:

Note: ‘Logicalfilename’ is used to identity the file for further modifications and ‘os-filename’ refers the original location where the file is stored in the hard disk.

Example:

Visit: www.gcreddy.net for Testing Information 17

CREATE DATABASE databasename[ON](NAME=<logical file name>,FILENAME=<os-filename>,SIZE=<in mb’s>,MAXSIZE=<in mb’s>,FILEGROWTH=<in mb’s>)][LOG ON(NAME=<logical file name>,FILENAME=<os-filename>,SIZE=<in mb’s>,MAXSIZE=<in mb’s>,FILEGROWTH=<in mb’s>)]

CREATE DATABASE empON(NAME=’emp-dat’,FILENAME=’d:\backup\data\emp_dat.mdf’,SIZE=15,MAXSIZE=50,FILEGROWTH=5)LOG ON(NAME=’emp-Log’,FILENAME=’d:\backup\log\emp_log.ldf’,SIZE=10,MAXSIZE=25,FILEGROWTH=5)

Page 18: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

MODIFYING A DATABASE:The changes that can be made to existing database are

The data and log files can be added or removed. The database can be made to expand or shrink File groups can be added and removed from the database. The configuration settings for the database can be changed

The database can be expanded by allocating additional space to the existing database file or by allocating space to a new file. The size of the database must be increased by at least 1mb.

A maximum size should be specified using the MAXSIZE parameter of the ALTER DATABASE statement. This prevents the file from growing until the disk space is exhausted.

Syntax:

Example:

To add a file group:

To attach new files to new file group:

Visit: www.gcreddy.net for Testing Information 18

ALTER DATABASE <database Name>ADD FILE <file specifications>|ADD LOG FILE <file specifications>|REMOVE FILE <file name>|ADD FILEGROUP <file group name>|REMOVE FILEGROUP <file group name>|MODIFY FILE <file specifications>|MODIFY FILEGROUP <file group name>

ALTER DATABASE empADD FILE(NAME= ‘emp1_dat’,FILE NAME=’d:\backup\data\emp1_dat.mdf’,SIZE=4mb,MAXSIZE=30mb,FILEGROWTH=1mb)

ALTER DATABASE empADD FILEGROUP frgp1

ALTER DATABASE empADD FILE(NAME= ‘emp2_dat’,FILE NAME=’c:\mssql\emp2_dat.mdf’,SIZE=4mb,MAXSIZE=30mb,FILEGROWTH=1mb)TO FILEGROUP frgp1

Page 19: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

VIEWING THE DATABASE:The information regarding the database such as owner, size, date and time of

creation, status can be viewed using the following System Stored Procedure:

Syntax:

NOTE: The sp_helpdb system stored procedure without a database name reports information about all the databases in the system.

Database options can be changed or displayed using:

Syntax:

Different options that can be set to database are:

Dbuseonly – only owner of the database can use it.

Offline – the database is offline when this option is set.

Readonly – data can only read in the database

Select into/bulk copy – faster bulk copy

Single user – only one user can use it

Example:

Renaming the database:

The name of the database can be changed as:

Syntax:

Visit: www.gcreddy.net for Testing Information 19

Sp_helpdb ‘database name’

Example:sp_helpdb emp

Sp_dboption ‘database name’, ‘option name’, TRUE/FALSE

sp_dboption ‘emp’, ‘readonly’, TRUE

sp_renamedb ‘old name’, ‘new name’Example:sp_renamedb ‘emp’, ’employee’

Page 20: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Deleting the database:

Syntax:

TABLES

Tables are database objects that contain all the data in a database. A table definition is a collection of columns. In tables, data is organized in a row-and-column format similar to a spreadsheet. Each row represents a unique record, and each column represents a field within the record.

After you have designed the database , the tables that will store the data in the database can be created. The data is usually stored in permanent tables. Tables are stored in the database files until they are deleted and are available to any user who has the appropriate permissions.

Temporary Tables

You can also create temporary tables. Temporary tables are similar to permanent tables, except temporary tables are stored in tempdb and are deleted automatically when no longer in use.

The two types of temporary tables, local and global, differ from each other in their names, their visibility, and their availability. Local temporary tables have a single number sign (#) as the first character of their names; they are visible only to the current connection for the user; and they are deleted when the user disconnects from instances of Microsoft® SQL Server™ 2000. Global temporary tables have two number signs (##) as the first characters of their names; they are visible to any user after they are created; and they are deleted when all users referencing the table disconnect from SQL Server.

For example, if you create a table named employees, the table can be used by any person who has the security permissions in the database to use it, until the table is deleted. If you create a local temporary table named #employees, you are the only person who can work with the table, and it is deleted when you disconnect. If you

Visit: www.gcreddy.net for Testing Information 20

DROP DATABASE <database name>

Example:DROP DATABASE employee

Page 21: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

create a global temporary table named ##employees, any user in the database can work with this table. If no other user works with this table after you create it, the table is deleted when you disconnect. If another user works with the table after you create it, SQL Server deletes it when both of you disconnect.

Table Properties

You can define up to 1,024 columns per table. Table and column names must follow the rules for identifiers; they must be unique within a given table, but you can use the same column name in different tables in the same database. You must also define a data type for each column.

Although table names must be unique for each owner within a database, you can create multiple tables with the same name if you specify different owners for each.

Creating a Table using Enterprise Manager:

1. Open the Enterprise Manger Tool from the Start menu.2. Expand the server Group and the corresponding server.3. Expand the corresponding database4. Right click on Tables and select New Table… item

Visit: www.gcreddy.net for Testing Information 21

Page 22: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

5. In the window displayed enter a name to the column, data type and lengh

6. Click on the save icon of the toolbar to save the table.

Creating a Table using Query Analyzer:

Visit: www.gcreddy.net for Testing Information 22

Page 23: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

We can make use of the following syntax to create a table:

NULL | NOT NULL

Are keywords that determine if null values are allowed in the column. NULL is not strictly a constraint but can be specified in the same manner as NOT NULL.

DEFAULT

Specifies the value provided for the column when a value is not explicitly supplied during an insert.

constant_expression

Is a constant, NULL, or a system function used as the default value for the column.

IDENTITY

Indicates that the new column is an identity column. When a new row is added to the table, Microsoft® SQL Server™ provides a unique, incremental value for the column. The IDENTITY property can be assigned to tinyint, smallint, int, bigint, decimal(p,0), or numeric(p,0) columns. Only one identity column can be created per table. Bound defaults and DEFAULT constraints cannot be used with an identity column. You must specify both the seed and increment or neither. If neither is specified, the default is (1,1).

seed

Is the value used for the very first row loaded into the table.

increment

Is the incremental value added to the identity value of the previous row loaded.

Visit: www.gcreddy.net for Testing Information 23

CREATE TABLE tablename(colname datatype (size) [NOT NULL | DEFAULT <constant value> | IDENTITY(seed,increment)], colname2 ……..)

Page 24: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Example:

1. Select the corresponding database in which we want to create the table from the available drop down button.

2. Type the following command in the window.

3. click on Execute button to run the command.

Example 2: Crating a table with identity column

When an IDENTITY property to define an identifier column, consider that:

A table can have only one column defined with the IDENTITY property The seed and increment can be specified. The default for both is 1 The identifier column must not allow NULL values and must not contain

DEFAULT definition In order to insert the values explicitly into the identity column , SET

IDENTITY_INSERT option is used.

Syntax:

Visit: www.gcreddy.net for Testing Information 24

CREATE TABLE dept( dept_no int identity (10,10), dept_name varchar(20), location varchar(20))

SET IDENTITY_INSERT tablename ON | OFF

Page 25: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

DATATYPES:

The choice of the datatype determines the kind of data that can be stored in the column and the maximum length of data that can be stored in the column. SQL Server provides different type of data. They are:

Numeric Datatypes:

SQL Server provides many ways to store numeric values, which provide flexibility in precision, range of values, and data storage size. Numeric type falls into various categories like int, smallint, tinyint, money, smallmoney, and bit. To store decimal values datatypes like float,real, decimal and numeric are use.

“Bigint” is the new datatype in SQL Server 2000 under this category.

Character Datatype:

There are three valid datatypes for storing strings. They are:

Char: this is used for storing fixed-length strings. Columns defined as char will store blanks to fill out a fixed number of characters. The maximum length of a character column is 8000 bytes.

Varchar: this is used for storing variable length strings. Columns defined as varchar will truncate blanks to save space.

Text: this is used for storing of virtually unlimited size(upto 2 gigabytes of text per row.

Binary Datatypes:

These datatypes store strings consisting of binary values.i.e, haxadecima numbers instead of characters. They are:

Binary: Stores binary data of fixed lengh with a maximum lengh of 8,000 bytes

Varbinary: Stores variable lengh binary data with a maximum length of 8,000 bytes

Visit: www.gcreddy.net for Testing Information 25

Page 26: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Image: SQL Server provides a mechanism for storing binary data more than 8000 bytes using image datatypes. For Example, the photograph of the employees can be stored.

DateTime Datatype:

SQL Server enables to store date and time values. Columns using datetime or smalldatetime will store both date and time.

Unicode Datatype:

Unicode standard includes all the characters that are defined in the various character sets. Using Unicode data types, a column can store any character that is defined by the Unicode standard. Unicode data is stored using nchar, nvarchar, ntext datatypes.

Special DataTypes:

Cursor,TimeStamp, Unique Identifier and Bit.

New Datatypes:

SQL Server 2000 introduces three new data types. bigint is an 8-byte integer type. sql_variant is a type that allows the storage of data values of different data types. table is a type that allows applications to store results temporarily for later use. It is supported for variables, and as the return type for user-defined functions

Modifying Tables

After a table is created, you can change many of the options that were defined for the table when it was originally created, including:

Columns can be added, modified, or deleted. For example, the column name, length, data type, precision, scale, and nullability can all be changed, although some restrictions exist. For more information.

PRIMARY KEY and FOREIGN KEY constraints can be added or deleted. UNIQUE and CHECK constraints and DEFAULT definitions (and objects) can be

added or deleted.

Visit: www.gcreddy.net for Testing Information 26

Page 27: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

An identifier column can be added or deleted using the IDENTITY or ROWGUIDCOL property.

Renaming a Table

Renaming a Column:

Syntax for ALTER TABLE command:

Examples:

Changing datatype

Changing NULLs

Adding Columns

Visit: www.gcreddy.net for Testing Information 27

ALTER TABLE tablenameADD columnName datatype [not null |identity|default…]|ALTER COLUMN <column specifications>|DROP COLUMN columnName|ADD CONSTRAINT constraintName {CHECK(..) | UNIQUE | PRIMARY KEY..}|DROP CONSTRAINT constraintName

ALTER TABLE emp ALTER COLUMN emp_no varchar(5)

Syntax:SP_RENAME <old_tableName>,<new_tableName>

Example:SP_RENAME employee.emp

Syntax:SP_RENAME <’ tableName.columnname’>,<’newcolName’>

Example:SP_RENAME ‘emp.basic_salary’,’bsal’

ALTER TABLE emp ALTER COLUMN emp_no varchar(5) not null

Page 28: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Sp_help:

This System Stored Procedure is used to provide description about the table structure.

Example:

Inserting Values in a Table

The Insert command is used to add rows to a table. The data entered in the table should match the order of the columns as they appear in the table.

Syntax:

Example:

When only the date is specified in the datetime datatype, the time is included as 00:00 AM by default.

If we want to insert only certain columns data into the table, the column names have to be specified.

Example:

Data ManipulationTo modify the values stored in a table, UPDATE statement is used.

Example: the employee name Samuel with the emp_no “E001” was wrongly entered as Sam in the table. To correct it, the following statement is used.

Visit: www.gcreddy.net for Testing Information 28

ALTER TABLE emp ADD doj datetime

SP_HELP emp

INSERT <table_name> (column_list) VALUES (data_list)

INSERT empVALUES(‘E001’,’sam’,10,’B’,4500,’11/3/96’)

INSERT emp ( emp_no,emp_name)VALUES(‘E004’,’Sammy’)

Page 29: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Deleting data from a Table:To remove rows from a table, DELETE or TRUNCATE statements can be used.To delete a particular row from the table we have to use DELETE command.

To delete all rows from the table, TRUNCATE command can also be used.

The TRUNCATE statement removes the whole table at a time. Whereas the delete table command removes each row from the table one by one. This is much faster than a DELETE statement, especially on large tables.

To remove the table along with the structure, DROP statement is used.

Retrieval of Data:To retrieve data from a database object, SELECT statement is used.

Syntax:

Visit: www.gcreddy.net for Testing Information 29

UPDATE empSET emp_name=’Samuel’WHERE emp_no=’E001’

Syntax:DELETE FROM tablename WHERE condition

Example:DELETE FROM emp WHERE emp_no=’E002’

Syntax:TRUNCATE TABLE tablename

Example:TRUNCATE TABLE emp

Syntax:DROP TABLE tablename

Example:DROP TABLE dept1

SELECT <column_list> FROM <table_name> WHERE <condition>

Page 30: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Example:

DATA INTEGRITY

It is very important for the data in a database to be accurate, consistent and reliable. This implies that it is very crucial to enforce data integrity.

Data integrity ensures the consistency and correctness of data stored in a database. It is broadly classified into the following four categories.

Entity integrity – ensures that each row in a table is unique. It enforces integrity of the data contained in the columns, which uniquely identify the rows in a table.

Domain integrity – ensures that only valid ranges of values are allowed to be stored in a column. It can be enforced, by restricting the type of data, the range of values and the format of the data.

Referential integrity – ensures that the data in the database remains uniformly consistent, accurate and usable even after the data in it has been changed. It maintains the integrity of data by ensuring that the changes made in the parent table are also reflected in all the dependent tables.

User defined integrity – refers to a set of rules specified by a user, which do not belong to the entity, domain and referential integrity categories.

ENFORCING DATA INTEGRITY

Incorporating business rules and specifying the relevant constraints can enforce data integrity.

Business rules refer to specific policies followed by an organization for the smooth running of its business. Business rules ensure that the database stores accurate data in relation to the business policies.

For example an organization may have a personnel policy, which states that the minimum salary of an employee is $500. This is a business rule.

Constraints refer to rules, which restrict the values that are inserted in the columns of a table.

CONSTRAINTS:

A Constraint can either be created at the time of creating a table or can be added later. When a constraint is created after table creation, it checks the existing data. If the existing data does not conform to the rule being enforced by the constraint, then the constraint is rejected.

Visit: www.gcreddy.net for Testing Information 30

1. SELECT * FROM emp2. SELECT emp_no,emp_name

FROM empWHERE dept_no=10

Page 31: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

A constraint can be created using either of the following statements:

CREATE TABLE statement. ALTER TABLE statement.

Using CREATE TABLE statement:

A constraint can be defined on a column at the time of creating a table. It can be created with the CREATE TABLE statement:

The syntax is :

Using ALTER TABLE statement:

A constraint can also be defined on a column after a table has been created. This can be done using the ALTER TABLE statement.

The syntax is:

TYPES OF CONSTRAINTS

The following are the different types of Constraints:

CHECK constraint UNIQUE KEY constraint PRIMARY KEY constraint FOREIGN KEY constraint

CHECK CONSTRAINT

A CHECK constraint enforces domain integrity by restricting the values to be inserted in a column. It allows only valid values in a column. It is possible to define multiple CHECK constraints on a single column.

Syntax:

Visit: www.gcreddy.net for Testing Information 31

CREATE TABLE table name(ColumnName1 datatype CONSTRAINT contraint_name constraint_type, Columnname2 data type ……….)

ALTER TABLE table nameADD CONSTRAINT constraint_name constraint_type (fieldName)

CREATE TABLE table_name(colName datatype CONSTRAINT const_name CHECK(<criteria>), colName2 ………..)

Page 32: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Example:

The rules regarding the creation of CHECK constraint are as follows: It can be created at the column level as well as table level. It is used to limit the values that can be inserted into a column. It can contain user-specified search conditions. It cannot contain sub queries. A sub query is one or more select

statements embedded within another select statement. It does not check the existing data into the table if created with the No

Check Option. It can reference other columns of the same table.

UNIQUE CONSTRAINT

UNIQUE constraints are used to enforce uniqueness on non-primary key columns.

A primary key constraint column automatically includes a restriction for uniqueness. However a unique constraint allows null values.

It is not advisable to have columns with null values, though these are allowed. A null value is also validated, hence there can only be one record in the table with a null value. The table can’t contain another row with null value.

For example:

The rules regarding the creation of UNIQUE constraint are:

It does not allow two rows to have the same non-null values in a table. It gets enforced automatically when a UNIQUE index is created. Multiple UNIQUE constraints can be placed on a table.

PRIMARY KEY constraint:

A primary key constraint is defined on a column or a set of columns whose values uniquely identify the rows in a table. These columns are referred to as primary key

Visit: www.gcreddy.net for Testing Information 32

CRAETE TABLE Location(Loc_id int, City varchar(15) CONSTRAINT chk_city CHECK( city in (‘’ BERKELEY’, ‘BOSTON’, ‘CHICAGO’, ‘DALLAS’, ‘MUNCHEN’, ‘NEW YORK’, ‘PARIS’, ‘WASHINGTON’,)

ALTER TABLE AUTHOUR ADD CONSTRAINT unq_ta UNIQUE (title_id, au_id)

Page 33: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

columns. A primary key column cannot contain NULL values since it is used to uni8quely identify rows in a table.

While defining a PK constraint, you need to specify a name for the constraint. If no name is specified, SQL Server automatically assigns a unique name to the constraint.

Any column or set of columns that uniquely identifies a row in a table can be a candidate for the primary key. These set of columns are referred to as candidate keys. One of the candidate keys is chosen to be the primary key, based on familiarity and greater usage. The other key, which is not chosen as the primary key is called as alternate key.

Syntax:

Example:

CLUSTERED AND NON CLUSTERED INDEX

An index is a database object which provides faster access to data by searching the data using the key values. When an index is created on a table, the data in the table is sorted based on the key value on which the index is created.

Sql server provides two types of indexes:

Clustered index Non clustered index

Visit: www.gcreddy.net for Testing Information 33

CREATE TABLE table name(ColumnName1 datatype CONSTRAINT contraint_name Primary key, Columnname2 data type ……….)

OR

ALTER TABLE table nameADD CONSTRAINT constraint_name PRIMARY KEY (field name)

CREATE TABLE emp(empcode int CONSTRAINT pk_const PRIMARY KEY,name char (20),designation char(20),salary int not null)

OR

ALTER TABLE empADD CONSTRAINT pk_const PRIMARY KEY (empcode)

Page 34: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

In a clustered index the data is physically sorted, as a result, only one clustered index is possible per table. A clustered index changes the physical order of the rows. Therefore, it is advisable to create a clustered index before a non-clustered index so that the non clustered index is not rebuilt. A clustered index is faster in performance in comparison to a con clustered index.

Hence a clustered index is one in which the logical order of the index is same as the physical sorted order of the corresponding rows that exist in a table.

A non-clustered index is a separate index structure independent of the physical sort order of the data in the table. As such, the data rows may be randomly placed in the table.

Hence a non-clustered index one in which the logical order of the index does not match the physical sort order of the rows on disk.

If a column has a PRIMARY KEY constraint with a clustered index defined on it, then the constraint needs to be dropped before a new constraint is defined on the column

It creates unique clustered index by default It cannot be created on columns that have been defined as NULL during table

creation It can be created only once for a table, that is only primary key constraint can

be created per table It always checks for existing data even if it is created with the WITH NO

CHECK OPTION

When a PK constraint is created a unique clustered index gets created automatically. The index cannot be dropped explicitly. It is dropped only when the table or the constraint is dropped. If a clustered index already exists, then the PK constraint gets rejected.l

Foreign key constraintsA foreign key is a column or combination of columns whose values match the

primary key of another table.

A foreign key does not have to be unique. However, foreign key values must be copies of the primary key values of the master table.

A foreign key is a column on which a FOREIGN KEY constraint has been defined. A FOREIGN KEY constraint associates one or more columns of a table with an identical set of columns on which a PRIMARY KEY constraint has been defined (primary key column) in another table.A foreign key may refer to the primary key of another table or same table.

Syntax:

Visit: www.gcreddy.net for Testing Information 34

CREATE TABLE table_name(colName datatype CONSTRAINT const_name REFERENCES parent_Table(primary key column),colName2……..)(or)ALTER TABLE table_nameADD CONSTRAINT const_name REFERENCES parent_Table(primarykey column)

Page 35: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

For Example:

The rules regarding the creation of a FOREIGN KEY constraint are as follows:

The no.of columns specified in the foreign key statement must match the no.of columns in the references clause and must be specified in the same order.

The foreign key can reference the primary key or a UNIQUE constraint of another table.

The foreign key constraint that is created using the WITH NOCHECK option will prevent the foreign key constraint from validating existing data.

DROPPING CONSTRAINTS:

A constraint can be dropped using the alter table statement in the query analyzer.The syntax of the ALTER TABLE statement for dropping a constraint is;

Drops the constraint, con_city, defined on the city column of the publishers table.All the constraints defined on a table are dropped automatically when the table is dropped.

CONSTRAINTS AND TRIGGERS:Each category of data integrity is best enforced through the following

constraints.

Entity integrity is best enforced through the PRIMARY KEY constraint, UNIQUE constraint and the IDENTITY property.

The IDENTITY property creates an identity column in the table. An identity column is a primary key column for which numeric values are generated automatically. Each generated value is different from the previous value, thus ensuring uniqueness of data in each row at the table. The IDENTITY property also ensures that while inserting data, the user need not explicitly insert a value for the identity column.

Domain integrity is best enforced through the DEFAULT constraint, CHECK constraint and the FOREIGH KEY constraint.

Visit: www.gcreddy.net for Testing Information 35

ALTER TABLE dept ADD CONSTRAINT fk_ecode FOREIGN KEY (e_code) REFERENCES EMPLOYEES(e_code)

ALTER TABLE table_nameDROP CONSTRAINT constraint_name

For example:ALTER TABLE publishersDROP CONSTRAIANT con_city

Page 36: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Referential integrity is best enforced through the FOREIGN KEY constraint and the check constraint.

User-defined integrity is best enforced through all column and table level constraints that are specified with the CREATE TABLE constraint.

RULES AND DEFAULTS

Rules and defaults are objects, which help enforce the data integrity. These objects are bound to columns or user defined data types to ensure that only valid values are allowed to insert into the tables.

RulesA rule provides a mechanism for enforcing domain constraints for columns or

user defined data types. The rule is applied before any modification is to be done on the table. In other words, a rule specifies the restriction on the values for a column or a user defined data type.

The syntax of the CREATE RULE statement is:

More Examples:

CREATE RULE dept_name_ruleAS @deptname NOT IN (‘accounts’,’stores’)

CREATE RULE max_price_ruleAS @maxprice >=$5000

CREATE RULE emp_code_ruleAS @empcode LIKE ‘[F-M][A-Z]

Information on a rule can be obtained using the sp_help system stored procedure. The text of a rule can be displayed using the sp_helptext system stored procedure with the name of the rule as its parameter.

Binding Rules

A rule can be bound using the sp_bindrule system stored procedure.

Syntax:

Visit: www.gcreddy.net for Testing Information 36

CREATE RULE rule_nameAS conditional_expression.

For example:CREATE RULE type_rule

AS @typerule IN(‘business’,’mod_cook’, ‘trad_cook’, ‘popular_comp’, ‘psychology’)

Sp_bindrule rule_name, object_name.ColName

For example: Sp_bindrule type_rule, ‘titles.type’

Page 37: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Binds the rule, type_rule,to the type column of the titles table

The restrictions on the use of the rules are as follows:

Only one rule can be bound to a column or a user defined datatype. A rule cannot be bound to system datatypes. If a new rule is bound to a column or datatype that is already been inserted in

the table, the existing values in the tables do not have to meet the criteria specified by the rule.

A rule cannot be defined for a system-defined datatype

Unbinding Rules

A rule can be unbound from a column or user-defined datatype using the sp_unbindrule system stored procedure.

The syntax of the sp_unbindrule is:

Unbinds the rule attached to the type column of the titles table.

DEFAULTS

Default is a constant value assigned to a column, into which the user need not insert values.A default can be bound to a column or a user-defined datatype.

The syntax of the CREATE DEFAULT statement is:

Any constant, built-in funtion, mathematical expression or a global variable can be used in the constant expression. The character and date constants must be included in single quotation marks (‘), whereas money, integer, and floating-point constants can be specified without quotation marks. Binding Defaults The sp_bindefault system stored procedure is used for binding a default.The syntax of sp_bindefault is:

Visit: www.gcreddy.net for Testing Information 37

Sp_unbindrule object_name

For example: Sp_unbindingrule ‘titles.type’

CREATE DEFAULT default_nameAs constant_expression

Sp_bindefault default _name_, ‘object_name.ColName’

For example: 1.CREATE DEFAULT city_default AS ‘Oakland’

2. Sp_default city_default, ‘authors.city’

Page 38: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Creates a default, city_default, and binds the default value, Oakland, to city column of the authors table.

The statement

Binds the default city_default to the user-defined datatype, city_datatype.

UNBINDING DEFAULTS

Defaults can be unbound from a column or user defined datatype using the sp_unbindefault system stored procedure.

The syntax of sp_unbindefault is:

Unbinds the default specified on the city column of the authors table.

RENAMING RULES AND DEFAULTS

The sp_rename system stored procedure can be used for renaming rules and defaults.

The syntax of sp_rename is:

DROPPING RULES AND DEFAULTS

The DROP RULE and DROP DEFAULT statement can be used to drop a rule and default respectively.A rule or default must be unbound from the column or the user-defined datatype before it is dropped.

The syntax for dropping a rule is:

Visit: www.gcreddy.net for Testing Information 38

Sp_bindefault city_default, city_datatype.

Sp_unbindefault object_nameFor example: Sp_unbindefault ‘authors.city’

Sp_rename old_object_name, new_object_name

Page 39: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Where rule_name is the name of the rule to be dropped.

The syntax for dropping a default is :

Where default_name is the name of the default to be dropped.

JOINS

By using joins, you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how Microsoft® SQL Server™ 2000 should use data from one table to select the rows in another table.

A join condition defines the way two tables are related in a query by:

Specifying the column from each table to be used for the join. A typical join condition specifies a foreign key from one table and its associated key in the other table.

Specifying a logical operator (=, <>, and so on) to be used in comparing values from the columns.

Visit: www.gcreddy.net for Testing Information 39

DROP RULE rule_name

DROP DEFAULT default_name

Page 40: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Joins can be specified in either the FROM or WHERE clauses. The join conditions combine with the WHERE and HAVING search conditions to control the rows that are selected from the base tables referenced in the FROM clause.

Specifying the join conditions in the FROM clause helps separate them from any other search conditions that may be specified in a WHERE clause, and is the recommended method for specifying joins. A simplified SQL-92 FROM clause join syntax is:

Join_type specifies what kind of join is performed: an inner, outer, or cross join. join_condition defines the predicate to be evaluated for each pair of joined rows. This is an example of a FROM clause join specification:

Although join conditions usually have equality comparisons (=), other comparison or relational operators can be specified, as can other predicates

When SQL Server processes joins, the query engine chooses the most efficient method (out of several possibilities) of processing the join. Although the physical execution of various joins uses many different optimizations, the logical sequence is:

The join conditions in the FROM clause are applied.

The join conditions and search conditions from the WHERE clause are applied. The search conditions from the HAVING clause are applied.

Types of Joins

Join conditions can be specified in either the FROM or WHERE clauses; specifying them in the FROM clause is recommended. WHERE and HAVING clauses can also contain search conditions to further filter the rows selected by the join conditions.

Joins can be categorized as:

Inner joins (the typical join operation, which uses some comparison operator like = or <>). These include equi-joins and natural joins.

Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. For example, retrieving all rows where the student identification number is the same in both the students and courses tables.

Outer joins. Outer joins can be a left, a right, or full outer join.

Visit: www.gcreddy.net for Testing Information 40

SELECT columnList FROM first_table join_type second_table [ON (join_condition)]

Page 41: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause:

LEFT JOIN or LEFT OUTER JOIN

The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.

RIGHT JOIN or RIGHT OUTER JOIN.

A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.

FULL JOIN or FULL OUTER JOIN.

A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.

Cross joins.

Cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products.

Case Study:

When you look at the example tables below, notice that: 

The "Employee_ID" column is the primary key of the "Employees" table The "Prod_ID" column is the primary key of the "Orders" table The "Employee_ID" column in the "Orders" table is used to refer to the

persons in the "Employees" table without using their names

Employees:

Employee_ID Name01 Hansen, Ola02 Svendson, Tove

Visit: www.gcreddy.net for Testing Information 41

Page 42: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

03 Svendson, Stephen04 Pettersen, Kari

Orders:

Prod_ID Product Employee_ID234 Printer 01657 Table 03865 Chair 03

Using JoinsExample INNER JOIN

Syntax

SELECT field1, field2, field3FROM first_tableINNER JOIN second_tableON first_table.keyfield = second_table.foreign_keyfield

Who has ordered a product, and what did they order?

SELECT Employees.Name, Orders.ProductFROM EmployeesINNER JOIN OrdersON Employees.Employee_ID=Orders.Employee_ID

The INNER JOIN returns all rows from both tables where there is a match. If there are rows in Employees that do not have matches in Orders, those rows will not be listed.

Result

Name ProductHansen, Ola PrinterSvendson, Stephen TableSvendson, Stephen ChairExample LEFT JOIN

Syntax

SELECT field1, field2, field3FROM first_tableLEFT JOIN second_tableON first_table.keyfield = second_table.foreign_keyfield

List all employees, and their orders - if any.

Visit: www.gcreddy.net for Testing Information 42

Page 43: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

SELECT Employees.Name, Orders.ProductFROM EmployeesLEFT JOIN OrdersON Employees.Employee_ID=Orders.Employee_ID

The LEFT JOIN returns all the rows from the first table (Employees), even if there are no matches in the second table (Orders). If there are rows in Employees that do not have matches in Orders, those rows also will be listed.

Result

Name ProductHansen, Ola PrinterSvendson, Tove  Svendson, Stephen TableSvendson, Stephen ChairPettersen, Kari  Example RIGHT JOIN

Syntax

SELECT field1, field2, field3FROM first_tableRIGHT JOIN second_tableON first_table.keyfield = second_table.foreign_keyfield

List all orders, and who has ordered - if any.

SELECT Employees.Name, Orders.ProductFROM EmployeesRIGHT JOIN OrdersON Employees.Employee_ID=Orders.Employee_ID

The RIGHT JOIN returns all the rows from the second table (Orders), even if there are no matches in the first table (Employees). If there had been any rows in Orders that did not have matches in Employees, those rows also would have been listed.

Result

Name ProductHansen, Ola PrinterSvendson, Stephen TableSvendson, Stephen ChairExample

Who ordered a printer?

Visit: www.gcreddy.net for Testing Information 43

Page 44: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

SELECT Employees.NameFROM EmployeesINNER JOIN OrdersON Employees.Employee_ID=Orders.Employee_IDWHERE Orders.Product = 'Printer'

Result

NameHansen, Ola

Self Join:Joining a table to it self is called as self join. In a self-join, we have to use two

copies of the same table twice. To distinguish between the two copies we have to use duplicate names to the tables called as table aliases.

Example:

Get the employees and corresponding manager names from the following emp table. In this table mgrid filed refers the id of the manager for the employee. These are nothing but empid’s. It means, any one of the employees will become the manager for other employee.

EMPEmpid Empname mgrid

100 Anil 104101 Balu 103102 Santosh 100103 Vivek 104104 Jagan 102

BUILT IN FUNCTIONS

SQL Server 2000 provides a lot of functions, which can be used as calculated fields as part of column lists in a SELECT statement. Such functions are called as Built-in Functions.

Arithmetic operators

The arithmetic operators supported by SQL server are:

+ for addition - for subtraction / for division * for multiplication

Visit: www.gcreddy.net for Testing Information 44

SELECT a.empid,a.empname,a.mgrid,b.empname ManagerName FROMEMP a INNER JOIN EMP bON a.mgrid=b.empid

Page 45: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

% for modulo

The modulo arithmetic operator is used to obtain the remainder of two divisible numeric integer values. It cannot be used with money data type columns.

All the arithmetic operators can be used in the SELECT list with the column names and numeric constants in a combination.

Example:

When any arithmetic operation is performed on a NULL value, the result is always NULL because NULL values have no explicitly assigned values. Arithmetic operations can be performed on more than one column at a time. Consider the following query code:

The above query computes the product of ytd_sales and price from the titles table and displays the output with the user-defined headings.

Some rules regarding the usage of arithmetic operators are:

Arithmetic operations can be performed on numeric columns or numeric constants.

The modulo (%) operator cannot be used with columns of money, smallmoney, float or real datatypes.

The syntax is:SELECT function_name(parameters)

String functions provided by SQL server.

FUNCTION DESCRIPTIONExpression+expression[+expression] Concatenates two or more character or

binary strings.ASCII (character_expression) Returns the ASCII value of the

characater expressionCHAR (integer_expression) Returns the character equivalent of the

ASCII code value.CHARINDEX(‘pattern’, expression) Returns the starting position of the

specified pattern.DIFFERENCE (character_expression1, character_expression2)

Compares two straing and evaluates the similarity between them on a scale of 1 to 4.

LOWER (character_expression) Converts two string and evaluates the

Visit: www.gcreddy.net for Testing Information 45

SELECT title_id, price, price+5, ytd_sales*5 FROM titles.

SELECT Title_Id=title_id, sValue=ytd_sales*price FROM tiles

Page 46: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

similarity between them on a scale of 1 to 4.

LTRIM(character_expression) Returns the data with out leading brackets

PATINDEX(‘%pattern’, expression) Returns the starting position of the first occurrence of the pattern in the specified expression, zero if the pattern is not found.

REPLICATE(char_expression, integer_expression

Repeats a character expression a specified number of times.

REVERSE(character_expression) Returns the reverse of character expression.

RIGHT(character_expression, integer_expression)

Returns the part of the character string from the right.

RTRIM(character_expression) Returns the data without tailing blanks.SOUNDEX(character_expression) Returns the four-digit code to evaluate

the similarity of two character strings.SPACE(numeric_expression) Returns a string of repeated spaces.

The number of spaces is equal to the integer expression.

STR(float expression[,length[,decimal]]) Returns character data converted from numeric data.

STUFF(charactaer_expression1,start,length, character_expression)

Deletes length characters from first character exspression at start and then inserts character expression2 into character expression.

UPPER(character_expression) Converts the character expression into upper case.

Date Functions:The syntax is:SELECT date_function(parameters)

FUNCTION DESCRIPTIONDATEADD(datepart, number, date) Adds the no.of dateparts to date.DATEDIFF(datepart, date1, date2) Returns the number of dateparts

between two dates.DATENAME(datepart, date) Returns the integer value of the date

part.DATEPART(datepart,date) Returns the integer value of the date

part.GETDATE() Returns the current date and time.

Examples:

SELECT GETDATE()

Visit: www.gcreddy.net for Testing Information 46

Page 47: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

The above statement displays the current system date and time with the help of the GETDATE function.

SELECT DATEDIFF(yy,ord_date,getdate())

This statement uses the DATEDIFF function to find the difference between the current date and the order_date, from sales tables. The difference should be expressed in terms of number of years.

SELECT title, DATEPART(yy,pubdate) FROM titles.

The above statement uses the DATEPART function to return the year when the book was published, along with the title name.

SELECT Title=title_id, Month=dATENAME(mm,pubdate), year=DATENAME(yy, pubdatae) FROM titles.

Data Conversion:

SQL server handles certain datatype conversion automatically. If a character expression is compared with an int expression, SQL server makes the conversion automatically for the comparison(implicit conversion).

The CONVERT function is used to change data from one type to another when SQL server cannot implicitly perform a conversion. Using the CONVERT function, data can be modified in variety of styles.

The syntax is:

Aggregate FunctionsAggregate functions are used to produce summary data using tables.

Function Parameters Description

AVG (ALL/DISTINCT] expression Returns the average of values specified in the expression, either all records or distinct records

SUM (ALL/DISTINCT] expression) Returns the sum of values specified in the expression, either all records or distinct records.

MIN (expression) Returns the minimum of a value specified in the expression.

MAX (expression) Returns the maximum of a value specified in the expression.

COUNT (ALL| DISTINCT expression) Returns the number of unique or all records specified in an expression.

Visit: www.gcreddy.net for Testing Information 47

SELECT Ytd_Sales=CONVERT(char(10),ytd_sales)FROM titles.

SELECT CONVERT(int, zip) FROM authors

CONVERT(datatype[(length), expression[,style])

Page 48: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

COUNT (*) Returns the total number of records specified in an expression.

Examples of Aggregate functions

SELECT ‘Average Price”=AVG(price) FROM titles

Returns the average value of all the price values in the titles table with user-defined heading.

SELECT ‘Sum’=SUM(DISTINCT advance) FROM titles

Returns the sum value of all-the unique advance values in the titles table with user-defined heading.

SELECT ‘Minimum Ytd Sales’=MIN(ytd_sales) FROM titles

Returns the minimum value of ytd_sales value in the titles table with user-defined heading.

SELECT ‘Maximum Ytd Sales’=MAX(ytd_sales) FROM titles

Returns the maximum value of ytd_sales in the titles table with user-defined heading.

SELECT ‘Unique Price’=COUNT(DISTINCT price) FROM titles

Returns the number of unique price values in the titles table with user-defined heading.

SELECT ‘Price=COUNT(price) FROM titles

Returns the number of total number of price values in the titles with user-defined heading.

Selecting Rows

There are situations in which only a few rows need to be retrieved from the table based on a condition. The WHERE clause, is provided by SQL server, to specify a condition.

The syntax for using the WHERE clause is:

Example:

Search Based On Conditions

SQL Server provides few methods of searching rows in a table. These methods can be broadly categorized into the following categories.

Comparison operators like =, >, <, >=, <=, !=, !< and !> Range operators like BETWEEN and NOT BETWEEN. List operators line IN and NOT IN. String operators like LIKE and NOT LIKE. Unknown values like IS NULL and NOT NULL. Logical operators like AND , OR and NOT.

Comparison OperatorThe command syntax is:

Visit: www.gcreddy.net for Testing Information 48

SELECT column_list FROM table_name WHERE search_condition

SELECT * FROM publishers WHERE state = ‘MA’

Page 49: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

SELECT column_list FROM table_name WHERE expression1 comparison_operator expression2

Valid Comparison operatorsOperator 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

Examples:

Range Operator

The range operator is used to retrieve data that can be extracted in ranges. The range operations are:

BETWEEN NOT BETWEEN

The syntax is:

List Operator

The syntax is:

Visit: www.gcreddy.net for Testing Information 49

SELECT title FROM titles WHERE type=’business’SELECT stor_id, ord_num, title_id FROM sales WHERE qty>20SELECT type, title_id, price FROM titles WHERE price * ytd_sales<advance.

SELECT column_list FROM table_name WHERE expression1 range_operator expression2 AND expression2

Examples:

1. SELECT title from titles WHERE advance BETWEEN 2000 AND 50002. SELECT title FROM titles WHERE advance NOT BETWEEN 4000 AND 5000

SELECT column_list FROM table_name WHERE expression list_operator(‘value_list’)

Examples:

1. SELECT pub_name, city, state FROM publishers WHERE state IN (‘MA’, ‘DC’)

2. SELECT pub_name, city, state FROM publishers WHERE state NOT IN (‘MA’, ‘DC’)

Page 50: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

String Operator

SQL Server provides a pattern-matching method for string expressions using the LIKE keyword with the wildcard characters. The LIKE keyword is used to select those rows that match the specified portion of character string. The LIKE keyword allows wildcard characters that can be used as a part of an expression.

Wild card Description% Represents any string of zero or more characters(s)- Represents a single character[] Represents any single character within the specified range.[^] Represents any single character not within the specified

range.

Examples of the LIKE operator with wildcards.

Example DescriptionSELECT title FROM titles WHERE type LIKE ‘bus%’

Returns all titles from titles table where first three characters of the column type are ‘bus’

SELECT * FROM publishers WHERE country LIKE ‘US_’

Returns all rows from publishers table where country name is three characters long and starts with US where the third character can be anything.

SELECT title_id, price FROM titles WHERE title_id LIKE ‘P[SC]]%’

Returns all columns from the titles table where title_id starts with the character P and contains S or C in the second position followed by any number of characters.

SELECT title_id, price FROM titles WHERE title_id, LIKE ‘P[^C]%’

Returns all title_id and price from the titles table where title_id starts with P and does not contain and S as the second character and the third position onwards can contain any characters.

Unknown ValuesUnknown values refer to the data entered in the form of the NULL keyword. In

SQL serve terms, NULL is an unknown value or the value for which data is not available. The rows containing the NULL values can be retrieved by using the IS NULL keyword in the WHERE clause.

The Syntax is:SELECT column_list FROM table_nameWHERE column_name unknown_value_operator.

SELECT title, ytd_sales FROM titles WHERE ytd_sales IS NULL

Visit: www.gcreddy.net for Testing Information 50

Page 51: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Logical Operator OR – Returns the result when any of the specified search conditions is

true. AND – returns the result when all of the specified search conditions

are true. NOT – Bnegates the expression that follows it.

SELECT column_list FROM table_name WHERE conditional_expression{AND\OR}[NOT] conditional_expression.

Examples of Logical operators

Example DescriptionSELECT * FROM publishers WHERE city=’Boston’ OR city=’Paris’

Returns all the rows specific to the conditions, even if any one of the conditions is true.

SELECT publishers WHERE city=’Boston’ AND city=’MA’

Returns all the rows specific to the conditions, when both the conditions are true.

SELECT * FROM publishers WHERE city=’Boston’ OR NOT city=’Paris’

Returns all the rows specific to the conditions, except the rows specified with the condition after NOT operator.

Distinct

The distinct clause removes duplicate rows from the result set. Duplicate rows can be eliminated by using the DISTINCT keyword in the SELECT statement.

Syntax:

TOP and PERCENTThe TOP clause limits the number of rows returned in the result set.

The syntax is:

TOP n [PERCENT]

Where n specifies the number of rows are to be returned, if PERCENT is not specified. If PERCENT is specified, n specifies the percentage of the rows to be returned.

Visit: www.gcreddy.net for Testing Information 51

SELECT [ALL|DISTINCT] column_name FROM table_nameWHERE search_condition

Example:SELECT DISTINCT title_idFROM titleauthorWHERE title_id LIKE’PS%’

Page 52: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

The TOP clause is used with the SELECT statement.The following example returns the top 20 rows of the result set.

SELECT TOP 20

The next example returns the 10% of rows from top of the result set.

SELECT TOP 10 PERCENT

It the SELECT statement, including TOP, has and ORDER BY clause, then the rows to be returned are selected after the ORDER BY statement has been applied.

SUB QUERIES

A sub query can be defined as a group of nested SELECT statements inside a SELECT, INSERT, UPDATE or DELETE statement. Sub query can also be used inside the WHERE or HAVING clauses of the outer SELECT, INSERT, UPDATE or DELETE statements. SELECT statements containing one or more sub queries are called nested queries.

The command syntax is:

A subquery must be enclosed within parentheses and cannot use ORDER BY, COMPUTE BY or FOR BROWSE clauses. SQL Server does not implement any restriction on level of nesting while using subqueries, SQL Server imposes restrictions on the number of tables or views used in a subquery or a join.

SQL Server evaluates the inner query first and returns the result to the outer query for the final result set.The outer query always depends on the evaluation result of the subquery.

Subqueries can be divided into three catefories depending upon the values they return;

Visit: www.gcreddy.net for Testing Information 52

(SELECT [ALL|DISTINCT] suquery_select_list[FROM {table_nmae | view_name}

[[,table_name2|view_name2}][..,{table_name16|view_name16{]]

[WHERE clause]GROUP BY clause][HAVING clause])

Page 53: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Sub queries that operate on lists: this type of query returns single-column-multiple values results and are implemented using the IN clause. The syntax is as follows:

Subqueries that are introduced with an unmodified comparison o-erator: this type of query returns single column-single value results for outer query evaluation and is implemented using unmodified comparison operators(operators without the ANY or ALL keywords) the syntax is as follows:

Subqueries that check for the existence of data: this type of query checks for the existence of records in a table that are used in the inner query, and returns either a TRUE or a FALSE VALUE based on the existence of data. This is implemented using the EXISTS keyword. The syntax is as follows:\

SubQueries With IN

A subquery introduced with IN returns zero or more values. Consider the following example where all author ID’S, from the TITLEAUTHOR table, are displayed whose books are sold:

SQL Server returns a list of all title IDs to the main query then lists all the authors, whose books are sold, in the result set.

Consider the following example where the server returns a list of publisher IDs to the main query, and then determines whether each publisher’s pub_id is in that list:

The inner query is evaluated first and then the result set is sent to the outer query.

Consider another subquery with the IN clause:

Visit: www.gcreddy.net for Testing Information 53

WHERE expression [NOT] IN (subquery)

WHERE expression comparison_operator [ANY|ALL] (subquery)

WHERE [NOT] EXISTS (subquery)

SELECT au_idFROM titleauthorWHERE title_id IN (SELECT title_id FROM sales)

SELECT publisher=pub_nameFROM publishers WHERE pub_id IN ( SELECT pub_id FROM titles WHERE type=’business’)

SELECT type=type, Average=AVG(ytd_sales)FROM titlesWHERE type IN (SELECT type FROM titles

WHERE title=” the busy executive’s database guide” or title=’Is Anger the Enemy?’) GROUUP BY type

Page 54: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

The inner query is evaluated first and then the result set is sent to the outer query.

The NOT IN clause is used in the same way as the IN clause. Consider the following example.

Sub Queries with EXISTS

The subquery, when used with the EXISTS clause, always returns data in terms of TRUE OR FALSE and passes the status to the outer query to produce the results set. The subquery returns a TRUE value if the result set contains any rows.

The query introduced with the EXISTS keyword differs from other queries. The EXISTS keyword is not preceded by any column name, constant or there expression and it contains an asterisk (*) in the SELECT list.

Aggregate functions can also be used in subqueries. Consider the following example which displays the titles of all those books for which the advance is more than the average advance of business related books.

Subquery Restrictions:

The restrictions imposed are:

Visit: www.gcreddy.net for Testing Information 54

SELECT pub_id, pub_nameFROM publishersWHERE pub_id NOT IN (SELECT pub_id FROM titlesWHERE type=’mod_cook’)

1. SELECT pub_nameFROM publishersWHERE EXISTS (SELECT * FROM titles WHERE type=’business’)

2. SELECT pub_nameFROM publishersWHERE EXISTS (SELECT * FROM publishers WHERE City=’Paris’)

SELECT Title=titleFROM titlesWHERE advance>(SELECT AVG (advance) from titles

WHERE type=’business’)

Page 55: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

The column list of the select statement of a subquery introduced with the comparison operator can include only one column.

The column used in the WHERE clause of the outer query should be compatible with the column used in the select list of the inner query.

The DISTINCT keyword cannot be used with the subqueries that include the GROUP BY clause.

The ORDER BY clause, GROUP BY clause and INTO keyword cannot be used in a subquery, because a subquery cannot manipulate its result internally.

Do not specify more than one column name in the subquery introduced with the EXISTS keyword.

A view created with a subquery cannot be updated.

Nested Sub Queries:A sub query can contain one or more subqueries. There is no restriction in the

number of subqueries that you can include with SELECT, INSERRT, UPDATE or DELETE statements.

Example:

Example DescriptionSELECT title_id=title_id, Title=titleFROM titleWHERE prie>ALL(SELECT priceFROM titlesWHERE pub_id=’0736’)

Lists all the titles along with their IDs from the titles table where price is greater than the maximum price of books published by the publisher with publisher ID 0736.

SELECT title_ID = title_id, Title = titleFROM titlesWHERE price >ANY (SELECT priceFROM titlesWHERE pub_id = `0736`)

Lists all the titles along with their titles IDs from the titles table where price is greater than the minimum price of books published by the publisher with publisher ID 0736.

SELECT publisher_ID = pub_id, Name = pub_nameFROM publishersWHERE city = ANY (SELECT city FROM authors)

Lists all the publishers where city is sane as of any author.

SELECT INTO Statement

Visit: www.gcreddy.net for Testing Information 55

1. SELECT ‘Author Name’=SUBSTRING (au_fname, 1,1)+’.’+au_lastnameFROM authors WHERE au_id IN(SELECT au_id FROM titleauthor WHERE title=’Net Etiquette’))

2. SELECT ‘Author ID’=au_id, Name=SUBSTRING (au_fnmae, 1,1) + ‘.’+au_lname FROM authors WHERE au_id IN (SELECT au_id FROM titleauthor WHERE type=’business’))

Page 56: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

A SELECT statement with an INTO clause is used to store the result set in a new table without a data definition process. The SELECT INTO statement creates a new table, if the table already exists then the operation fails.The syntax of the SELECT INTO statement is:

The SELECT INTO clause creates a permanent table if the select into/bulk copy database option is set. If the select into/bulkcopy database option is not set, then only local temporary tables (prefixed by #), and global temporary tables (prefixed by ##) can be created.

The select into/bulkcopy database option can be set using the following command:

SELECT title_id, titleINTO newtitlesFrom titles WHERE price >$15

Column names in the new table can be changed while specifying the columns in the SELECT statement. Consider the following example with the new column names:

UNION

SQL Server provides a unique operator known as the UNION operator that is used to combine the result set or more queries.

The syntax is:

Visit: www.gcreddy.net for Testing Information 56

SELECT columns_listINTO new_table_nameFROM table_namesWHERE conditions

sp_dboption ‘pubs’, ‘select into / bulkcopy ‘, true

SELECT Title _ID = title _id, Title_Name =titleINTO new titles 1FROM titlesWHERE advance >$7000

SELECT column_list [INTO new_table_name] [FROM clause] [WHERE clause] [GROUP BY clause] [HAVING clause]….] [ORDER BY clause] [COMPUTE clause]

Page 57: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

By default, the result set of the UNION operator removes the duplicate rows from the queries combined, until an ALL clause is specified with the UNION operator.

The queries combined with the UNION operator must contain an equal number of columns or expressions, and they must be compatible with each other

There are two tables: region_east and region_west. The region_east table contains the employee id, name and address of the employees of the eastern region. The region_west table contains the employee id, name and the address of the employees of the western region.

The region_east table contains the following data:

emp_id emp_name emp_add- - - - - - - - - - - - - - - - - - - - - - - - -- -- - - - - - - - - - - - - - - - - -E001 George 323, Park Avenue StreetE002 Jack 475, Barbara LinesE003 Nancy 68, Bank Street

The region_west table contains the following data:

Emp_id emp_name emp_add- - - - - - - - - - - - - - - - - -- - - - - - - - - - - - - -- - - - - - - - - W001 Maria 45, Canara StreetW002 James 12, Blue LinesW003 Jill 98, Civil Lines

The following statement displays employee ids and names of the both the regions: east and the west.

SELECT emp_id emp_name FROM region_eastUnionSELECT emp_id, emp_name FROM region_west

SELECT ‘Employee ID’ =emp_id, ‘Employee Name’=emp_name FROM region_eastUnionSELECT emp_, emp_name FROM region_west

Rules Regarding the use of the UNION Operator

The restrictions imposed by SQL Server on the use of the UNION operator are listed below:

Visit: www.gcreddy.net for Testing Information 57

Page 58: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Corresponding columns in the individual queries of a UNION statement must occur in the same order, because UNION compares the columns in the order specified in the individual queries.

The columns or expressions used in one query must be equal in number, and should be compatible with the columns or expressions of other queries.

The first query in the UNION statement can only contain the INTO clause to store the final result set. The INTO clause cannot be used with any query other than the first query while implementing the UNION operator.

The ORDER BY and COMPUTE BY clauses cannot be used in an individual query. These clauses can be used only at the end of the last query to summarize and order the final result set.

The GROUP BY and HAVING clauses can only be used with individual queries and cannot be used for the final result to be set.

The UNION operator can also be used with the INSERT statement.

VIEWS

A view is a virtual table, which gives access to a subset of columns from one or more tables. Hence, a view is an object that derives its data from one or more tables. These tables are referred to as the base tables or the underlying tables.

Views ensure security of data by restricting access to the following data:

Specific rows of the table Specific columns of the table. Rows fetched by using joins. Statistical summary of data in a given table. Subsets of another view or a subset of views and tables

Common examples of views include:

A subset of rows or columns of a base table. A union of two or more tables A join of two or more tables A statistical summary of a base tables A subset of another view, or some combination of views and base

tables.

Managing Views

Using the CREATE VIEW statement we can create a view.

The syntax of the CREATE VIEW statement is:

The restrictions imposed on views are as follows: A view can be created only in the current database. A view can be created only if there is the SELECT permission on its base table. The SELECT INTO statement cannot be used in a view declaration statement. A view cannot derive its data from temporary tables.

Visit: www.gcreddy.net for Testing Information 58

CREATE VIEW view_name[(column_name [,column_name]….)][WITH ENCRYPTION]AS select_statement[WITH CHECK OPTION]

Page 59: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Example:

The above statements create a view named custview, which contains the custoemerid, companyname and the phone columns of the customer table. The following statement can be used to execute a view:

Getting View Information

SQL Server stores information in a view in the following system tables.

Sysobjects-stores the name of the view Syscolumns-stores the names of the columns defined in the view. Sysdepends-stores information on the view dependencies Syscomments-stores the text of the view definition

Altering a viewA view can be modified without dropping it. It ensures that the permissions on

the view are not lost. A view can be altered without affecting its dependent objects, such as, triggers and stores procedures.

A view can be modified using the ALTER VIEW statement.

The syntax of ALTER VIEW statement is:

Visit: www.gcreddy.net for Testing Information 59

USE NORTHWINDGO

CREATE VIEW custviewASSELECT customerid, companyname, phone FROM customers

GO

SELECT * from custview

ALTER VIEW view_name([column_name])[WITH ENCRYPTION]ASSelect_statement[WITH CHECK OPTION]

Example:ALTER VIEW custviewASSELECT customerid, companyname, phone, faxFrom customers

Page 60: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

The statement generates the results:

SELECT * FROM custview

Dropping a View

A view can be dropped from a database using the DROP VIEW statement. When a view is dropped, it has no effect on the underlying table(s). Dropping a view removes its definition and all permissions assigned to it. Further more if users query any views that refer to a dropped view, they receive an error message. However, dropping a table that refers to a view does not drop the view automatically. You must drop it explicitly.

The syntax of DROP VIEW statement is:

DROP VIEW view_name

Where view_name is the name of the view to be dropped.

It is possible to drop multiple views with a single DROP VIEW. A comma in the DROP statement separates each view that needs to be dropped.

Renaming a View

A view can be renamed with out dropping it. This also ensures that the permissions on the view are not lost.

The guidelines to be followed for renaming a view as follows.

The view must be in the current database. The new name for the view must follow the rules for renaming

identifiers. Only the owner of the view and the database in which view is created

can rename a view.

A view can be renamed by using the sp_rename system stored procedure.

The syntax of sp_rename is

Visit: www.gcreddy.net for Testing Information 60

Sp_rename old_viewname ,new_viewname

Example:sp_rename custview,customerView

Page 61: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

INDEXES

Indexes

Indexes in databases are similar to indexes in books. In a book, an index allows you to find information quickly without reading the entire book. In a database, an index allows the database program to find data in a table without scanning the entire table. An index in a book is a list of words with the page numbers that contain each word. An index in a database is a list of values in a table with the storage locations of rows in the table that contain each value. Indexes can be created on either a single column or a combination of columns in a table and are implemented in the form of B-trees. An index contains an entry with one or more columns (the search key) from each row in a table. A B-tree is sorted on the search key, and can be searched efficiently on any leading subset of the search key. For example, an index on columns A, B, C can be searched efficiently on A, on A, B, and A, B, C.

Most books contain one general index of words, names, places, and so on. Databases contain individual indexes for selected types or columns of data: this is similar to a book that contains one index for names of people and another index for places. When you create a database and tune it for performance, you should create indexes for the columns used in queries to find data.

In the pubs sample database provided with Microsoft® SQL Server™ 2000, the employee table has an index on the emp_id column. The following illustration shows how the index stores each emp_id value and points to the rows of data in the table with each value.

When SQL Server executes a statement to find data in the employee table based on a specified emp_id value, it recognizes the index for the emp_id column and uses the index to find the data. If the index is not present, it performs a full table scan starting at the beginning of the table and stepping through each row, searching for the specified emp_id value.

SQL Server automatically creates indexes for certain types of constraints (for example, PRIMARY KEY and UNIQUE constraints). You can further customize the table definitions by creating indexes that are independent of constraints.

The performance benefits of indexes, however, do come with a cost. Tables with indexes require more storage space in the database. Also, commands that insert, update, or delete data can take longer and require more processing time to

Visit: www.gcreddy.net for Testing Information 61

Page 62: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

maintain the indexes. When you design and create indexes, you should ensure that the performance benefits outweigh the extra cost in storage space and processing resources.

Table IndexesMicrosoft® SQL Server™ 2000 supports indexes defined on any column in a table, including computed columns.If a table is created with no indexes, the data rows are not stored in any particular order. This structure is called a heap.

The two types of SQL Server indexes are: Clustered

Clustered indexes sort and store the data rows in the table based on their key values. Because the data rows are stored in sorted order on the clustered index key, clustered indexes are efficient for finding rows. There can only be one clustered index per table, because the data rows themselves can only be sorted in one order. The data rows themselves form the lowest level of the clustered index.

The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. If a table has no clustered index, its data rows are stored in a heap.

Nonclustered

Nonclustered indexes have a structure completely separate from the data rows. The lowest rows of a nonclustered index contain the nonclustered index key values and each key value entry has pointers to the data rows containing the key value. The data rows are not stored in order based on the nonclustered key.

The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or are clustered. For a heap, a row locator is a pointer to the row. For a table with a clustered index, the row locator is the clustered index key.

The only time the rows in a table are stored in any specific sequence is when a clustered index is created on the table. The rows are then stored in sequence on the clustered index key. If a table only has nonclustered indexes, its data rows are stored in a unordered heap.Indexes can be unique, which means no two rows can have the same value for the index key. Otherwise, the index is not unique and multiple rows can share the same key value.

There are two ways to define indexes in SQL Server. The CREATE INDEX statement creates and names an index. The CREATE TABLE statement supports the following constraints that create indexes:

Visit: www.gcreddy.net for Testing Information 62

Page 63: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

PRIMARY KEY creates a unique index to enforce the primary key.

UNIQUE creates a unique index. CLUSTERED creates a clustered index. NONCLUSTERED creates a nonclustered index.

This example shows the Transact-SQL syntax for creating indexes on a table.

Visit: www.gcreddy.net for Testing Information 63

USE pubsGOCREATE TABLE emp_sample (emp_id int PRIMARY KEY, emp_name char(50), emp_address char(50), emp_title char(25) UNIQUE )GOCREATE NONCLUSTERED INDEX sample_nonclust ON emp_sample(emp_name)GO

Page 64: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

NORMALIZATION

Normalization is a technique for producing a set of relations with desirable properties, given the data requirements of an enterprise.

The process of normalization is a formal method that identifies relations based on their primary or candidate / foreign keys and the functional dependencies among their attributes.

The Process of Normalization

•Normalization is often executed as a series of steps. Each step corresponds to a specific normal form that has known properties. •As normalization proceeds, the relations become progressively more restricted in format, and also less vulnerable to update anomalies.•For the relational data model, it is important to recognize that it is only first normal form (1NF) that is critical in creating relations. All the subsequent normal forms are optional.

Unnormalized form (UNF)A table that contains one or more repeating groups

ClinetRental

ClientNo

cName propertyNo

pAddress rentStart rentFinish

rent

ownerNo

oName

CR76 Johnkay

PG4

PG16

6 lawrenceSt,Glasgow

5 Novar Dr,Glasgow

1-Jul-00

1-Sep-02

31-Aug-01

1-Sep-02

350

450

CO40

CO93

Tina Murphy

Tony Shaw

CR56 Aline PG4 6 lawrence 1-Sep-99 10-Jun-00 350 CO40 Tina

Visit: www.gcreddy.net for Testing Information 64

Page 65: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Stewart

PG36

PG16

St,Glasgow

2 Manor Rd,Glasgow

5 Novar Dr,Glasgow

10-Oct-00

1-Nov-02

1-Dec-01

1-Aug-03370

450

CO93

CO93

Murphy

Tony Shaw

Tony Shaw

Repeating group = (propertyNo, pAddress, rentStart, rentFinish, rent, ownerNo, oName)

Definition of 1NF

First Normal Form is a relation in which the intersection of each row and column contains one and only one value.

There are two approaches to removing repeating groups from unnormalized tables:1.Removes the repeating groups by entering appropriate data in the empty columns of rows containing the repeating data.

2. Removes the repeating group by placing the repeating data, along with a copy of the original key attribute(s), in a separate relation. A primary key is identified for the new relation

1NF ClientRental relation with the first approach

With the first approach, we remove the repeating group (property rented details) by entering the appropriate client data into each row.

The ClientRental relation is defined as follows:

ClientRental ( clientNo, propertyNo, cName, pAddress, rentStart, rentFinish, rent, ownerNo, oName)

ClientRental:

ClientNo

propertyNo

cName pAddress rentStart rentFinish

rent

ownerNo

oName

CR76 PG4 JohnKay

6 lawrenceSt,Glasgow

1-Jul-00 31-Aug-01

350 CO40 Tina Murphy

CR76 PG16 JohnKay

5 Novar Dr,Glasgow

1-Sep-02 1-Sep-02 450 CO93 Tony Shaw

CR56 PG4 AlineStewart

6 lawrenceSt,Glasgow

1-Sep-99 10-Jun-00 350 CO40 Tina Murphy

Visit: www.gcreddy.net for Testing Information 65

Page 66: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

CR56 PG36 AlineStewart

2 Manor Rd,Glasgow

10-Oct-00

1-Dec-01 370 CO93 Tony Shaw

CR56 PG16 AlineStewart

5 Novar Dr,Glasgow

1-Nov-02

1-Aug-03 450 CO93 Tony Shaw

1NF ClientRental relation with the second approach

With the second approach, we remove the repeating group (property rented details) by placing the repeating data along with a copy of the original key attribute (clientNo) in a separte relation.

Client (clientNo, cName)PropertyRentalOwner (clientNo, propertyNo, pAddress, rentStart,rentFinish, rent, ownerNo, oName)

Client:

ClientNo CnameCR76 John KayCR56 Aline Stewart

PropertyRentalOwner:

ClientNo

propertyNo

pAddress rentStart rentFinish rent ownerNo

oName

CR76 PG4 6 lawrenceSt,Glasgow

1-Jul-00 31-Aug-01 350 CO40 Tina Murphy

CR76 PG16 5 Novar Dr,Glasgow

1-Sep-02 1-Sep-02 450 CO93 Tony Shaw

CR56 PG4 6 lawrenceSt,Glasgow

1-Sep-99 10-Jun-00 350 CO40 Tina Murphy

CR56 PG36 2 Manor Rd,Glasgow

10-Oct-00

1-Dec-01 370 CO93 Tony Shaw

CR56 PG16 5 Novar Dr,Glasgow

1-Nov-02 1-Aug-03 450 CO93 Tony Shaw

Visit: www.gcreddy.net for Testing Information 66

Page 67: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Second Normal Form (2NF)

Second normal form (2NF) is a relation that is in first normal form and every non-primary-key attribute is fully functionally dependent on the primary key.The normalization of 1NF relations to 2NF involves the removal of partial dependencies. If a partial dependency exists, we remove the function dependent attributes from the relation by placing them in a new relation along with a copy of their determinant.

The ClientRental relation has the following functional dependencies:

fd1 clientNo, propertyNo & rentStart, rentFinish (Primary Key)fd2 clientNo & cName (Partial dependency)fd3 propertyNo & pAddress, rent, ownerNo, oName (Partial dependency)fd4 ownerNo & oName (Transitive Dependency)fd5 clientNo, rentStart & propertyNo, pAddress, rentFinish, rent, ownerNo, oName

(Candidate key)fd6 propertyNo, rentStart & clientNo, cName, rentFinish (Candidate key)

2NF ClientRental relation

After removing the partial dependencies, the creation of the three new relations called Client, Rental, and PropertyOwnerClient (clientNo, cName)Rental (clientNo, propertyNo, rentStart, rentFinish)PropertyOwner (propertyNo, pAddress, rent, ownerNo, oName)

Client: Rental:

ClientNo Property

No

renStart renFinish

CR76 PG4 1-Jul-00 31-Aug-01CR76 PG16 1-Sep-02 1-Sep-02CR56 PG4 1-Sep-99 10-Jun-00CR56 PG36 10-Oct-00 1-Dec-01CR56 PG16 1-Nov-02 1-Aug-03PropertyOwner:

propertyNo pAddress rent ownerNo oName

Visit: www.gcreddy.net for Testing Information

ClientNo CnameCR76 John KayCR56 Aline Stewart

67

Page 68: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

PG4 6 lawrence St,Glasgow 350 CO40 Tina MurphyPG16 5 Novar Dr, Glasgow 450 CO93 Tony ShawPG36 2 Manor Rd, Glasgow 370 CO93 Tony Shaw

Third Normal Form (3NF)

A relation that is in first and second normal form, and in which no non-primary-key attribute is transitively dependent on the primary key.

Transitive dependency: A condition where A, B, and C are attributes of a relation such that if A & B and B & C, then C is transitively dependent on A via B (provided that A is not functionally dependent on B or C).The normalization of 2NF relations to 3NF involves the removal of transitive dependencies by placing the attribute(s) in a new relation along with a copy of the determinant.

The functional dependencies for the Client, Rental and PropertyOwner relations are as follows:Clientfd2 clientNo & cName (Primary Key)

Rentalfd1 clientNo, propertyNo & rentStart, rentFinish (Primary Key)fd5 clientNo, rentStart & propertyNo, rentFinish (Candidate key)fd6 propertyNo, rentStart & clientNo, rentFinish (Candidate key)PropertyOwnerfd3 propertyNo & pAddress, rent, ownerNo, oName (Primary Key)fd4 ownerNo & oName (Transitive Dependency)

3NF ClientRental relation

The resulting 3NF relations have the forms:Client (clientNo, cName)Rental (clientNo, propertyNo, rentStart, rentFinish)PropertyOwner (propertyNo, pAddress, rent, ownerNo)Owner (ownerNo, oName)

Client: Rental:

ClientNo Property

No

renStart renFinish

CR76 PG4 1-Jul-00 31-Aug-01CR76 PG16 1-Sep-02 1-Sep-02CR56 PG4 1-Sep-99 10-Jun-00CR56 PG36 10-Oct-00 1-Dec-01CR56 PG16 1-Nov-02 1-Aug-03

Visit: www.gcreddy.net for Testing Information

ClientNo CnameCR76 John KayCR56 Aline Stewart

68

Page 69: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

PropertyOwner: Owner:

OwnerNo ownerNameCO40 Tina MurphyCO93 Tony Shaw

Boyce-Codd normal form (BCNF)

A relation is in BCNF, if and only if, every determinant is a candidate key. The difference between 3NF and BCNF is that for a functional dependency A à B, 3NF allows this dependency in a relation if B is a primary-key attribute and A is not a candidate key, whereas BCNF insists that for this dependency to remain in arelation, A must be a candidate key.

Example of BCNFfd1 clientNo, interviewDate à interviewTime, staffNo, roomNo (Primary Key)fd2 staffNo, interviewDate, interviewTimeà clientNo (Candidate key)fd3 roomNo, interviewDate, interviewTime à clientNo, staffNo (Candidate key)fd4 staffNo, interviewDate à roomNo (not a candidate key)As a consequece the ClientInterview relation may suffer from update anmalies.For example, two tuples have to be updated if the roomNo need be changed for staffNo SG5 on the 13-May-02.Client inerview

ClientNo InterviewDate InterviewTime StaffNo RoomNoCR76 13-May-02 10.30 SG5 G101CR76 13-May-02 12.00 SG5 G101CR74 13-May-02 12.00 SG37 G102CR56 1-Jul-02 10.30 SG5 G102

Example of BCNF(2)

Visit: www.gcreddy.net for Testing Information

propertyNo

pAddress rent ownerNo

PG4 6 lawrence St,Glasgow 350 CO40PG16 5 Novar Dr, Glasgow 450 CO93PG36 2 Manor Rd, Glasgow 370 CO93

69

Page 70: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

To transform the ClientInterview relation to BCNF, we must remove the violating functional dependency by creating two new relations called Interview and SatffRoom as shown below,Interview (clientNo, interviewDate, interviewTime, staffNo)StaffRoom(staffNo, interviewDate, roomNo)

interview

staffroom

Fourth Normal Form (4NF)

A relation that is in Boyce-Codd normal form and contains no nontrivial multi-valued dependencies.Multi-valued dependency (MVD)

It represents a dependency between attributes (for example, A, B and C) in a relation, such that for each value of A there is a set of values for B and a set of value for C. However, the set of values for B and C are independent of each other.

A multi-valued dependency can be further defined as being trivial or nontrivial. A MVD A à> B in relation R is defined as being trivial if • B is a subset of A or• A U B = R A MVD is defined as being nontrivial if neither of the above two conditions is satisfied.Fifth Normal Form (5NF)A relation that has no join dependency.

Lossless-join dependencyA property of decomposition, which ensures that no spurious tuples are generated when relations are reunited through a natural join operation.

Visit: www.gcreddy.net for Testing Information 70

SG5SG37SG5SG5staffNo

10.301-Jul-02CR5612.0013-May-02CR74

10.3013-May-02CR7612.0013-May-02CR76

interviewTimeinterviewDateClientNo

SG5SG37SG5staffNo

G1021-Jul-02G10213-May-02G10113-May-02roomNointerviewDate

Page 71: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Join dependencyDescribes a type of dependency. For example, for a relation R with subsets of the attributes of R denoted as A, B, …, Z, a relation R satisfies a join dependency if, and only if, every legal value of R is equal to the join of its projections on A, B, …, Z.

T-SQL Programming

T-SQL stands for TRANSACT-SQL. It is a programming language, which can be used to develop logic on the database.

Local Variables:

A local variable can be created by using the DECLARE statement. An initial value can be assigned to the variable with the help of the SELECT statement and can be used within the trigger or procedure where it is created or assigned the value.

The syntax is:

Example:

Initializing Variables:

We can make use of either SELECT or SET statements to initialize variables.

Syntax:

Example:

Global Variables:

Global variables are pre-defined and maintained by the system. The server to track server-wide and session-specific information uses them. They cannot be explicitly set or declared. Global variables cannot be defined by users and are not

Visit: www.gcreddy.net for Testing Information 71

DECLARE @variable_name data_type [, @variable_name data_type]

DECLARE @name variable char (20)DECLARE @age int

SELECT @varname=value (or)SET @varname=value

SELECT @name_variable=’AKINOVA KURENDIOL’, @age=22

Page 72: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

used to pass information across processors by applications. Many of the global variables report on system activity since the last time SQL server was started; other report information about a connection.

Some common global variables are:

Global Variable

Description

@@rowcount Returns the number of rows processed by preceding command.@@error Returns the error number of the last error generated.@@trancount Returns the transaction nesting level status.@@servername Returns the name of the local SQL server.@@version Returns the version of the SQL server using.@@spid Returns the current process ID.@@identity Returns the last identity value used in an insert.@@nestlevel Returns the number of level nested in a stored procedure/trigger.@@sqlstatus Returns the status of the previous fetch statement in cursor.

PRINT StatementThe PRINT statement is used to pass a message to the client program’s message handler. It is used to display user-defined messages.

The syntax is:

The message to be displayed using PRINT statement can be up to 255 characters long.

CONTROL-OF-FLOW LANGUAGE:

BEGIN…END

When series of statements need to be executed it is better to enclose them in blocks. SQL server provides the BEGIN…END block for this purpose and the statements enclosed between BEGIN and END block are known as statement block. Statement blocks are used with IF…ELSE and WHILE control –of-flow language. If BEGIN and END

Visit: www.gcreddy.net for Testing Information 72

PRINT character_string|@local_variable|@@global_variable

DECLARE @myname char(20)SELECT @myname=’JOJO ALAMENTO’SELECT ‘My Name is’ + @mynamePRINT @myname

GO

Page 73: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

are not used, only the first statement that immediately follows IF…ELSE or WHILE is executed.

The command syntax is:

IF…ELSE Block

Statements to be executed conditionally are identified with the IF…ELSE construct. The IF…ELSE block allows a statement or statement block to be executed when a condition is TRUE or FALSE.

The command syntax is:

IF…ELSE constructs acan be used in batches, in stored procedures and in ad hoc queries. IF tests can be nested, either after another IF or following and ELSE. There is no limit to the number of nesting levels.

Consider the following example:

CASE CONSTRUCT

In situations where you need a large number of IF statements, SQL Server provides a CASE statement. The CASE statement enables multiple possible conditions to be managed within a SELECT statement.

The syntax is:

Visit: www.gcreddy.net for Testing Information 73

BEGIN{sql_statement | statement_block}

END

IF Boolean_expression{sql_staement | statement_block}

[ELSE Boolean_expression{sql_statement | statement_block}]

USE pubsIF (SELECT SUM(price) FROM titles WHERE type=’business’) < 600BEGIN

PRINT ‘ the sum of the following BUSINESS books is less than 60 Dollars’PRINT ‘’FROM titlesWHERE type=’business’

END

CASEWHEN Boolean_expression THEN expression1[[WHEN Boolean_expression THEN expression][..][ELSE expression]

END

Page 74: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Example:

WHILE CONSTRUCT

The WHILE construct is useful when repeated execution of SQL statements(s) is required. The statements are executed repeatedly as long as the specified condition is true.

SQL Server provides BREAK and CONTINUE statements to control the loop from inside of the WHILE construct.

The command syntax is:

Visit: www.gcreddy.net for Testing Information 74

SELECT type=CASE type

WHEN ‘BUSINESS’ THEN ‘BUSINESS BOOK’WHEN ‘mad_cook’ THEN ‘MODERN COOKING’WHEN ‘trad_cook’ THEN ‘TRADITIONAL COOKING’WHEN ‘psychology’ THEN ‘PSYCHOLOGY BOOK’ELSE ‘No category assigned as yet’

END‘Average Price’=AVG(price)‘Average Advance=AVG (advance)

FROM titlesWHERE title_id LIKE ‘bu%” OR title_id LIKE ‘MC% OR title_id LIKE ‘PC%’ OR title_id LIKE ‘PS%’

GROUP BY type.

WHILE Boolean_expression{sql_statement | statement_block}[BREAK]{sql_statement | statement_block}[CONTINUE]

Example:

WHILE (SELECT AVG (price) FROM titles) < $60BEGIN

SELECT title FROM titlesIF (SELECT MAX (price) FROM titles) > $30

BREAKELSE

CONTINUEEND

Page 75: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

STORED PROCEDURES

A stored procedure is a group of Transact-SQL statements compiled into a single execution plan.

Stored procedures in SQL Server are similar to procedures in other programming languages in that they can:

Accept input parameters and return multiple values in the form of output parameters to the calling procedure or batch.

Contain programming statements that perform operations in the database, including calling other procedures.

Return a status value to a calling procedure or batch to indicate success or failure (and the reason for failure).

You can use the Transact-SQL EXECUTE statement to run a stored procedure. Stored procedures are different from functions in that they do not return values in place of their names and they cannot be used directly in an expression.

The benefits of using stored procedures in SQL Server rather than Transact-SQL programs stored locally on client computers are:

They allow modular programming. They allow faster execution. They can reduce network traffic. They can be used as a security mechanism.

Stored Procedures supported by SQL Server:

SQL Server supports five types of stored procedures. They are:

System Stored Procedures (sp_)

Many administrative and informational activities SQL Server can be performed through system stored procedures. These system stored procedures are stored in the Master database and are identified by the sp_prefix. They can be executed from any database.

Local Stored Procedures

These procedures will be created in the user database. The user who creates the procedure will become the owner for that procedure.

Temporary Stored Procedures

Temporary stored procedures are stored in tempdb database. They can be used in the case where an application builds dynamic Transact-SQL statements that

Visit: www.gcreddy.net for Testing Information 75

Page 76: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

are executed several times. Instead of recompiling the T-SQL statements each time, a temporary stored procedure can be created and compiled on the first execution, then execute the precompiled plan multiple times. The temporary stored procedures can be local or global.

Remote Stored Procedures

They are legacy feature of SQL Server. Their functionality in T-SQL is limited to executing a stored procedure on a remote SQL Server installation. The distributed queries in SQL Server support this ability along with the ability to access tables on linked OLEDB data sources directly from local T_SQL statements.

Extended Stored Procedures

These are dynamic link libraries (DLLs) that SQL Server can dynamically load and execute. These procedures run directly in the address space of SQL Server and are programmed using the SQL Server Open Data Services API. They are identified by the xp_prefix.

Creating a Stored Procedure

The stored procedures can be created using the CREATE PROCEDURE statement.

Syntax:

Example: creating a procedure to insert values into emp table.

Ex: Executing the Procedure:

Visit: www.gcreddy.net for Testing Information 76

CREATE PROCEDURE procedure_name [( @parameter1 data_type [OUTPUT] [, @parameter2 …..])]AS

SQL-Statements

Create procedure empInsert(@eid Char,@en varchar(10),@dno int,@grd char(1),@bsal numeric(9,2),@dj datetime)ASBegin

INSERT INTO emp VALUES(@eid,@en,@dno,@grd,@bsal,@dj)end

EXEC empInsert E001,’sam’,10,’B’,4500,’11/3/96’

Page 77: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

TRIGGERS

A trigger is a special type of stored procedure that automatically takes effect when the data in a specified table is modified. Triggers are invoked in response to an INSERT, UPDATE, or DELETE statement. A trigger can query other tables and can include complex Transact-SQL statements. The trigger and the statement that fires it are treated as a single transaction, which can be rolled back from within the trigger. If a severe error is detected (for example, insufficient disk space), the entire transaction automatically rolls back.

Triggers are useful in these ways:

Triggers can cascade changes through related tables in the database; however, these changes can be executed more efficiently using cascading referential integrity constraints.

Triggers can enforce restrictions that are more complex than those defined with CHECK constraints.

Unlike CHECK constraints, triggers can reference columns in other tables. For example, a trigger can use a SELECT from another table to compare to the inserted or updated data and to perform additional actions, such as modify the data or display a user-defined error message.

Triggers can also evaluate the state of a table before and after a data modification and take action(s) based on that difference.

Multiple triggers of the same type (INSERT, UPDATE, or DELETE) on a table allow multiple, different actions to take place in response to the same modification statement.

Creating a Trigger:

Visit: www.gcreddy.net for Testing Information 77

CREATE TRIGGER trigger_name ON { table | view } {     { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] }         AS                 sql_statement [ ...n ]     } }

Page 78: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

You can use the FOR clause to specify when a trigger is executed:

AFTER

The trigger executes after the statement that triggered it completes. If the statement fails with an error, such as a constraint violation or syntax error, the trigger is not executed. AFTER triggers cannot be specified for views, they can only be specified for tables. You can specify multiple AFTER triggers for each triggering action (INSERT, UPDATE, or DELETE). If you have multiple AFTER triggers for a table, you can use sp_settriggerorder to define which AFTER trigger fires first and which fires last. All other AFTER triggers besides the first and last fire in an undefined order which you cannot control.

AFTER is the default in SQL Server 2000. You could not specify AFTER or INSTEAD OF in SQL Server version 7.0 or earlier, all triggers in those versions operated as AFTER triggers.

INSTEAD OF

The trigger executes in place of the triggering action. INSTEAD OF triggers can be specified on both tables and views. You can define only one INSTEAD OF trigger for each triggering action (INSERT, UPDATE, and DELETE). INSTEAD OF triggers can be used to perform enhance integrity checks on the data values supplied in INSERT and UPDATE statements. INSTEAD OF triggers also let you specify actions that allow views, which would normally not support updates, to be updatable.

Triggers Compared to Constraints

Constraints and triggers each have benefits that make them useful in special situations. The primary benefit of triggers is that they can contain complex processing logic that uses Transact-SQL code. Therefore, triggers can support all of the functionality of constraints; however, triggers are not always the best method for a given feature.

Entity integrity should always be enforced at the lowest level by indexes that are part of PRIMARY KEY and UNIQUE constraints or are created independently of constraints. Domain integrity should be enforced through CHECK constraints, and referential integrity (RI) should be enforced through FOREIGN KEY constraints, assuming their features meet the functional needs of the application.

Triggers are most useful when the features supported by constraints cannot meet the functional needs of the application. For example:

FOREIGN KEY constraints can validate a column value only with an exact match to a value in another column, unless the REFERENCES clause defines a cascading referential action.

A CHECK constraint can validate a column value only against a logical expression or another column in the same table. If your application requires that a column value be validated against a column in another table, you must use a trigger.

Visit: www.gcreddy.net for Testing Information 78

Page 79: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Constraints can communicate about errors only through standardized system error messages. If your application requires (or can benefit from) customized messages and more complex error handling, you must use a trigger.

Triggers can cascade changes through related tables in the database; however, these changes can be executed more efficiently through cascading referential integrity constraints.

Triggers can disallow or roll back changes that violate referential integrity, thereby canceling the attempted data modification. Such a trigger might go into effect when you change a foreign key and the new value does not match its primary key.

If constraints exist on the trigger table, they are checked after the INSTEAD OF trigger execution but prior to the AFTER trigger execution. If the constraints are violated, the INSTEAD OF trigger actions are rolled back and the AFTER trigger is not executed.

Example:While entering the details of a new employee, the salary has to be entered

according to the grade. If the grade it changed, the basic salary should also be changed accordingly. Instead of manually doing this, the HR manager wanted the basic salary of the employees to be entered automatically whenever an employee is added or grade is changed.

Solution: Create sal_info and emp tables as follows.

Insert some values into the sal_info table:

Now, create the emp table as follows:

Now, create the required trigger as follows:

Visit: www.gcreddy.net for Testing Information 79

CREATE TABLE sal_info(grade char(1), bsal numeric(18,0))

INSERT INTO sal_infoSELECT ‘A’,1000 UNION ALLSELECT ‘B’,2000 UNION ALLSELECT ‘C’,3000

CREATE TABLE emp(emp_no int,emp_name varchar(10),dept_no int,grade char(1),bsal numeric(18,0),doj datetime)

CREATE TRIGGER tr_emp ON empFOR INSERT,UPDATEASDECLARE @sal numeric(18,0)SELECT @sal=sal_info.bsal from sal_info,inserted Where inserted.grade=sal_info.grade

UPDATE emp set bsal=@sal from emp.insertedWhere emp.emp_no=inserted.emp_no

Page 80: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

An insert/update is written for the table emp. Whenever a new record is inserted or updated, the new grade is obtained from the inserted table. The corresponding basic salary is obtained from the table sal_info and the basic salary in the emp table is set to this value.

This trigger can be checked by inserting a record with a null value for the field bsal. When a select statement is given, the value for bsal will also be present.

Altering a Trigger:

The definition of an existing trigger can be altered without dropping it. The altered definition replaces the definition of the existing trigger with the new definition.

Syntax

Example:

This example creates a trigger that prints a user-defined message to the client when a user tries to add or change data in the emp table. Then, the

Visit: www.gcreddy.net for Testing Information 80

INSERT INTO emp VALUES(100,’Arvind’,30,’B’,null,getdate())

SELECT * FROM EMP

Emp_no emp_name dept_no grade bsal doj100 Arvind 30 B 2000 2006-06-15

ALTER TRIGGER trigger_name ON { table | view } {     { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] }         AS                 sql_statement [ ...n ]     } }

Page 81: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

trigger is altered using ALTER TRIGGER to apply the trigger only on INSERT activates. This trigger is helpful because it reminds the user who updates or inserts rows into this table.

Dropping a Trigger:

A trigger can be dropped by using, DROP TRIGGER statement. A trigger gets dropped automatically when its associated table is dropped. Permissions to drop a trigger defaults to the table owner. But the members of the system administrators(sysadmin) and the database owner(db_owner) can drop any object by specifying the owner in the DROP TRIGGER statement.

Syntax:

Disabling or Enabling a Trigger:

Triggers can be enabled or disabled using ALTER TABLE statement. On disabling a trigger, the actions in the trigger are not performed until the trigger is re-enabled.

Syntax:

USER DEFINED FUNCTIONS

A User-Defined Function is, much like a Stored Procedure, an ordered set of T-SQL statements that are pre-optimized and compiled and can be called to work as a single unit. The primary difference between them is how results are retuned.

With a Stored Procedure, you can pas parameters in, and also get values in parameters passed back out. You can return a value, but that value is really intended to indicate success or failure rather than return data. You can also return result sets,

Visit: www.gcreddy.net for Testing Information 81

CREATE TRIGGER trig1ON empWITH ENCRYPTIONFOR INSERT, UPDATEAS RAISERROR(40008,16,10)

ALTER TRIGGER trig1ON empFOR INSERTAS RAISERROR(40008,16,10)

DROP TRIGGER trigger_name

ALTER TABLE table_name{ENABLE | DISABLE } TRIGGER{ALL | trigger_name[, --n]

Page 82: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

but you can’t really use those result sets in a query without first inserting them into some kind of table (usually a temporary table) to work with them further.

With a UDF, however, you can pass parameters in, but not out. Instead, the concept of output parameters has been replaced with a much more robust return value. As with system functions, you can return a scalar value. Another advantage is that this value is not limited to just the integer data type as it would be for a Stored Procedure. Instead, you can return most SQL Server data types.

Types of UDF’s:

Those that return a scalar value Those that return a table

General Syntax for creating a UDF:

UDFs Returning a Scalar Value:

Much like SQL Server’s own built-in functions, they will return a scalar value to the calling script or procedure. One of the truly great things about a UDF is that you are not limited to an integer for a return value – instead, it can be of any valid SQL Server data type, except for BLOBs, cursors, and timestamps. Even if you wanted to return an integer, a UDF should be advantage to you for two different reasons:

1. Unlike Stored Procedures, the whole purpose of the return value is to serve a meaningful piece of data – for Stored Procedures, a return value is meant as an indication of success or failure, and, in the event of failure, to provide some specific information about the nature of that failure.

2. You can perform functions in-line to your queries (for instances, include it as part of your SELECT statement) – you can’t do that with a Stored Procedure.

Case study:

Let’s create a table called ORDERS with 3 columns named as OrderID, CustID and OrderDate as follows

Visit: www.gcreddy.net for Testing Information 82

CREATE FUNCTION function_name(<@parameter name> <data type>[=default value>][,……n])RETURNS {<data type>|TABLE}ASBEGIN

[<function statements>]{RETURN <type as defined in RETURNS clause> |RETURN (<SELECT statement>)}

END

CREATE TABLE orders(ordered int, custid int,orderdate datetime)

Page 83: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Lets insert some data into the table with the use of a simple T-SQL program.

So, this gets us 10 rows inserted, with each row being inserted with today’s date, but one minute apart from each other.

So, now we’re ready to run a simple query to see what orders we have today. We might try something like:

Unfortunately, this query will not get us anything back at all. This is because GETDATE() gets the current time not just the day.

The solution is to convert the date to a string and back in order to truncate the time information, then perform comparison.

This time, we will get back every row with today’s date in the OrderDate column – regardless of what time of day the order was taken. Unfortunately, this isn’t exactly the most readable code. Imagine you had a large series of dates you needed to perform such comparisons against – it can get very ugly indeed.

So now let’s look at doing the same thing with a simple user-defined function. First, we’ll need to create the actual function. This is done with the new CREATE FUNCTION command, and it’s formatted much like a Stored Procedure. For example, we might code this function like this:

Visit: www.gcreddy.net for Testing Information 83

DECLARE @Counter int

SET @Counter =1WHILE @Counter <= 10BEGIN

INSERT INTO OrdersVALUES(1,1,DATEADD(mi, @Counter, GETDATE()))

SET @Counter = @Counter + 1END

SELECT *FROM OrdersWHERE orderdate=GETDATE()

SELECT *FROM OrdersWHERE CONVERT(varchar(12), orderdate, 101)=CONVERT(varchar(12), GETDATE(),101)

CREATE FUNCTION dbo.DateOnly(@dt datetime)RETURNS varchar(12)ASBEGIN

RETURN CONVERT(varchar(12), @dt, 101)END

Page 84: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Whether the date returned from GETDATE() is passed in as the parameter and the task of converting the date is included in the function body and the truncated date is returned.

To see this function in action, let’s reformat our query as follows:

We get back the same set as with the stand-alone query. Even for a simple query like this one, the new code is quite a bit more readable. There is, however, one requirement for this type. The owner name is required in the function call. SQL Server will, for some reason, not resolve functions the way it does with other objects.

UDFs that Return a Table:

SQL Server’s new user-defined functions are not limited to just returning scalar values. They can return something far more interesting – tables.

To make the change to using a table, as a return value is not hard at all – a table is just like any other SQL Server data type as far as a UDF is concerned. To illustrate this, we’ll build a relatively simple one:

This function returns a table of SELECTEed records and does a little formatting: joining the last and first names, separating them with a comma, and concatenating the three components to fill the address2 column.

Visit: www.gcreddy.net for Testing Information 84

SELECT *FROM OrdersWHERE dbo.DateOnly(OrderDate) = dbo.DateOnly(GETDATE())

USE pubsGO

CREATE FUNCTION dbo.fnListOfAuthors()RETURNS TABLEASRETURN ( SELECT au_id,

au_lname + ‘, ‘ + au_fname AS au_name,address AS address1,City + ‘, ‘ + state + ‘ ‘ + zip AS address2

FROM authors)GO

Page 85: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

At this point, we’re ready to use our function just as we would use a table – the only exception is that as was discussed with scalar functions, we must use the two-part naming convention:

LOCKS

Microsoft® SQL Server™ 2000 has locking that allows different types of resources to be locked by a transaction. To minimize the cost of locking, SQL Server locks resources automatically at a level appropriate to the task. Locking at a smaller granularity, such as rows, increases concurrency, but has a higher overhead because more locks must be held if many rows are locked. Locking at a larger granularity, such as tables, are expensive in terms of concurrency because locking an entire table restricts access to any part of the table by other transactions, but has a lower overhead because fewer locks are being maintained.

SQL Server can lock these resources (listed in order of increasing granularity).

Resource Description

Visit: www.gcreddy.net for Testing Information 85

SELECT *FROM dbo.fnListOfAuthors()

Page 86: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

RID Row identifier. Used to lock a single row within a table.Key Row lock within an index. Used to protect key ranges in

serializable transactions.Page 8 kilobyte –(KB) data page or index page.Extent Contiguous group of eight data pages or index pages.Table Entire table, including all data and indexes.DB Database.

SQL Server locks resources using different lock modes that determine how the resources can be accessed by concurrent transactions.

SQL Server uses these resource lock modes.

Lock mode DescriptionShared (S) Used for operations that do not change or update data (read-only

operations), such as a SELECT statement.Update (U) Used on resources that can be updated. Prevents a common form

of deadlock that occurs when multiple sessions are reading, locking, and potentially updating resources later.

Exclusive (X) Used for data-modification operations, such as INSERT, UPDATE, or DELETE. Ensures that multiple updates cannot be made to the same resource at the same time.

Intent Used to establish a lock hierarchy. The types of intent locks are: intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).

Schema Used when an operation dependent on the schema of a table is executing. The types of schema locks are: schema modification (Sch-M) and schema stability (Sch-S).

Bulk Update (BU) Used when bulk-copying data into a table and the TABLOCK hint is specified.

Shared Locks

Shared (S) locks allow concurrent transactions to read (SELECT) a resource. No other transactions can modify the data while shared (S) locks exist on the resource. Shared (S) locks on a resource are released as soon as the data has been read, unless the transaction isolation level is set to repeatable read or higher, or a locking hint is used to retain the shared (S) locks for the duration of the transaction.

Update Locks

Visit: www.gcreddy.net for Testing Information 86

Page 87: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Update (U) locks prevent a common form of deadlock. A typical update pattern consists of a transaction reading a record, acquiring a shared (S) lock on the resource (page or row), and then modifying the row, which requires lock conversion to an exclusive (X) lock. If two transactions acquire shared-mode locks on a resource and then attempt to update data concurrently, one transaction attempts the lock conversion to an exclusive (X) lock. The shared-mode-to-exclusive lock conversion must wait because the exclusive lock for one transaction is not compatible with the shared-mode lock of the other transaction; a lock wait occurs. The second transaction attempts to acquire an exclusive (X) lock for its update. Because both transactions are converting to exclusive (X) locks, and they are each waiting for the other transaction to release its shared-mode lock, a deadlock occurs.To avoid this potential deadlock problem, update (U) locks are used. Only one transaction can obtain an update (U) lock to a resource at a time. If a transaction modifies a resource, the update (U) lock is converted to an exclusive (X) lock. Otherwise, the lock is converted to a shared-mode lock.

Exclusive Locks

Exclusive (X) locks prevent access to a resource by concurrent transactions. No other transactions can read or modify data locked with an exclusive (X) lock.

Intent Locks

An intent lock indicates that SQL Server wants to acquire a shared (S) lock or exclusive (X) lock on some of the resources lower down in the hierarchy. For example, a shared intent lock placed at the table level means that a transaction intends on placing shared (S) locks on pages or rows within that table. Setting an intent lock at the table level prevents another transaction from subsequently acquiring an exclusive (X) lock on the table containing that page. Intent locks improve performance because SQL Server examines intent locks only at the table level to determine if a transaction can safely acquire a lock on that table. This removes the requirement to examine every row or page lock on the table to determine if a transaction can lock the entire table.

Intent locks include intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).

Lock mode DescriptionIntent shared (IS) Indicates the intention of a transaction to read some (but not

all) resources lower in the hierarchy by placing S locks on those individual resources.

Intent exclusive (IX) Indicates the intention of a transaction to modify some (but not all) resources lower in the hierarchy by placing X locks on those individual resources. IX is a superset of IS.

Shared with intent Indicates the intention of the transaction to read all of the

Visit: www.gcreddy.net for Testing Information 87

Page 88: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

exclusive (SIX) resources lower in the hierarchy and modify some (but not all) resources lower in the hierarchy by placing IX locks on those individual resources. Concurrent IS locks at the top-level resource are allowed. For example, an SIX lock on a table places an SIX lock on the table (allowing concurrent IS locks), and IX locks on the pages being modified (and X locks on the modified rows). There can be only one SIX lock per resource at one time, preventing updates to the resource made by other transactions, although other transactions can read resources lower in the hierarchy by obtaining IS locks at the table level.

Schema Locks

Schema modification (Sch-M) locks are used when a table data definition language (DDL) operation (such as adding a column or dropping a table) is being performed. Schema stability (Sch-S) locks are used when compiling queries. Schema stability (Sch-S) locks do not block any transactional locks, including exclusive (X) locks. Therefore, other transactions can continue to run while a query is being compiled, including transactions with exclusive (X) locks on a table. However, DDL operations cannot be performed on the table.

Bulk Update Locks

Bulk update (BU) locks are used when bulk copying data into a table and either the TABLOCK hint is specified or the table lock on bulk load table option is set using sp_tableoption. Bulk update (BU) locks allow processes to bulk copy data concurrently into the same table while preventing other processes that are not bulk copying data from accessing the table.

Deadlocking

A deadlock occurs when there is a cyclic dependency between two or more threads for some set of resources. Deadlock is a condition that can occur on any system with multiple threads, not just on a relational database management system. A thread in a multi-threaded system may acquire one or more resources (for example, locks). If the resource being acquired is currently owned by another thread, the first thread may have to wait for the owning thread to release the target resource. The waiting thread is said to have a dependency on the owning thread for that particular resource.If the owning thread wants to acquire another resource that is currently owned by the waiting thread, the situation becomes a deadlock: both threads cannot release the resources they own until their transactions are committed or rolled back, and their transactions cannot be committed or rolled back because they are waiting on resources the other owns. For example, thread T1 running transaction 1 has an exclusive lock on the Supplier table. Thread T2 running transaction 2 obtains an exclusive lock on the Part table, and then wants a lock on the Supplier table.

Visit: www.gcreddy.net for Testing Information 88

Page 89: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Transaction 2 cannot obtain the lock because transaction 1 has it. Transaction 2 is blocked, waiting on transaction 1. Transaction 1 then wants a lock on the Part table, but cannot obtain it because transaction 2 has it locked. The transactions cannot release the locks held until the transaction is committed or rolled back. The transactions cannot commit or roll back because they require a lock held by the other transaction to continue.

TRANSACTIONS

A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties, called the ACID (Atomicity, Consistency, Isolation, and Durability) properties, to qualify as a transaction:

Atomicity

A transaction must be an atomic unit of work; either all of its data modifications are performed, or none of them is performed.

Consistency

When completed, a transaction must leave all data in a consistent state. In a relational database, all rules must be applied to the transaction's modifications to maintain all data integrity. All internal data structures, such as B-tree indexes or doubly-linked lists, must be correct at the end of the transaction.

Visit: www.gcreddy.net for Testing Information 89

Page 90: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Isolation

Modifications made by concurrent transactions must be isolated from the modifications made by any other concurrent transactions. A transaction either sees data in the state it was in before another concurrent transaction modified it, or it sees the data after the second transaction has completed, but it does not see an intermediate state. This is referred to as serializability because it results in the ability to reload the starting data and replay a series of transactions to end up with the data in the same state it was in after the original transactions were performed.

Durability

After a transaction has completed, its effects are permanently in place in the system. The modifications persist even in the event of a system failure.

Controlling Transactions

Applications control transactions mainly by specifying when a transaction starts and ends. This can be specified using either Transact-SQL statements or database API functions. The system must also be able to correctly handle errors that terminate a transaction before it completes.

Transactions are managed at the connection level. When a transaction is started on a connection, all Transact-SQL statements executed on that connection are part of the transaction until the transaction ends.

Starting Transactions

You can start transactions in Microsoft® SQL Server™ as explicit, autocommit, or implicit transactions.

Explicit transactions

Explicitly start a transaction by issuing a BEGIN TRANSACTION statement.

Autocommit transactions

This is the default mode for SQL Server. These transactions will contain only one statement. Each individual Transact-SQL statement is committed when it completes. You do not have to specify any statements to control transactions.

Implicit transactions

Set implicit transaction mode on through either an API function or the Transact-SQL SET IMPLICIT_TRANSACTIONS ON statement. When that transaction is completed

Visit: www.gcreddy.net for Testing Information 90

Page 91: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

either by using COMMIT / ROLLBACK, the next Transact-SQL statement starts a new transaction.

Ending Transactions

You can end transactions with either a COMMIT or ROLLBACK statement.

COMMIT

If a transaction is successful, commit it. A COMMIT statement guarantees all of the transaction's modifications are made a permanent part of the database. A COMMIT also frees resources, such as locks, used by the transaction.

Syntax:

ROLLBACK

If an error occurs in a transaction, or if the user decides to cancel the transaction, then roll the transaction back. A ROLLBACK statement backs out all modifications made in the transaction by returning the data to the state it was in at the start of the transaction. A ROLLBACK also frees resources held by the transaction.

Syntax:

Savepoints

Savepoints offer a mechanism to roll back portions of transactions. You create a savepoint using the SAVE TRANSACTION savepoint_name statement, and then later execute a ROLLBACK TRANSACTION savepoint_name statement to roll back to the savepoint instead of rolling back to the start of a transaction.

Example: Let us suppose emp table contains the following data.

Empid Ename Sal

100 Anil 1500

101 Balu 2000

102 Vivek 3500

Visit: www.gcreddy.net for Testing Information 91

COMMIT TRAN[SACTION] transactionName

ROLLBACK TRAN[SACTION] transactionName [savepointname]

Page 92: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Output: The result for the above program is as given below. each block is the result of select statement.

100 Anil 1500

101 Balu 2000

102 Vivek 3500

100 Anil 1500

101 Balu 2000

100 Anil 1500

101 Balu 4000

100 Anil 1500

101 Balu 2000

100 Anil 1500

101 Balu 2000

102 Vivek 3500

Errors During Transaction Processing

If a severe error prevents the successful completion of a transaction, SQL Server automatically rolls back the transaction and frees all resources held by the transaction. If the client's network connection to SQL Server is broken, any outstanding transactions for the connection are rolled back when the network notifies SQL Server of the break. If the client application fails or if the client computer goes down or is restarted, this also breaks the connection, and SQL Server rolls back any

Visit: www.gcreddy.net for Testing Information 92

1. BEGIN TRAN2. SELECT * FROM emp3. DELETE FROM emp WHERE empid=1024. SELECT * FROM emp5. SAVE TRAN sp16. UPDATE emp SET sal=4000 WHERE empid=1017. SELECT * FROM emp8. ROLLBACK TRAN sp19. SELECT * FROM emp10. ROLLBACK TRAN11.SELECT * FROM emp

Page 93: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

outstanding connections when the network notifies it of the break. If the client logs off the application, any outstanding transactions are rolled back.

If a run-time statement error (such as a constraint violation) occurs in a batch, the default behavior in SQL Server is to roll back only the statement that generated the error. You can change this behavior using the SET XACT_ABORT statement. After SET XACT_ABORT ON is executed, any run-time statement error causes an automatic rollback of the current transaction. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT.

SQL Server Security

SQL Server validates users at two levels of security on database user accounts and roles.

Login Authentication Permissions Validation

The authentication stage identifies the user using a login account and verifies only the ability to connect with SQL Server. If the authentication is successful, the user is connected to SQL Server. The user then needs permissions to access database on the server, which is done by using an account in each database, mapped to the user login.

Visit: www.gcreddy.net for Testing Information 93

Page 94: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

The permission validation stage controls the activities the user is allowed to perform in the SQL Server database.

Login Authentication:

A user must have a login account to connect to SQL Server. SQL Server provides two types of Login Authentications.

Windows NT Authentication SQL Server Authentication

Windows NT Authentication

When using Windows NT Authentication, the user is not required to specify a login ID or password to connect to SQL Server. The user’s access to SQL Server is controlled by the Windows NT account, which is authenticated when he/she logs on to the Windows Operating System.

SQL Server Authentication

When using SQL Server authentication, the users must supply the SQL Server login and password to connect to SQL Server. The users are identified in SQL Server by their SQL Server login.

Authentication Mode:

SQL Server can operate in two security modes:

Windows NT Authentication Mode: Only Windows NT Authentication is allowed. Users cannot specify SQL Server Authentication.

Mixed Mode: It allows users to connect to SQL Server using Windows NT Authentication or SQL Server Authentication.

Create a User Login:

Expand the server Expand security Right click on “Logins” and select “New Login…”

Visit: www.gcreddy.net for Testing Information 94

Page 95: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

In the window displayed enter a name to the user under Name Textbox Click the SQL Server Authentication option button to provide the password Enter a password for the user login Click “OK”

A window called Confirm Password will be displayed. In the enter the password again

Click “OK”

Visit: www.gcreddy.net for Testing Information 95

Page 96: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Providing access to a database for a user:

Right click on the login name and select properties

In the window displayed click on “Database Access” tab Make a check mark on the database for which the access has to be given. Click “OK”

Visit: www.gcreddy.net for Testing Information 96

Page 97: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Granting Permissions on a table:

Right click on table name and select “Properties” In the window displayed click on “Permissions” In the window displayed make a check mark in the required action to give

permission to that action for the user on that table.

Visit: www.gcreddy.net for Testing Information 97

Page 98: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

BACKING UP AND RESTORING DATABASES

The backup and restore component of Microsoft® SQL Server™ 2000 provides an important safeguard for protecting critical data stored in SQL Server databases.

With proper planning, you can recover from many failures, including:

Media failure.

User errors. Permanent loss of a server.

Additionally, backing up and restoring databases is useful for other purposes, such as copying a database from one server to another. By backing up a database from one computer and restoring the database to another, a copy of a database can be made quickly and easily.

Using the Enterprise Manager to take backup of database:

1. Open the Enterprise Manager tool from the start menu.2. Expand the server group, the corresponding server, and the database.

3. Right click on the corresponding database and choose All Tasks -> Backup Database…

Visit: www.gcreddy.net for Testing Information 98

Page 99: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

4. In the window displayed click on ADD button.

5. Specify the path and filename by clicking on the browse button.

6. click OK.

Recovering Database :

1. Open Enterprise Manager Tool2. Create a database for backup copy to be restored.3. Right click on the newly created database and choose All Tasks Restore

Database…

Visit: www.gcreddy.net for Testing Information 99

Page 100: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

4. In the window displayed click the drop down button of “Show backups of database” and select the database name that is to be restored.

5. Click on “Options” tab and make a check marks on “force restore over existing datbase”.

Visit: www.gcreddy.net for Testing Information 100

Page 101: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

6. Cick ok. If we successfully restored the database into the new database, we will get the following message.

Visit: www.gcreddy.net for Testing Information 101

Page 102: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

What's New in SQL Server 2005

Enterprise Data Management

In today's connected world, data and the systems that manage that data must always be secure yet available to your users. With SQL Server 2005, users and information technology (IT) professionals across your organization will benefit from reduced application downtime, increased scalability and performance, and tight yet flexible security controls. SQL Server 2005 also includes many new and improved capabilities to help make your IT staff more productive. SQL Server 2005 includes key enhancements to enterprise data management in the following areas:

•Manageability

•Availability

•Scalability

•Security

Manageability

SQL Server 2005 makes it simpler and easier to deploy, manage, and optimize enterprise data and analytical applications. As an enterprise data management platform, it provides a single management console that enables data administrators anywhere in your organization to monitor, manage, and tune all of the databases and associated services across your enterprise. It provides an extensible management infrastructure that can be easily programmed using SQL Management Objects, enabling users to customize and extend their management environment and independent software vendors (ISVs) to build additional tools and functionality to further extend the capabilities that come out of the box.

SQL Server Management Studio

SQL Server 2005 simplifies management by providing one integrated management console to monitor and manage the SQL Server relational database, as well as Integration Services, Analysis Services, Reporting Services, Notification Services, and SQL Server Mobile Edition across large numbers of distributed servers and databases. Database

Visit: www.gcreddy.net for Testing Information 102

Page 103: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

administrators can perform several tasks at the same time, such as authoring and executing a query, viewing server objects, managing an object, monitoring system activity, and viewing online help. SQL Server Management Studio hosts a development environment for authoring, editing, and managing scripts and stored procedures using Transact-SQL, Multidimensional Expressions, XML for Analysis, and SQL Server Mobile Edition. Management Studio is readily integrated with source control. Management Studio also hosts tools for scheduling SQL Server Agent jobs and managing maintenance plans to automate daily maintenance and operation tasks. The integration of management and authoring in a single tool coupled with the ability to manage all types of servers provides enhanced productivity for database administrators.

SQL Server 2005 exposes more than 70 new measures of internal database performance and resource usage, ranging from memory, locking, and scheduling to transactions and network and disk I/O. These Dynamic Management Views (DMVs) provide greater transparency and visibility into the database and a powerful infrastructure for proactive monitoring of database health and performance.

SQL Management Objects

SQL Management Objects (SMO) is a new set of programming objects that exposes all of the management functionality of the SQL Server database. In fact, Management Studio was built with SQL Management Objects. SMO is implemented as a Microsoft .NET Framework assembly. You can use SMO to automate common SQL Server administrative tasks, such as programmatically retrieving configuration settings, creating new databases, applying Transact-SQL scripts, creating SQL Server Agent jobs, and scheduling backups. The SMO object model is a more secure, reliable, and scalable replacement for Distributed Management Objects (DMO), which was included with earlier versions of SQL Server.

Availability

Investments in high-availability technologies, additional backup and restore capabilities, and replication enhancements will enable enterprises to build and deploy highly available applications. Innovative high-availability features such as database mirroring, failover clustering, database snapshots, and enhanced online operations will minimize downtime and help to ensure that critical

Visit: www.gcreddy.net for Testing Information 103

Page 104: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

enterprise systems remain accessible. This section reviews these enhancements in greater detail.

Database Mirroring

Database mirroring allows continuous streaming of the transaction log from a source server to a single destination server. In the event of a failure of the primary system, applications can immediately reconnect to the database on the secondary server. The secondary instance detects failure of the primary server within seconds and accepts database connections immediately. Database mirroring works on standard server hardware and requires no special storage or controllers. Figure 1 shows the basic configuration of database mirroring.

Figure 1: Basic Configuration of Database MirroringFailover Clustering

Failover clustering is a high-availability solution that exploits Microsoft Windows Clustering Services to create fault-tolerant virtual servers that provide fast failover in the event of a database server failure. In SQL Server 2005, support for failover clustering has been extended to SQL Server Analysis Services, Notification Services, and SQL Server replication. The maximum number of cluster nodes has been increased to eight. SQL Server failover clustering is now a complete fault-tolerant server solution.

Availability Feature Database Mirroring

Failover Clustering

Automatic Failover Yes Yes

Visit: www.gcreddy.net for Testing Information 104

Page 105: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Availability Feature Database Mirroring

Failover Clustering

Transparent Client Redirection Yes, auto-redirect Yes, reconnect to same IP

Impact on Overall Throughput No impact to minimal No impact

Zero Work Loss Yes Yes

Requires Certified Hardware No Yes

Provides Redundant Data Yes No

Database Snapshots

SQL Server 2005 introduces the ability for database administrators to create instant, read-only views of a database. This database snapshot provides a stable view without the time or storage overhead of creating a complete copy of the database. As the primary database diverges from the snapshot, the snapshot adds its own copy of pages as they are modified. As a result, the snapshot may be used to quickly recover from an accidental change to a database by simply reapplying the original pages from the snapshot to the primary database.

Fast Recovery

SQL Server 2005 improves the availability of SQL Server databases with a new and faster recovery option. Users can reconnect to a recovering database after the transaction log has been rolled forward. Earlier versions of SQL Server required users to wait until incomplete transactions had rolled back, even if the users did not need to access the affected parts of the database.

Dedicated Administrator Connection

SQL Server 2005 introduces a dedicated administrator connection to access a running server even if the server is not responding or is otherwise unavailable. This allows you to execute diagnostic functions or Transact-SQL statements so you can troubleshoot problems on a server. The connection is activated by members of the sysadmin fixed server role and is only available through the SQLCMD command prompt tool either locally or from a remote computer.

Online Operations (Index Operations and Restore)

The ability to create, rebuild, or drop an index online is an enhanced feature of SQL Server 2005 that augments the indexing capabilities of earlier versions of SQL Server. The online index option allows

Visit: www.gcreddy.net for Testing Information 105

Page 106: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

concurrent modifications (updates, deletes, and inserts) to the underlying table or clustered index data and any associated indexes during index data definition language (DDL) execution. With support for online index operations, you can add indexes without interfering with access to tables or other existing indexes. Additionally, the server workload allows index operations to take advantage of parallel processing. SQL Server 2005 also introduces the ability to perform a restore operation while an instance of SQL Server is running. Online restoration capabilities improve the availability of SQL Server because only the data that is being restored is unavailable. The rest of the database remains online and available. Earlier versions of SQL Server require that you bring a database offline before you restore the database.

Replication

Replication is designed to increase data availability by distributing the data across multiple database servers. Availability is increased by allowing applications to scale out the SQL Server read workload across databases. SQL Server 2005 offers enhanced replication using a new peer-to-peer model that provides a new topology in which databases can be synchronized transactionally with any identical peer database.

Scalability

Scalability advancements such as table partitioning, snapshot isolation, and 64-bit support will enable you to build and deploy your most demanding applications using SQL Server 2005. The partitioning of large tables and indexes significantly enhances query performance against very large databases.

Table and Index Partitioning

Table and index partitioning eases the management of large databases by facilitating the management of the database in smaller, more manageable chunks. While the concept of partitioning data across tables, databases, and servers is not new to the world of databases, SQL Server 2005 provides a new capability for the partitioning of tables across filegroups in a database. Horizontal partitioning allows for the division of a table into smaller groupings based on a partitioning scheme. Table partitioning is designed for very large databases, from hundreds of gigabytes to terabytes and beyond.

Visit: www.gcreddy.net for Testing Information 106

Page 107: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Snapshot Isolation

After data is copied, transformed, and archived to an analysis-oriented database, it must be maintained and/or rebuilt periodically. Users certainly benefit from looking at a transactionally consistent version of the database; however, the version of the data that they are viewing is no longer current. It can take many hours to build and index the data and that might not be what the user really needs. This is where snapshot isolation is helpful. The snapshot isolation level allows users to access the last row that was committed by using a transactionally consistent view of the database. This new isolation level provides the following benefits:

•Increased data availability for read-only applications.

•Nonblocking read operations allowed in an online transaction processing (OLTP) environment.

•Automatic mandatory conflict detection for write transactions.

•Simplified migration of applications from Oracle to SQL Server.

Replication Monitor

Replication Monitor is a tool that sets a new standard for ease of use in managing complex data replication operations with its intuitive user interface and wealth of data metrics.

Support for 64-bit System Itanium 2 and x64

Optimized for the Intel Itanium processor, SQL Server (64-bit) takes advantage of advanced memory addressing capabilities for essential resources such as buffer pools, caches, and sort heaps, reducing the need to perform multiple I/O operations to bring data in and out of memory from disk. Greater processing capacity without the penalties of I/O latency opens the door to new levels of application scalability. Windows Server 2003 x64 provides high performance for both 32-bit and 64-bit applications on the same system. The underlying architecture is based on 64-bit extensions to the industry-standard x86 instruction set, allowing today's 32-bit applications to run natively on x64 processors. At the same time, new 64-bit applications are executed in 64-bit mode, which processes more data per clock cycle, allows greater access to memory, and speeds numeric calculations. The result is a platform that takes advantage of the existing wealth of 32-bit applications while also providing a smooth migration path to 64-bit computing.

Visit: www.gcreddy.net for Testing Information 107

Page 108: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Security

SQL Server 2005 makes significant enhancements to the security model of the database platform, with the intention of providing more precise and flexible control to enable tighter security of the data. A considerable investment has been made in a number of features to provide a high level of security for your enterprise data including the following:

•Enforcing policies for SQL Server login passwords in the authentication space.

•Providing for more granularity in terms of specifying permissions at various scopes in the authorization space.

•Allowing for the separation of owners and schemas in the security management space.

Authorization

A new security model in SQL Server 2005 allows administrators to manage permissions at a granular level and at a designated scope, making management of permissions easier as well as ensuring that the principle of least privileges is upheld. SQL Server 2005 lets you specify a context under which statements in a module execute. This feature also acts as an excellent mechanism for granular permission management.

Authentication

SQL Server 2005 clustering supports Kerberos authentication against a SQL Server 2005 virtual server. Administrators can specify Microsoft Windows-style policies on standard logins so that a consistent policy is applied across all accounts in the domain.

Native Encryption

SQL Server 2005 supports encryption capabilities within the database itself, fully integrated with a key management infrastructure. By default, client/server communications are encrypted. To centralize security assurance, server policy can be defined to reject unencrypted communications.

Visit: www.gcreddy.net for Testing Information 108

Page 109: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

SQL Server and Trustworthy Computing

The Microsoft Trustworthy Computing initiative outlines a framework that defines the steps necessary to support more secure computing as well as measures that help you deploy and maintain a more secure environment. These steps help to protect the confidentiality, integrity, and availability of data and systems at every phase of the software life cycle—from design, to delivery, to maintenance. To uphold the four tenets of the Trustworthy Computing initiative, Microsoft and the SQL Server team have addressed the following issues:

•Secure by design. The SQL Server development team conducted multiple security audits and spent more than two months studying SQL Server components and the interaction between them. For each potential security threat, the team did a threat analysis to evaluate the issue and completed additional design and testing work to neutralize potential security issues. Because of these design efforts, SQL Server 2005 includes many new server security features.

•Secure by default. Upon installation, SQL Server 2005 chooses the right set of configuration values for all setup options, ensuring that when a new system is installed, it will be in a secure state by default.

•Secure in deployment. Microsoft has created content to help organizations deploy SQL Server using the proper security credentials and to fully understand the steps and permissions required. SQL Server deployment tools provide the information necessary to understand the decisions you need to make during deployment. Security updates are easy to find and install—and if you choose the option, the updates install automatically. Tools are also available to help you assess and manage security risks across organizations.

Developer Productivity

SQL Server 2005 includes many new technologies that bring significant increases in developer productivity. From .NET Framework support to tight integration with Visual Studio, these features provide developers with the ability to more easily create secure, robust database applications at a lower cost. SQL Server 2005 enables developers to take advantage of existing skills across a variety of development languages while providing an end-to-end development environment for the database. Native XML capabilities also allow developers to build new classes of connected applications across any platform or device.

Visit: www.gcreddy.net for Testing Information 109

Page 110: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Enhancements for developer productivity include the following:

•Expanded language support

•Improved development tools

•Extensibility

•Improved data access

•XML and Web services

•Application framework

Expanded Language Support

Because the common language runtime (CLR) is hosted in the database engine, developers can choose from a variety of familiar languages to develop database applications, including Transact-SQL, Microsoft Visual Basic .NET, and Microsoft Visual C# .NET. Additionally, CLR hosting provides developers with increased flexibility with user-defined types and functions. The CLR also provides opportunities to use non-Microsoft code for rapid database application development.

CLR/.NET Framework Integration

With the release of SQL Server 2005, database programmers can now take full advantage of the Microsoft .NET Framework class library and modern programming languages to implement functionality within the server. Using CLR integration, you can code your stored procedures, functions, and triggers in the .NET Framework language of your choice. Microsoft Visual Basic .NET and the C# programming language both offer object-oriented constructs, structured exception handling, arrays, namespaces, and classes. Additionally, the .NET Framework provides thousands of classes and methods that have extensive built-in capabilities that you can easily use on the server side. Many tasks that were awkward or difficult to perform in Transact-SQL can be better accomplished by using managed code; additionally, two new types of database objects—aggregates and user-defined types—are available. You can now better use the knowledge and skills that you have already acquired to write in-process code. In short, SQL Server 2005 enables you to extend the database server to more easily perform appropriate computation and operations on the back end.

Visit: www.gcreddy.net for Testing Information 110

Page 111: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

This integration between SQL Server and the CLR provides several major benefits:

•Enhanced programming model. Programming languages that are compatible with the .NET Framework are in many respects richer than Transact-SQL, offering constructs and capabilities that were previously not available to SQL Server developers.

•Enhanced safety and security. Managed code runs in a CLR environment, hosted by the database engine. This allows .NET Framework database objects to be safer and more secure than the extended stored procedures available in earlier versions of SQL Server.

•User-defined types and aggregates. Two new database objects that expand the storage and querying capabilities of SQL Server are enabled by hosting the CLR.

•Common development environment. Database development is integrated into the Microsoft Visual Studio 2005 development environment. You can use the same tools for developing and debugging database objects and scripts that you use to write middle-tier or client-tier .NET Framework components and services.

•Performance and scalability. Because managed code compiles to native code prior to execution, you can achieve significant performance increases in some scenarios.

By using languages such as Visual Basic .NET and C#, you can capitalize on CLR integration to write code that has more complex logic and is more suited for computation tasks. Additionally, Visual Basic .NET and C# offer object-oriented capabilities such as encapsulation, inheritance, and polymorphism. You can easily organize related code into classes and namespaces, which means that you can more easily organize and maintain your code investments when you are working with large amounts of code. The ability to logically and physically organize code into assemblies and namespaces is a huge benefit that allows you to better find and relate different pieces of code in a large database implementation.

Managed code is more efficient than Transact-SQL at processing numbers and managing complicated execution logic, and provides extensive support for string handling, regular expressions, and so on. Also, with the functionality that is available in the .NET Framework

Visit: www.gcreddy.net for Testing Information 111

Page 112: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

class library, you have full access to thousands of prebuilt classes and routines that you can access easily from any stored procedure, trigger, or user-defined function. Everything from improved string-handling functions, math functions, date operations, access to system resources, advanced encryption algorithms, file access, image processing, and XML data manipulation is easily accessible from managed stored procedures, functions, triggers, and aggregates.

One of the major benefits of managed code is type safety. Before managed code is executed, the CLR performs several checks through a process known as verification to ensure that the code is safe to run. For example, the code is checked to ensure that memory is not read that has not been written to.

Transact-SQL Enhancements

Transact-SQL has long been the basis for all SQL Server programmability. SQL Server 2005 provides many new language capabilities for developing scalable database applications. These enhancements include error handling, new recursive query capabilities, and support for new SQL Server Database Engine capabilities. Transact-SQL enhancements in SQL Server 2005 increase your expressive powers in query writing, allowing you to improve the performance of your code and extend your error management capabilities. The continuous effort that is being put into enhancing Transact-SQL shows a firm belief in its significant role in SQL Server.

Improved Development Tools

Developers will be able to use one development tool for Transact-SQL, XML, Multidimensional Expressions (MDX), and XML for Analysis (XMLA). Integration with the Visual Studio development environment will provide more efficient development and debugging of line-of-business and business intelligence (BI) applications.

Business Intelligence Development Studio

The Business Intelligence Development Studio is a common development environment for building BI solutions based on Visual Studio including a database engine, analysis services, and reporting services. Use the Business Intelligence Development Studio graphical user interface (GUI) to design SQL Server Integration Services (SSIS) packages for data-management applications. SSIS packages are designed, developed, and debugged in Business Intelligence Development Studio by dragging tasks from the toolbox, setting their properties, and connecting tasks with precedence constraints. Figure 2

Visit: www.gcreddy.net for Testing Information 112

Page 113: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

shows the interface in Visual Studio for Business Intelligence Development Studio.

Figure 2: Business Intelligence Development Studio Interface in Visual StudioVisual Studio Integration

SQL Server 2005 and Visual Studio 2005 together provide deeper levels of integration between the database and the application development environment than ever before. Developers now have the ability to create CLR stored procedures, functions, user-defined types, and user-defined aggregates directly from within the Visual Studio development environment. They can deploy these new database objects directly from Visual Studio without having to switch tools. Visual Studio 2005 directly supports all of the new SQL Server data types, such as native XML. You can also add your CLR database objects to the same source control system that you use for all you Visual Studio projects, thus providing an even greater level of integration and security to your development processes.

Cross-Tier and Cross-Language Debugging

SQL Server 2005 and Visual Studio 2005 together provide even deeper integration in the area of application debugging. The combination lets you seamlessly debug both CLR and Transact-SQL code using the same Visual Studio debugging interface, and allows you to debug from CLR

Visit: www.gcreddy.net for Testing Information 113

Page 114: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

to Transact-SQL and back again, regardless of the location of the code, whether it is on the developer computer or stored in the SQL Server database.

Extensibility

User-Defined Types and Aggregates

User-defined types in SQL Server 2005 are not an object relational extensibility mechanism. They are a way to extend the scalar type system of the database. The scalar type system includes the columnar types that ship with SQL Server (types such as int, nvarchar, uniqueidentifier, and so on). With user-defined types, you can define your own type that can be used for column definitions, for example. Create a user-defined type if your type really is an atomic value that is appropriate to be modeled as a column.

Use user-defined types if you need to define your own scalar type. Example scenarios for such types include custom date/time data types in various calendars, and currency data types. With user-defined types, you can create a single object that exposes all the behaviors that are available on the type, and encapsulate, or hide, the underlying data that is stored by the type. Everyone that needs to access the data has to use the user-defined type programmatic interface. Taking advantage of existing functionality in the .NET Framework (such as the internationalization or calendar functionality) is another strong reason to consider implementing your type as a user-defined type.

In a number of scenarios, you may need to perform aggregations over data. This includes performing statistical calculations, such as avg, stddev, and so on. If the desired aggregation function is not directly supported as a built-in aggregate function, you have three ways to perform a custom aggregation in SQL Server 2005:

•Write the aggregation as a user-defined aggregate.

•Write the aggregate using a CLR stored procedure.

•Use a server-side cursor.

SQL Management Objects

Visit: www.gcreddy.net for Testing Information 114

Page 115: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

SQL Management Objects (SMO) is the management object model for SQL Server 2005. SMO represents significant design and architectural improvements for the SQL Server management object model. It is a simple-to-use but rich object model that is based on .NET Framework managed code. SMO is the primary tool for developing database management applications using .NET Framework. SMO is used by every dialog box in SQL Server Management Studio, and every administrative action that you can perform in SQL Server Management Studio you can also accomplish by using SMO.

The new SMO object model and the Microsoft Windows Management Instrumentation (WMI) application programming interfaces (APIs) replace SQL-DMO. Where possible, SMO incorporates similar objects as SQL-DMO for ease of use. You can still use SQL Server 2005 with SQL-DMO, but SQL-DMO will not be updated to manage features that are specific to SQL Server 2005.

Analysis Management Objects

Analysis Management Objects (AMO) allows client applications to access the range of administrative commands and capabilities available to Analysis Services using an object library that can provide object-level validation capabilities, instead of having to manually generate DDL scripts for Analysis Services commands and the often-lengthy contents of the Analysis Services Scripting Language (ASSL) ObjectDefinition element. Applications using AMO can either connect and work directly with objects on an Analysis Services instance, or create such objects without an existing connection and persist the metadata for later deployment. AMO also "wraps" ASSL commands and elements.

Improved Data Access and Web Services

In SQL Server 2005, you can develop XML Web services in the database tier, making SQL Server an HTTP listener. This provides a new type of data access capability for applications that are centralized around Web services. In SQL Server 2005, you can use HTTP to access SQL Server directly, without using a middle-tier listener such as Microsoft Internet Information Services (IIS). SQL Server exposes a Web service interface to allow the execution of SQL statements and invocation of functions and procedures. Query results are returned in XML format and can take advantage of the Visual Studio Web services infrastructure.

ADO.NET 2.0/ADOMD.NET

Visit: www.gcreddy.net for Testing Information 115

Page 116: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Much is new in the next version of ADO.NET. From new support for query change notifications to Multiple Active Result Sets (MARS), ADO.NET evolves dataset access and manipulation to achieve greater scalability and flexibility.

Query Notification

SQL Server 2005 introduces notification support for SQL Server queries. You can use this support to send a command to SQL Server and to request that a notification be generated if executing the same command again produces different results from those obtained initially. You accomplish this by using a dependency object that detects when the underlying data is changed. Commands that are sent to the server through any of the client APIs such as ADO.NET, OLE DB, Open Database Connectivity (ODBC), Microsoft ActiveX Data Objects (ADO), or Simple Object Access Protocol (SOAP) may include a tag that requires a notification. For each statement that is executed as part of the request, the server creates a notification subscription that fires once for each statement that is included in the request. Notifications are delivered through a SQL Service Broker queue that applications can poll, and use activation services or blocking statements that return whenever the notifications are available. Query notifications are useful for enabling the caching of results in applications such as database-driven Web sites. Figure 3 shows the query notification process.

Figure 3: Query NotificationMARS

Multiple Active Result Sets (MARS) provides the means to have more than one pending request per connection, in particular to have more than one default result set open per connection. Default result sets are forward-only, read-only result sets. For default result sets, the client drivers transparently retrieve the data in large chunks (Tabular Data Stream buffer-sized chunks) so that application requests are satisfied without a round trip to the server (as in the case of server cursors). The application can use a simple row-at-a-time programming model

Visit: www.gcreddy.net for Testing Information 116

Page 117: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

without compromising performance. The MARS feature removes the current restriction in which an open default result set blocks the driver from sending requests to the server until the entire result set is consumed.

Transparent Failover for Data Mirroring

SQL Server 2005 supports a "hot spare" capability through database mirroring. If a SQL Server instance fails, work can be shifted to the backup server automatically. This requires an instance to witness the failover known as (not surprisingly) the witness instance. Hot spare scenarios require that existing client connections must "know" to fail over (establish a connection with the new server instance), as well. It is suboptimal for client connections to produce an error on the next attempted access and to have to be manually "failed over" by client programming. SqlClient in ADO.NET 2.0 supports client failover without special programming of the application program.

XML Support

Advancements such as the native XML data type and XQuery help organizations seamlessly connect internal and external systems. SQL Server 2005 supports both relational and XML data natively, so enterprises can store, manage, and analyze data in the format that best suits their needs. Support for existing and emerging open standards such as Hypertext Transfer Protocol (HTTP), XML, Simple Object Access Protocol (SOAP), XQuery, and XML Schema definition language (XSD) also facilitate communication across extended enterprise systems.

XML Data Type

XML can model complex data; it is not limited to the scalar types that are supported by SQL Server. As such, a string-based, built-in data type such as char or varchar does not suffice to make full and effective use of the power and the numerous advantages of XML. For example, if XML is stored as a string, you can insert or select an entire document, or even retrieve contiguous bytes from it, but you cannot query into the contents of the document itself. By providing the XML data type, SQL Server 2005 allows you to query portions of an XML document, validate that the document conforms to an XML schema, and even modify the contents of the XML document in place. It also integrates traditional, relational data with data in unstructured or semistructured XML documents in ways that are not possible with SQL Server 2000. In SQL Server 2005, XML data is stored as binary large objects (BLOBs) in

Visit: www.gcreddy.net for Testing Information 117

Page 118: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

an internal representation that allows efficient reparsing and some compression.

A collection of XML schemas can be associated with a column of type XML. This provides validation for constraints, inserts, and updates, and typing of values inside stored XML data, as well as optimizations for storage and query processing. SQL Server 2005 also provides several DDL statements for managing schemas on the server.

XQuery

The XML Query Language, or XQuery, is an intelligent and robust language that is optimized for querying all types of XML data. With XQuery, you can run queries against variables and columns of the XML data type using the latter's associated methods. As with many XML standards, the World Wide Web Consortium (W3C) oversees the development of XQuery. XQuery evolved from a query language called Quilt, which was itself based on a variety of other query languages such as the XML Path Language (XPath) version 1.0, XML Query Language (XQL), and SQL. It also contains XPath 2.0 as a subset. Therefore, if you have experience using XPath 1.0, you can capitalize on your skills and do not have to learn an entirely new query language. There are, however, significant enhancements that go beyond XPath 1.0, such as typing, special functions, and support for better iteration, sorting of results, and construction.

SQL Server 2005 ships with deep XQuery capabilities that allow for XML object manipulation in the data tier. It supports a statically typed subset of the XQuery 1.0 Working Draft of November 15, 2003.

Web Services Support

In SQL Server 2005, you can develop XML Web services in the database tier, making SQL Server an HTTP listener. This provides a new type of data access capability for applications that are centralized around Web services. In SQL Server 2005, you can use HTTP to access SQL Server directly without using a middle-tier listener such as Microsoft Internet Information Services (IIS). SQL Server exposes a Web service interface to allow the execution of SQL statements and invocation of functions and procedures. Query results are returned in XML format and can take advantage of the Visual Studio Web services infrastructure.

Visit: www.gcreddy.net for Testing Information 118

Page 119: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

XML for Analysis Services

XML for Analysis Services (XMLA) is the native, standards-based protocol for communicating with the Analysis Services server. New kinds of applications are enabled and easy to develop—applications that integrate analytics with operations in real time. With XMLA as the native protocol, Analysis Services clients can be configured to have a zero footprint, and each server is automatically a Web service. A light-footprint Win32 layer is available for backward compatibility with tools that work with Analysis Services 2000 on OLE DB for OLAP, ADOMD, and ADOMD.NET. Many users will continue to use the ADOMD.NET object model to build custom applications on Analysis Services.

Application Framework

SQL Server 2005 introduces a new SQL Server application framework that includes Service Broker, Notification Services, SQL Server Mobile, and SQL Server Express. Service Broker is a distributed application framework that provides reliable asynchronous messaging at the database-to-database level.

Service Broker

Over the last 10 years, the proliferation of e-commerce applications has created the need for increased workflow management across database applications. When an online customer places an order for a book, this order needs to commit transactions into the inventory, shipping, and credit card systems, and needs to send an order confirmation using another Web application. Waiting for each of these processes to happen in order does not scale well. SQL Server 2005 provides a new scalable architecture for building asynchronous message routing. Figure 4 outlines the Service Broker architecture.

Visit: www.gcreddy.net for Testing Information 119

Page 120: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Figure 4: Service Broker Architecture

The Service Broker technology allows internal or external processes to send and receive streams of reliable, asynchronous messages by using extensions to normal Transact-SQL data manipulation language. Messages are sent to a queue in the same database as the sender, to another database in the same instance of SQL Server, or to another instance of SQL Server either on the same server or on a remote server.

Microsoft SQL Server Notification Services is a platform for developing and deploying applications that generate and send notifications to users. Notifications are personalized, timely messages that can be sent to a variety of devices.

Notifications reflect subscriber preferences. The subscriber enters a subscription to express an interest in information, such as "Notify me when the stock price of Adventure Works reaches $70.00," or "Notify me when the strategy document my team is writing is updated."

A notification can be generated and sent to the user as soon as a triggering event occurs, or it can be generated and sent on a predetermined schedule that the user specifies. The user's subscription specifies when the notification should be generated and sent.

Notifications can be sent to a various devices, such as to a user's mobile phone, personal digital assistant (PDA), Microsoft Windows

Visit: www.gcreddy.net for Testing Information 120

Page 121: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Messenger, or e-mail account. Because these devices often accompany the user, notifications are ideal for sending high-priority information.

SQL Server Mobile Edition

SQL Server 2000 shipped with SQL Server 2000 Windows CE Edition, which is now SQL Server Mobile Edition version 3.0. A number of new key features in SQL Server Mobile Edition relate to developers:

•You can create a SQL Server Mobile Edition database on the desktop or on the device, directly from SQL Server Management Studio. You can also manipulate the schema of the SQL Server Mobile Edition database directly from Management Studio, regardless of whether the database resides on the mobile device or on the desktop. You can use SQL Server Management Studio to run queries that target a SQL Server Mobile Edition database on the device or on the desktop. You can also take advantage of new SQL Server Mobile Edition features that include an XML showplan rendered in a graphical user interface format just like native SQL Server and the ability to use query hints to override the query optimizer in SQL Server Mobile Edition. For the first time, you can control the optimization plan on a device.

•You can now code against SQL Server Integration Services (SSIS) objects to exchange data.

•The new SqlCeResult set is derived from the SQLResult set that is in SQL Server 2005. This allows SQL Server Mobile Edition to have a true, scrollable, and updateable cursor. It also allows binding to data objects that are on devices.

•You can code an application to synchronize data while leaving the main application open and you can have two separate applications access the same database on the device at the same time.

•You can get notifications that you can code into status bars that will give the synchronization status. Previously, you had no way to know how far synchronization had progressed, to notify users that a device had not stopped responding.

•You can maintain the small size of the database through a much more aggressive page reclamation policy.

•You can share parameterized query code with SQL Server syntax.

Visit: www.gcreddy.net for Testing Information 121

Page 122: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

SQL Server Express

More than ever, developers are making the most of relational databases to provide a rich end-user experience. Protecting and managing information inside these applications is critical. Microsoft SQL Server Express helps developers build robust and reliable applications by providing a free, easy-to-use, and robust database. Too often, database systems are overly complex for building simple applications. Microsoft Visual Studio 2005 and SQL Server Express reduce this complexity by providing a simple but powerful development environment for building data-driven applications. Developers can design schemas, add data, and query local databases, all inside the Visual Studio 2005 environment. If developers need more advanced database features, then SQL Server Express can be seamlessly upgraded to more sophisticated versions of SQL Server. Figure 5 shows the Query Editor interface in SQL Server Express Manager.

Figure 5: The Query Editor in SQL Server Express Manager

A new graphical user interface tool called SQL Server Express Manager (XM) is freely available as a separate Web download. XM allows easy database management and query analysis capabilities, has a small download size, and will be freely redistributable. XM supports connections to SQL Server Express and other SQL Server 2005 editions, SQL Server 2000, and MSDE 2000. A simplified connection dialog box guides the user through the selection of the instance and the authentication methods to be used. Both local and remote connections are possible using XM. Object Explorer enumerates and

Visit: www.gcreddy.net for Testing Information 122

Page 123: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

displays the common objects used, such as the instance, tables, stored process, and so on, in a hierarchical manner and helps the user visualize access to the database.

All database management functionalities are available by invoking the right-click context menu from Object Explorer. Some of the database management options to be exposed include creating and modifying databases, tables, logins, and users. Many of these common database operations are available as task wizards that guide the user through the process, while many others are available as tabbed window documents. For instance, XM provides a New/Edit Database document for creating new databases and editing existing databases.

Many database users prefer to manage their servers using Transact-SQL, because this approach offers finer-grained control than using the graphical user interface. The Query Editor in XM lets users develop and execute Transact-SQL statements and scripts. The Query Editor has rich features such as keyword color-coding and a results pane that returns results in a data grid. Error messages, if any, are also shown in the results pane.

Business Intelligence

SQL Server 2005 furthers Microsoft leadership in the area of business intelligence (BI) through innovations in scalability, data integration, development tools, and rich analytics. SQL Server 2005 enables scalable BI by putting critical, timely information in the hands of employees across your organization. From the CEO to the information worker, employees will be able to quickly and easily harness data to make better decisions faster. The comprehensive integration, analysis, and reporting capabilities of SQL Server 2005 enable companies to extend the value of their existing applications, regardless of the underlying platform. BI features include enhancements in the following areas:

•An end-to-end integrated business intelligence platform

•Integration Services

•Analysis Services

•Reporting Services

Visit: www.gcreddy.net for Testing Information 123

Page 124: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

•Integration with the Microsoft Office System

End-to-End Integrated Business Intelligence Platform

SQL Server 2005 is a complete BI platform that provides the features, tools, and functionality to build both classic and innovative kinds of analytical applications. The following information introduces the tools that you will use to build an analytical application, and highlights new functionality that makes it easier than ever to build and manage complex BI systems.

The SQL Server 2005 BI toolset delivers end-to-end BI application integration:

•Design. Business Intelligence Development Studio is the first integrated development environment designed for the BI developer. Built on Visual Studio 2005, Business Intelligence Development Studio delivers a rich, integrated, professional development platform for BI system developers. Debugging, source control, and script and code development are available for all components of the BI platform.

•Integrate. SQL Server Integration Services (SSIS) has been rewritten to perform complex data integration, transformation, and synthesis at high speed for very large data volumes. Business Intelligence Development Studio makes building and debugging packages positively fun. Integration Services, Analysis Services, and Reporting Services work together to present a seamless view of data from heterogeneous sources.

•Analyze. Microsoft Data Mining has always been easy to use. Now it is even better with the addition of important new algorithms, including Association Rules, Time Series, Regression Trees, Sequence Clustering, Neural Network, and Naïve Bayes. SQL Server 2005 blurs the lines between relational and multidimensional databases. You can store data in the relational database, in the multidimensional database, or use the new Proactive Cache feature to get the best of both worlds. Important new analytical capabilities have been added to Analysis Services cubes as well; these include key performance indicator (KPI) framework, MDX scripts, and other built-in advanced business analytics. The Reporting Services report delivery and management framework enables easy distribution of complex analytics to the widest possible audience.

•Report. Reporting Services extends the Microsoft BI platform to

Visit: www.gcreddy.net for Testing Information 124

Page 125: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

reach the business user who needs to consume the analysis. Reporting Services is an enterprise-managed reporting environment, embedded and managed through Web services. Reports can be personalized and delivered in a variety of formats, with a range of interactivity and printing options. Complex analyses can reach a broad audience through the distribution of reports as a data source for downstream BI. New with SQL Server 2005 is the reporting tool, Report Builder.

•Manage. SQL Server Management Studio integrates the management of all SQL Server 2005 components. BI practitioners will benefit from this extension of the server abilities you expect from the relational engine—scalability, reliability, availability, programmability, and so on—to the full set of BI platform components.

Integration Services

SQL Server 2005 includes a redesigned enterprise data extraction, transformation, and loading (ETL) platform, called SQL Server Integration Services (SSIS). SSIS enables organizations to more easily integrate and analyze data from multiple heterogeneous information sources. By analyzing data across an array of operational systems, organizations may gain a competitive edge through a holistic understanding of their business.

Enterprise ETL Platform

This new platform is the successor to the popular feature in SQL Server 2000 called Data Transformation Services (DTS). SSIS is completely new for SQL Server 2005. SSIS provides the breadth of features and very high-scale performance that is necessary to build enterprise-class ETL applications. SSIS is fully programmable, embeddable, and extensible—characteristics that make it an ideal ETL platform.

Beyond Traditional ETL

SQL Server 2005 supports nontraditional data (Web Services, XML) out of the box, in the following ways:

•SSIS brings analytics to the data without persisting the data.

Visit: www.gcreddy.net for Testing Information 125

Page 126: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

•Data mining and text mining can be done in the data flow.

•Data mining and analytics are brought to the data flow for data quality and data cleansing.

Analysis Services

With SQL Server 2005, Analysis Services provides, for the first time, a unified and integrated view of all your business data as the foundation for your traditional reporting, online analytical processing (OLAP) analysis, and data mining.

Unified Dimensional Model

By combining the best aspects of traditional OLAP analysis and relational reporting, Analysis Services provides a metadata model that covers both sets of needs. A set of cubes and dimensions defined in Analysis Services is referred to as a Unified Dimensional Model (UDM). The UDM is a central metadata repository defining business entities, business logic, calculations, and metrics that serves as the source for all reports, spreadsheets, OLAP browsers, KPIs, and analytical applications.

Using the powerful new Data Source View feature, the UDM is mapped to a host of heterogeneous back-end data sources, providing a complete and integrated picture of the business regardless of the location of the data.

With the UDM's friendly descriptions of the business entities, navigation hierarchies, multiple perspectives, and even automatic translations to native languages, users will find it easy to explore the corporate business data.

Data Mining

SQL Server 2005 Data Mining is the BI technology that helps you build complex analytical models, and integrate those models with your business operations. Analysis Services establishes new ground for data mining. By creating an easy-to-use, extensible, accessible, and flexible platform, Analysis Services data mining capabilities introduce data mining to organizations that previously would never have considered a data mining solution.

Through an enterprise-class architecture, a deep integration with the SQL Server family of BI tools, and a rich set of other tools, APIs, and algorithms, SQL Server enables the creation of a new breed of

Visit: www.gcreddy.net for Testing Information 126

Page 127: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

intelligent applications that enhance productivity, increase profits, and reduce costs by providing customized data-driven solutions to a broad range of business problems.

Reporting Services

Reporting Services extends the Microsoft BI platform to reach the information worker who needs access to business data. Reporting Services is a server-based enterprise reporting environment, managed through Web services. Reports can be delivered in a variety of formats, with a range of interactivity and printing options. Complex analyses can reach a broad audience through the distribution of reports as a data source for downstream BI.

As an integrated component of SQL Server 2005, Reporting Services provides the following:

•A high-performance engine for processing and formatting reports.

•A complete set of tools for creating, managing, and viewing reports.

•An extensible architecture and open interfaces for embedding reports or integrating reporting solutions in diverse IT environments.

Relational and OLAP Reports

Reports built on relational data are useful but the ability to add additional analytic capabilities makes such reporting powerful. Reporting Services allows you to easily build reports together or separately. SQL Server 2005 supports both relational and OLAP data and provides a query editor for both, including SQL Query Editor and MDX Query Editor.

Report Builder

Report Builder, a new component of SQL Server 2005 Reporting Services, allows business users to create their own reports using a user-friendly model of their data. Report Builder takes advantage of the Reporting Services platform to bring ad hoc reporting to all end users. Users create and edit reports with the Report Builder client application. The Report Builder user interface is built on top of familiar Microsoft Office paradigms such as Microsoft Excel and Microsoft PowerPoint. Figure 6 shows a sample Report Builder report.

Visit: www.gcreddy.net for Testing Information 127

Page 128: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Figure 6: Design Reports with Report Builder

Report Builder is a ClickOnce application deployed through the browser. Users start by selecting report layout templates containing predefined data sections such as tables, matrices, and charts. They drag and drop report items from the model to the design surface and set constraints to filter the report data. The model contains all of the necessary information for the Report Builder to automatically generate the source query and retrieve the requested data. The Report Builder also allows users to:

•Add text and formatting to reports.

•Create new fields and calculations defined using the model.

•Preview, print, and publish reports.

•Export report data to formats such as Microsoft Excel.

Integration with the Microsoft Office System

Reports served up by the Report Server in Reporting Services can run in the context of Microsoft SharePoint Portal Server and Microsoft

Visit: www.gcreddy.net for Testing Information 128

Page 129: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Office System applications such as Microsoft Word and Microsoft Excel. You can use SharePoint features to subscribe to reports, create new versions of reports, and distribute reports. You can also open reports in Word or Excel to view HTML versions of the reports.

Upgrading to SQL Server 2005

The following are some tips for upgrading to SQL Server 2005:

•Upgrade to SQL Server 2005 from SQL Server 7.0 or SQL Server 2000.

•Run Upgrade Advisor before upgrading to determine if any product changes are expected to break existing applications.

•The SQL Server Database Engine, Analysis Services, and Reporting Services can be upgraded by the setup program.

•SQL Server Integration Services, the replacement for Data Transformation Services (DTS), is installed side by side with DTS. You can run DTS packages using the DTS runtime components.

•SQL Server 2005 Notification Services is installed side by side with Notification Services 2.0. You must migrate instances of Notification Services to SQL Server 2005 when you upgrade the SQL Server Database Engine.

•Use the Surface Area Configuration tool after upgrading to enable or disable SQL Server 2005 services, network protocols, and features.

Visit: www.gcreddy.net for Testing Information 129

Page 130: SQL Server Guide

Visit: www.gcreddy.com for QTP Information

Visit: www.gcreddy.net for Testing Information 130