an introduction to database (ms-sql)

97
Ramendra Narayan Singh Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Upload: ramendra-singh

Post on 16-Feb-2016

25 views

Category:

Documents


1 download

DESCRIPTION

An Introduction to Database (MS-SQL)

TRANSCRIPT

Page 1: An Introduction to Database (MS-SQL)

Ramendra Narayan Singh

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 2: An Introduction to Database (MS-SQL)

IntroductionIdentifying keys in tablesQuerying databasesCreating and managing tablesImplementing data integrityMaintaining databasesIntroduction to IndexesCreating viewsImplementing batchesImplementing stored proceduresImplementing transactionsCreating triggers

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 3: An Introduction to Database (MS-SQL)

Introduction :Inbuilt Databases in Ms SQL:

mastermodelmsdbtempdb

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 4: An Introduction to Database (MS-SQL)

master

All the system information for a SQL Server is held by the master database. E.g., login accounts, configuration settings, SQL server initialization information, remote server information, ongoing processes, system error messages, tapes and disks available on the system, and active locks.

The master database also stores the locations of all the other databases. As such, without master database the other databases cannot be found.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 5: An Introduction to Database (MS-SQL)

modelThe model database is used as the template

for all new 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 the SQL Server is started, the model database must always exist on a SQL Server system.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 6: An Introduction to Database (MS-SQL)

msdb

The msdb database contains operational records such as database backup and restore history, job definitions for replication agents, push/pull subscription and snapshot agents, and maintenance plan history records.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 7: An Introduction to Database (MS-SQL)

tempdbThe tempdb is a work area for temporary tables

and temporary stored procedures. These are dropped automatically when the SQL server is stopped, so there is no need to save the tempdb between server sessions. The tempdb is re-created every time SQL Server is started, so the system starts with a clean copy of the database.

By default, tempdb auto grows as needed while SQL Server is running, but it is reset to its initial size each time the database server is started.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 8: An Introduction to Database (MS-SQL)

Types of SQL Statements:

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

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 9: An Introduction to Database (MS-SQL)

Data Definition Language (DDL)Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:

 CREATE - to create objects in the database ALTER - alters the structure of the database DROP - delete objects from the database TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 10: An Introduction to Database (MS-SQL)

Data Manipulation Language (DML)

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:

 SELECT - retrieve data from the a database INSERT - insert data into a table UPDATE - updates existing data within a table DELETE - deletes all records from a table, the

space for the records remain

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 11: An Introduction to Database (MS-SQL)

Data Control Language (DCL)

Data Control Language (DCL) statements. Some examples:

 GRANT - gives user's access privileges to

database REVOKE - withdraw access privileges given

with the GRANT command

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 12: An Introduction to Database (MS-SQL)

Transaction Control Language (TCL)

Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

COMMIT - save work done SAVEPOINT - identify a point in a transaction to

which you can later roll back ROLLBACK - restore database to original since the

last COMMIT SET TRANSACTION - Change transaction options

like isolation level and what rollback segment to useCopyright © 2008 by BrickRed Technologies Pvt. Ltd.

®

Page 13: An Introduction to Database (MS-SQL)

Entities & AttributesEntity: The basic data item stored in a database is

called an entity. An entity can be any object, item, place, person, concept, or activity about which data can be stored. Entities are building blocks of the databases.

 Attribute: An attribute is a property of an entity. It

describes a part of the entity. An entity can have one or more attributes.

 Table: You represent an entity in the form of a table in

a database. A table is a set of rows and columns. You represent the attributes of the entity as column headings and the actual data about the entity in rows.

Note: Attributes are also referred to as fields or columns. Rows are also referred to as records or tuples. Tables are also referred to as relations.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 14: An Introduction to Database (MS-SQL)

Identifying keys in tablesTypes of Keys:Candidate Key: A Candidate key is an attribute that uniquely

identifies a row. It can also be referred to as Surrogate key. Primary Key: A Primary Key is a candidate key that you

choose to identify rows uniquely. Alternate Key: If there are multiple candidate keys in a table,

the candidate keys that are not chosen as a primary key will be called alternate keys.

Composite Key: When the key that is used to uniquely identify the rows of a table is made up of more than one attribute, it is called a Composite key.

 Foreign Key: Two tables can be related using a common

attribute. When a primary key of one table is also available as an attribute in another related table, it is called a Foreign key.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 15: An Introduction to Database (MS-SQL)

Above mentioned keys help in maintaining the database integrity.Entity Integrity: Entity Integrity ensures that each row can be

uniquely identified by an attribute called the primary key. The primary key cannot be NULL.

Referential Integrity: Ensuring that all the values in the foreign key match with the primary key values is called referential integrity.

In a client/server system, there is a program that requests for a particular service and there is another that processes this request. The program that requests for the services is called client, while the one that services the request is called server.

Most RDBMSs adhere to the client/server architecture.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 16: An Introduction to Database (MS-SQL)

Querying databasesDisplaying all the data from a table :

SELECT * FROM <tablename>

Displaying specific attributes/columns from a table :SELECT column-name[,column-name] … FROM <tablename>

 Displaying specific columns with user-friendly column

headings :Method 1 SELECT column_heading = column_name from <table name>Method 2SELECT column_name column_heading FROM <tablename>

Displaying selected rows from a table :SELECT select_list FROM <tablename> WHERE conditionCopyright © 2008 by BrickRed Technologies Pvt.

Ltd. ®

Page 17: An Introduction to Database (MS-SQL)

Following is the list of Comparison operators which can be used in Where clause :

Sr. # Operator Description

1 = Equal to

2 > Greater than

3 < Less than

4 >= Greater than or equal to

5 <= Less than or equal to

6 <> Not equal to

7 != Not equal to

8 !> Not greater than

9 !< Not less than

10 () Controls precedence

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 18: An Introduction to Database (MS-SQL)

Displaying rows that satisfy multiple conditions:SELECT select_list FROM <tablename> WHERE [NOT] condition {AND | OR} [NOT] condition

You use the logical operators AND and OR to connect two or more search conditions in the Where clause.

You use AND when you want all the conditions to be satisfied. You use OR when you want any of the conditions to be satisfied.

NOT negates the expression that follows it.When you use more than one logical operator in a

statement, NOT is evaluated first, then AND and finally OR.

Parentheses can be used to change the order of evaluation and can make an expression more readable.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 19: An Introduction to Database (MS-SQL)

Displaying rows with missing values :SELECT select_list from tablename WHERE column_name IS [NOT] NULL

Use of IS NULL and IS NOT NULL A NULL means that there is no entry for that column of that

row. It is not the same as a zero or a blank. NULLs fail all comparisons. For instance, two NULLS are

not equal to each other. NULLs sort low. This means that NULL will be the first item

to be displayed in the output that is sorted in ascending order.

Displaying data in a specific order: The ORDER BY ClauseSELECT select_list FROM <tablename> ORDER BY column name | select_list_number [ASC|DESC]

Note : You can use a relative column number instead of the column name in the ORDER BY clause. ASC is the default sort order.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 20: An Introduction to Database (MS-SQL)

Aggregate functions

Aggregate functions are used to calculate aggregates. The aggregate functions, on execution, summarize the values for a column or a group of columns within a table for which they are applied, and produce a single value.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 21: An Introduction to Database (MS-SQL)

Various aggregate functions are :Function Name Parameters Description

AVG ([ALL|DISTINCT] expression) Average of the values in a numeric expression, either all or distinct

COUNT ([ALL|DISTINCT] expression) Number of values in an expression, either all or distinct

COUNT (*) Number of selected rows

MAX (expression) Highest value in the expression

MIN (expression) Lowest value in the expression

SUM ([ALL|DISTINCT] expression) Total of values in a numeric expression, either all or distinct

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

E.g.

SELECT “No of Employees” = COUNT(cEmployeeCode) FROM Employee

Generating a summary report :

SELECT select_list FROM <tablename> WHERE search_conditions GROUP BY column_name HAVING search_conditions

Page 22: An Introduction to Database (MS-SQL)

Displaying the top few rows: The TOP keywordSELECT TOP n[PERCENT] column_name FROM <tablename> Where, n is a number if the PERCENT keyword is used, then ‘n’

percent of the rows are returned. The TOP clause limits the number of rows

returned in the result set. If the select statement, including TOP, has an

ORDER BY clause, then the rows to be returned are selected after the ORDER BY clause has been applied.Copyright © 2008 by BrickRed Technologies Pvt. Ltd.

®

Page 23: An Introduction to Database (MS-SQL)

Displaying the average: The COMPUTE BY clauseSELECT column_name FROM <tablename> ORDER BY column_name COMPUTE row_aggregate (column_name) [BY column_name]

The COMPUTE BY clause can only be used for columns that are ordered.

The column names in the Select list must be ordered and used in the COMPUTE BY clause.

Columns not mentioned in the COMPUTE BY clause cannot be part of the Select list.e.g. SELECT empname, salary FROM Employee COMPUTE AVG(salary)Copyright © 2008 by BrickRed Technologies Pvt.

Ltd. ®

Page 24: An Introduction to Database (MS-SQL)

String Functions:ASCII SELECT ASCII(“ABC”) – Returns 65

the ASCII code of the leftmost characterCHAR SELECT CHAR(65) – Returns A the

char equivalent of the ASCII code value…..

For a complete list of string functions, please refer to: http://msdn2.microsoft.com/en-us/library/ms181984.aspx

E.g. SELECT UPPER (cEmpName) FROM employee

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 25: An Introduction to Database (MS-SQL)

Date Functions:Function Name Syntax Description

DATEADD (datepart,number,date) Adds the number of dateparts to the date

DATEDIFF (datepart,date1,date2) Calculates the number of dateparts between two dates

DATENAME (datepart, date) Returns datepart from the listed date, as ASCII value e.g. October

DATEPART (datepart,date) Returns datepart from the listed date as an integer

GETDATE () Returns current date and time

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 26: An Introduction to Database (MS-SQL)

In the above table, datepart can be:

Datepart Abbreviation Values

Year yy 1753-9999

Quarter qq 1-4

Month mm 1-12

Day of year dy 1-366

Day dd 1-31

Week wk 0-51

Weekday dw 1-7(1 is Sunday)

Hour hh 0-23

Minute mi 0-59

Second ss 0-59

Millisecond ms 0-999

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 27: An Introduction to Database (MS-SQL)

e.g. SELECT “today” = getdate(), “10 days from

today” = getdate() + 10

or 

SELECT “today” = getdate(), “10 days from today” = dateadd(dd,10,getdate())

 Mathematical functions : 

ABS, ACOS, ASIN, ATAN, ATN2, COS, SIN, COT, TAN, DEGREES, EXP, FLOOR, LOG, LOG10, PI, POWER, RADIANS, RAND, ROUND, SIGN, SQRT

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 28: An Introduction to Database (MS-SQL)

Retrieving rows based on pattern matching:Wildcard Description

% Any string of zero or more characters

_ Any single character

[] Any single character within the specified range or set

[^] Any single character not within the specified range or set

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Expression Returns

Like ‘LO%; All names that begin with “LO”

Like ‘Lo%’ All names that begin with “Lo”

Like ‘%ion’ All names that end with “ion”

Like ‘%rt%’ All names that have the letters “rt” in them

Like ‘_rt’ All three-letter names ending in “rt”

Like ‘[DK]%’ All names that begin with “D” or “K”

Like ‘[A-D]ear’ All four letter names that ends in “ear” and begin with any letter from “A” to “D”

Like ‘D[^c]%’ All names beginning with “D” and not having “c” as the second letter

Page 29: An Introduction to Database (MS-SQL)

e.g. SELECT * FROM employee WHERE empname LIKE ‘raj%’

Generating reports with unique values: The DISTINCT keyword

 SELECT DISTINCT column_name

FROM <tablename>

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 30: An Introduction to Database (MS-SQL)

Types of Joins Displaying data from two or more tables:  For this we use JOINs. There are following types of JOINs supported by MS-SQL  Cross Join – A join that includes more than one table without any condition in

the ON clause is called a cross join. The output of such joins is called a Cartesian product.

 e.g. SELECT title FROM titles cross join publishers; if one table is having 18 rows

and another is having 8 rows then the result would be 144 rows.  Natural Join – a join that restricts the redundant column data from the result

set is known as natural join. It is implemented by specifying the various column names of the tables in the select list.

  Equi Join – a join that uses an asterisk sign (*) in the select list and displays

redundant columns in the resultset is termed as equi join. An equi join displays redundant column data in the result set, where two or more tables are compared for equality.

Self Join – a join is said to be a self join when one row in a table correlates with other rows in the same table. Since the same table is used twice for comparison, an alias name differentiates the two copies of the table. All join operators except the outer join operators can be used in a self join.

e.g. SELECT t1.titleid, t1.pubid, t2.titleid, t2.pubid FROM titles t1 JOIN titles t2 ON t1.pubid = t2.pubid

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 31: An Introduction to Database (MS-SQL)

Outer Join – a join can be termed an outer join when the result set contains all the rows from one table and the matching rows from another. An outer join eliminates the information contained in the row that does not match the condition for only one of the tables.

SELECT column_name FROM <tablename> [LEFT | RIGHT] OUTER JOIN <tablename> ON <tablename.reference_columnname> = <tablename.reference_columnname

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 32: An Introduction to Database (MS-SQL)

Combining data from two tables: The union operator

SELECT column _name FROM <tablename > UNION [ALL] SELECT column_name FROM <tablename>

 Note – The column headings of the result set are the

column names of the first select statement. All columns in the following select statements must be of similar datatype and must have similar number of columns.

By default, the union clause removes duplicate rows. If ALL is used, these duplicate rows are also displayed.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 33: An Introduction to Database (MS-SQL)

Using one query in another: Subqueries/nested queries

In certain situations, you may require a complex query to be broken into a series of logical steps. This process is useful when you query relies on the results of another query. One query nested in another query is called a subquery.

The syntax of the select clause to retrieve data based on the output of another query is SELECT columnname FROM <tablename> WHERE columnname = (SELECT columnname FROM <tablename> WHERE columnname = <value>)

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 34: An Introduction to Database (MS-SQL)

Creating and managing tablesCreating a table CREATE TABLE <tablename>(columnname datatype [NULL | NOT NULL] [IDENTITY (SEED,

INCREMENT)],columnname datatype …)

Where, Tablename is the name of the table Columnname is the name of the column in the table Datatype is the system defined or user defined datatype for the

column NULL | NOT NULL are keywords that specify whether r not null

values are allowed for the column Identity is used for those columns that need automatically generated

unique system values. This property can be used to generate sequential numbers.

Seed is the starting or initial value for the identity column. Increment is the step value used to generate the next value for the

column. This value can also be negative.Copyright © 2008 by BrickRed Technologies Pvt.

Ltd. ®

Page 35: An Introduction to Database (MS-SQL)

e.g. CREATE TABLE sales(cItemCode char(4) NOT NULL,cItemName char(10) NULL,iQuantitySold int NOT NULL,dSalesDate datetime NOT NULL) CREATE TABLE employee(iEmployeeCode int IDENTITY (100,1),cEmployeeName char(25) NOT NULL,cDepartmentName char(25) NOT NULL)

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 36: An Introduction to Database (MS-SQL)

Data Types in MSSQLDatatype Code Used to store

int i Integer data (whole numbers)

float f Floating precision data

money m Monetary data

datetime d Date and time data

char(n) c Character data

varchar(n) v Character data

smallint si Integer data

text t Character string

tinyint ti Integer data

bit bt Integer data with 0 or 1

image im Variable length binary data to store images

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 37: An Introduction to Database (MS-SQL)

Check whether the table has been created : The sp_help command

You can use the sp_help command to view the structure of the table.

sp_help table_name Deleting a table You use the DROP TABLE statement to delete a table from

the database. When the table is dropped from the database, all the data from the table is also deleted.

 DROP TABLE <tablename> Creating user defined datatypes: User defined datatypes

A use defined datatype is specific to the database in which it is created. However, if it is created in the model database, the in is included in all the newly created use defined databases.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 38: An Introduction to Database (MS-SQL)

The sp_addtype command :sp_addtype type [,system_data_type] [,null_type]

e.g. sp_addtype typSellingDate, datetime, ‘NOT NULL’

 the null type is ignored if a NULL or NOT NULL

condition is specified in the create table statement Verifying that the datatype has been created in

the database: sp_help datatype_name

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 39: An Introduction to Database (MS-SQL)

Data Integrity:It is important for the data in a database to be accurate, consistent and reliable. Thus, it is 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 Domain Integrity Referential Integrity User defined integrity

Entity Integrity Entity integrity ensures that each row can be uniquely identified by an attribute called the primary key. The primary key cannot be NULL.

 Domain Integrity

Domain integrity ensures that only a valid range of values is allowed to be stored in a column. You can enforce domain integrity by restricting the type of data, the range of values, and the format of data.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 40: An Introduction to Database (MS-SQL)

Referential IntegrityReferential integrity ensures that all the values in the foreign key match the values in the primary key. Referential integrity ensures that the data in the database remains uniformly consistent, accurate and usable even after the data in it has been changed.

 User defined integrity User defined integrity refers to a set of business rules that do not

belong to the categories of entity, domain and referential integrity, and are specified by a user.

 Data integrity can be enforced by using following constraints:

Types of constraints

Constraints can be divided into five categories Primary key constraint Unique constraint Foreign key constraint Check constraint Default constraint

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 41: An Introduction to Database (MS-SQL)

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 the primary key columns. A primary key column cannot contain null values since it is used to uniquely identify the rows in a table. The primary key constraint ensures entity integrity.

You can define a PRIMARY KEY constraint at the time of table creation or you can add it later by altering the table. While defining a PRIMARY KEY constraint, you need to specify a name for the constraint. If name is not specified, SQL server automatically assigns a name to the constraint.

If a PRIMARY KEY constraint is defined on a column that already contains data, then the existing data in the column is checked. If any duplicate values are found, then the PRIMARY KEY constraint is rejected.

CONSTRAINT constraint_name PRIMARY KEY [CLUSTERED | NONCLUSTERED]

  CLUSTERED | NONCLUSTERED are keywords that specify if a

clustered or a nonclustered index is to be created for the primary key constraint.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 42: An Introduction to Database (MS-SQL)

e.g. CREATE TABLE employee(cEmployeeCode char(4) CONSTRAINT pkEmployeeCode

PRIMARY KEY CLUSTERED,….)

Above command creates a table employee with cEmployeeCode as the primary key. The name of the constraint is pkEmployeeCode. You can also create a primary key after the table has been created, by giving the following command:

ALTER TABLE employeeADD CONSTRAINT pkEmployeeCode PRIMARY KEY

CLUSTERED (cEmployeeCode)The above statement creates a PRIMARY KEY constraint, pkEmployeeCode, on the cEmployeeCode column of the employee table.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 43: An Introduction to Database (MS-SQL)

The UNIQUE ConstraintUNIQUE constraint are used to enforce uniqueness

on non-primary key columns. A primary key constraint column automatically includes a restriction for uniqueness. The unique constraint is similar to the primary key constraint except that it allows NULL values, but there can be only one row in the table with NULL value. Multiple unique constraints can be created on a table.

CONSTRAINT constraint_name UNIQUE [CLUSTERED | NONCLUSTERED]

 Clustered |Non-clustered are keywords that specify

if a clustered or a non-clustered index is to be created for the unique constraint.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 44: An Introduction to Database (MS-SQL)

Implementing Unique constraint

CREATE TABLE employee(…imPhoto image, dJoiningDate datetime, dResignationDate datetime,cSocialSecurityno char(15) CONSTRAINT

unqSocialSecurity UNIQUE)By altering the table: ALTER TABLE employee ADD CONSTRAINT unqSocialSecurity UNIQUE

(cSocialSecurityno)

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 45: An Introduction to Database (MS-SQL)

The foreign key constraintYou use the foreign key constraint to remove the

inconsistency in two tables when the data in one table depends on the data in another 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, that is, a primary key column in another table. A foreign key may refer to the primary key of the same or another table. The foreign key constraint enforces referential integrity.

CONSTRAINT constraint_name FOREIGN KEY REFERENCES table_name (columnname)

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 46: An Introduction to Database (MS-SQL)

Implementing Foreign key constraint

CREATE TABLE employee(..cDepratmentCode char(4) REFERENCES department

(cDepartmentCode),…)

By altering table: 

ALTER TABLE employeeADD CONSTRAINT fkDepartmentCode FOREIGN KEY

(cDepartmentCode) REFERENCES department(cDepartmentCode)

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 47: An Introduction to Database (MS-SQL)

The CHECK constraintA check constraint enforces domain integrity by

restricting the values to be inserted in a column. It is possible to define multiple check constraints on a single column. These are evaluated in the order in which they are defined. A single check constraint can be applied to multiple columns when it is defined at the table level.

[CONSTRAINT constratin_name] check (expression) A check constraint can be specified along with: The in keywordThe alter table commandThe between keywordThe in keywordUsing the in keyword you can ensure that the values

entered are from a list of constant expressions.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 48: An Introduction to Database (MS-SQL)

Implementing CHECK constrainte.g.CREATE TABLE recruiter(…cCity char(15) CONSTRAINT chkcity CHECK (cCity IN (‘kolkata’, ‘delhi’, ‘patna’,

‘chennai’))..) By altering table:

ALTER TABLE recruiterADD CONSTRAINT chkcity CHECK(ccity IN (‘kolkata’, ‘delhi’, ‘patna’, ‘chennai’)) Wildcards can also be used for following certain patterns:The LIKE keyword

CHECK(cRecruiterCode LIKE “[0-9] [0-9] [0-9] [0-9]”) i.e. can contain only four digit numbers.

 The BETWEEN keywordCHECK (mTotoalPaid BETWEEN 0 AND 50000) i.e. mTotalPaid attribute can have a

value between 0 and 50000 only.Copyright © 2008 by BrickRed Technologies Pvt. Ltd.

®

Page 49: An Introduction to Database (MS-SQL)

The DEFAULT constraint   A default constraint can be used to assign a constant value to a

column, and the user need not insert values for such a column. System supplied values like user, current_user and the other similar values can be assigned as defaults.

 [CONSTRAINT constraint_name] DEFAULT(constant_expression | NULL)

e.g.CREATE TABLE employee(…cCity char(15) DEFAULT “delhi”…) By altering table:

ALTER TABLE employeeADD CONSTRAINT defcity DEFAULT “delhi” for cCity

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 50: An Introduction to Database (MS-SQL)

Creating Rule: A rule provides a mechanism for enforcing domain

integrity for columns or user defined datatypes. The rule is applied before an insert or update statement is issued. In other words, a rule specifies a restriction on the values for a column or a user defined datatype. Rules must be used to implement business related restrictions or limitations.

 The CREATE RULE statementCREATE RULE rule_name AS conditional_expression 

CREATE RULE rultype AS @rultype IN (‘business’s, ‘mod_cook’,’trad_cook’,’popular_comp’,’psychology’) i.e. allows only particular values to be inserted in a column.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 51: An Introduction to Database (MS-SQL)

CREATE RULE ruldeptname AS @deptname NOT IN (‘accounts’,’stores’) i.e. specifies that if the value is accounts or ‘stores’, then these values will be rejected from being inserted into the column or user defined datatype, to which the rule is bound.

 CREATE RULE rulmaxprice AS @maxprice >= $5000 i.e.

allows a value of $5000 or more to be inserted in the columns or user defined datatype, to which the rule is bound.

 CREATE RULE rulempcode AS @empcode LIKE ‘[f-m][a-z]

…..’ i.e. allows a character string that follows the pattern specified in the like clause to be inserted in the column or user defined datatype, to which the rule is bound.

The rule can be deleted by using the drop rule statement

DROP RULE rule_nameCopyright © 2008 by BrickRed Technologies Pvt.

Ltd. ®

Page 52: An Introduction to Database (MS-SQL)

Binding rulesWhen a rule is created, it has be bound to

either a column or a user defined datatype sp_bindrule rule_name, object_name

[,futureonly]sp_bindrule rultype, ‘titles.type’ i.e. binds the rule called rultype to the column type of the titles table. The same rule can be bound to the columns of other tables when the same attribute is available.

 

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 53: An Introduction to Database (MS-SQL)

Creating DEFAULT : The CREATE DEFAULT statement

CREATE DEFAULT default_name AS constant_expression

 CREATE DEFAULT defcity AS ‘delhi’ The default can be deleted by using the drop default

statement.DROP DEFAULT default_name

Binding defaults sp_bindefault default_name, object_name [,futureonly] sp_bindefault defcity, ‘employee.ccity’

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 54: An Introduction to Database (MS-SQL)

Storing details in a table: The insert statement INSERT [INTO] table_name [column_list] VALUES

default values | values_list | select_statement INSERT sales VALUES (‘I005”,

‘Printer’,100,’01/09/2008’) INSERT sales (cItemCode, cItemName, iQtySold,

dSaleDate) VALUES (‘I005”, ‘Printer’,100,’01/09/2008)

 INSERT sales VALUES (‘I005”, ‘Printer’,100,DEFAULT)

– i.e. specitying a default value 

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 55: An Introduction to Database (MS-SQL)

Storing data from existing table in a new table

SELECT columns_list INTO new_table_name FROM table_names WHERE conditions

 SELECT cTitileID, cTitle INTO newtitles FROM titles

WHERE iPrice > 15 The INSERT INTO statement You can use the insert into command to add data from

one table to anotherINSERT[INTO] table_name1SELECT column_name(s) FROM table_name2 [WHERE

condition]

INSERT INTO olditems SELECT * FROM items

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 56: An Introduction to Database (MS-SQL)

Updating a table: The UPDATE statementUPDATE table_name SET column_name = value

FROM table_name [WHERE condition] UPDATE employee SET cDepartmentCode =

‘0003’ WHERE cEmployeeCode = ‘0000015’ Guidelines for updating rowsAn update can be done on only on one table at

a timeIf an update violates integrity constraints,

then the entire update is rolled back, that is , the changes do not affect the table

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 57: An Introduction to Database (MS-SQL)

Deleting data: The DELETE statement

DELETE [FROM] table_name [WHERE condition]

 DELETE items WHERE cItemCode =’I001’ DELETE FROM employee WHERE

cEmployeeCode = ‘0003’

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 58: An Introduction to Database (MS-SQL)

Introduction to Indexes To speed up data retrieval, indexes are used.

Indexes also enforce the uniqueness of rows.  An index is an internal table structure that SQL

server uses to provide quick access to the rows of a table based on the values of one or more columns. Indexes in SQL server are like the indexes at the back of a book which help in finding the content your are looking for.

 There are two types of indexes CLUSTERED IndexNONCLUSTERED Index

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 59: An Introduction to Database (MS-SQL)

CLUSTERED IndexThe data is physically sortedOnly one clustered index can be created per table,

so you should build it on attributes that have a high percentage of unique values and that are not modified often.

NONCLUSTERED IndexThe physical order of the rows is not the same as

the index orderNonclustered indexes are typically created on

columns used in JOINs and WHERE clauses, and whose values may be modified frequently

SQL server creates nonclustered indexes by default when the create index command is given

There can be as many as 249 nonclustered indexes per table

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 60: An Introduction to Database (MS-SQL)

Features of indexes Indexes accelerate queries that join tables, and perform

sorting and grouping Indexes can be used to enforce uniqueness of rows. Indexes are useful on columns in which the majority of data

is unique. An index on columns containing a large amount of duplicate data is not useful

When you modify the data of an indexed column, the associated indexes are updated automatically

Maintaining indexes requires time and resources. You should not create an index that would not be used frequently

A clustered index should be created before a nonclustered index. A clustered index changes the order of rows. A nonclustered index would need to be rebuild if it is built before a clustered index.

Typically nonclustered indexes are created on foreign keys.

CREATE [UNIQUE] [CLUSTERED|NONCLUSTERED] INDEX index_name ON table_name(column_name)

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 61: An Introduction to Database (MS-SQL)

Views A view is a virtual table, which gives access to a

subset of columns from one or more tables. It is a query stored as an object in the database. Hence, a view is an object that derives its data from one or more tables. These tables are referred to as the base or underlying table.

A view serves as a security mechanism. This ensures that users are able to retrieve and modify only the data seen by them. The remaining data in the underlying tables can neither be seen nor accessed. Usage of complex queries can also be simplified using views.

Once a view is defined it can be referenced like any other table in the database. Though it is similar to a table, it is not stored in the database. It derives its set of values from the underlying tables.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 62: An Introduction to Database (MS-SQL)

The create view statementA view can be created by using the create view statementCREATE VIEW view_name AS select_statement Restrictions imposed on views are as follows:A view can be created only in the current databaseThe name of a view must follow the rules for identifiers and

must not be the same as that of the table on which it is based.

A view can be created only if there is select permission on its base table

A trigger or an index cannot be defined on a view.A SELECT INTO statement cannot be used in a view

declaration statementA view cannot derive its data from temporary tables.The create view statement cannot be combined with other

SQL statements in a single batchIn a view ORDER BY cannot be used in the SELECT

statementCopyright © 2008 by BrickRed Technologies Pvt. Ltd.

®

Page 63: An Introduction to Database (MS-SQL)

Modifying data using viewsViews do not maintain a separate copy of data. The

data is present in the base tables. Therefore, you can modify the base tables by modifying the data of the view. There are certain restrictions at the time of inserting, updating, or deleting data through views.

Guidelines for modifying data using viewsYou cannot modify data in a view if the modification

affects more than one underlying tableYou can modify the data in a view if the modification

affects only one table at a timeYou cannot change a column that is the result of a

calculation.  

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 64: An Introduction to Database (MS-SQL)

Implementing Batches

 Batches are groups of SQL statements submitted together to the SQL server for execution. The SQL server processes a batch interactively, or from a file.

A batch is parsed, optimized, compiled, and executed. SQL server compiles the statements of a batch into a single executable unit, called an execution plan. The statements in a the execution plan are then executed one at a time. If there is a syntax error in a batch no statement in the batch gets executed.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 65: An Introduction to Database (MS-SQL)

Variables: You can use a variable to store a temporary value. You can

declare a variable using the declare statement:

DECLARE @variable_name data_type e.g. DECLARE @charge int @symbol is required and is used by the query processor to

identify variables.Some more examples: SELECT @maxsal = MAX(salary) FROM employeeDECLARE @charge floatSELECT @charge = siPercentageCharge FROM

contractrecruiterIn the above example, the select statement will return

more than one value, but the last value will be stored in the variable.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 66: An Introduction to Database (MS-SQL)

There are two types of variables local and global. Local variables are declared within the batch and is

lost when the execution of the batch is over. Since we define them, they are called User defined variables. Global variables are those that are declared by the server and typically, assigned values by the server.

The names of local variables must begin with the @ sign. Local variables can either be assigned a system datatype or a user defined datatype. When a local variable is defined it is initialized to NULL.

 Global variables are system supplied and predefined variables. They are distinguished by local variables by having two @ signs preceding their names.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 67: An Introduction to Database (MS-SQL)

The following table contains a list of useful global variables:Variable Name Returns

@@version Date of the current version

@@serverName Name of the SQL server

@@spid Server process Id number of the current process

@@procid Stored process ID of the currently executing procedure

@@error 0 if the last transaction succeeded, else last error number

@@rowcount Number of rows affected by the last query, 0 if no rows are affected

@@connections Number of logins or attempted logins

@@trancount Number of currently active transactions fro a user

@@max_connections Maximum number of simultaneous connections

@@total_errors Total number of errors that have occurred during the current SQL server session

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 68: An Introduction to Database (MS-SQL)

If you declare a local variable that has the same name as a global variable, then the variable will be treated as a local variable.

 Printing messages: PRINT statement is used to display a user defined

message or the content of a variable on the screen. DECLARE @myname = char(50)SELECT @myname = ‘Ramendra’PRINT @myname SELECT “The numbers of rows returned by the query is

= “ + CONVERT(varchar, @@rowcount) Above statement will display the number of rows

returned by a queryCopyright © 2008 by BrickRed Technologies Pvt. Ltd.

®

Page 69: An Introduction to Database (MS-SQL)

Comment Entry: Multiple line comment entries : /* and */ Single line comment entries : -- (double hyphen) Control of Flow language

Control of flow language controls the flow of execution of SQL statements in batches, stored procedures, triggers and transactions. It is typically used when statements have to be conditionally or repeatedly executed. The control of flow language transforms standard SQL into a programming language.

The control of flow statement provided by SQL server for programming are :

 The IF…ELSE statement – can be used to execute SQL statements

conditionally. A particular action is performed when the given condition evaluates to true and another action is performed when the given condition evaluates to false.

IF Boolean_expressionStatement_blockELSE Boolean_expressionStatement _block

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 70: An Introduction to Database (MS-SQL)

The CASE statement – in situations where several conditions need to be evaluated, SQL server provides a programming construct called the case statement. The case statement evaluates a list of conditions and returns one of the various possible results. Yu can use the IF statement to do the same task. However, CASE statement can be used when there are more than two conditions.

 CASE WHEN Boolean_expression THEN expression[WHEN Boolean_expression THEN expression][….]][ELSE expression]END

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 71: An Introduction to Database (MS-SQL)

e.g.SELECT cCandidateCode, vFirstName, siTestScore,

‘Date of interview’ = CASEWHEN siTestScore >= 0 AND siTestScore < 80 THEN‘Sorry not called for interview’WHEN siTestScore >= 80 AND siTestScore < 85 THEN‘Interview date = 02/15/08’WHEN siTestScore >= 85 AND siTestScore < 90 THEN‘Interview date = 02/05/08’When siTestScore >= 90 THEN ‘Interview date =

02/01/08’ELSE‘The person has not given the test’ENDFROM externalcandidate

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 72: An Introduction to Database (MS-SQL)

The BEGIN….END statement – if there are multiple SQL statements, then these must be enclosed within the begin and end keywords. Then BEGIN…END block can be nested and is most often used in IF..ELSE statements and WHILE loops.

 BEGINStatement_blockEND The WHILE statement – can be used in a batch, stored

procedure, trigger or a cursor to allow a set of SQL statements to execute repeatedly as long as the given condition holds true.

In a while loop, when you have to stop an iteration based on a condition, you use the break statement.

You can use the BREAK and CONTINUE statements to control the execution of the statements inside a WHILE loop. The BREAK statement causes an exit from the WHILE loop. Any statements that appear after the END keyword that marks the end of the loop are executed. The CONTINUE statement causes the WHILE loop to restart, skipping any statements after continue inside the loop.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 73: An Introduction to Database (MS-SQL)

WHILE Boolean_expressionStatement_blockBREAKStatement_blockCONTINUE e.g.DECLARE @iTest intSELECT @iTest = siTestScore FROM internalcandidateWHERE cEmployeeCode =’000008’IF @iTest < 80PRINT “Rejected – Not called for interview”ELSEBEGIN PRINT “Called for interview”PRINT “Your test score = “PRINT @iTestEND

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 74: An Introduction to Database (MS-SQL)

WHILE (SELECT AVG(siPercentageCharge + 1) FROM recruitmentagencies) < 10

BEGINUPDATE recruitmentagencies SET siPercentageCharge = siPercentageCharge + 1END WHILE (SELECT AVG(siPercentageCharge +1) FROM

recruitmentagencies) < 18BEGINUPDATE recruitmentagenciesSET siPercentageCharge = siPercentageCharge + 1IF (SELECT MAX(siPercentageCharge) FROM

recruitmentagencies) >= 20BREAKELSE CONTINUEEND

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 75: An Introduction to Database (MS-SQL)

Stored ProceduresSQL server implements client/server technology. A

number of clients send queries to the central server. The server, after receiving the query request, parses it for syntax errors and processes the request. Since the query passes from the client to the server through the network, it adds to the network traffic. Hence, an increase in the number of queries from the clients leads to network congestion and load on the server. A stored procedure is a solution to all the above stated problems.

A stored procedure is a collection or batch of SQL statements and control of flow language that is stored under one name, and executed as a single unit. It helps in improving the performance of a query.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 76: An Introduction to Database (MS-SQL)

Benefits of stored procedureA stored procedure is a precompiled object.

Therefore no time is spent at all in parsing and compiling the procedure again.

Improved performance, reduction in network congestion, enhanced accuracy, better consistency, better security mechanism

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 77: An Introduction to Database (MS-SQL)

Types of procedures The stored procedures can be classifieds as User defined stored proceduresSystem stored proceduresTemporary stored proceduresRemote stored proceduresExtended stored procedures

User defined stored procedures – user defined stored procedures are created and stored in the current database.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 78: An Introduction to Database (MS-SQL)

System stored procedures - System stored procedures have names prefixed with sp_. These primarily support various administrative tasks that help manage the SQL server. System stored procedures are stored in the system database and are accessible to the users of all the databases.

 Temporary stored procedures - Temporary stored

procedures have names prefixed with the #symbol. They are stored in the tempdb database and are automatically dropped when the connection terminates.

Remote stored procedures - Remote stored procedures are procedures that are created and stored in databases on remote servers. These can be accessed from various server, provided the users have the appropriate permissions.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 79: An Introduction to Database (MS-SQL)

Extended stored procedures - These are dlls that are executed outside the SQL server environment. They are identified by the prefix xp_.

CREATE PROCEDURE proc_nameASBEGINSql_statement1Sql_statement2END

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 80: An Introduction to Database (MS-SQL)

CREATE PROCEDURE prcPrintEmployeeListAS BEGIN

PRINT “List of Employees”SELECT cName, vAddress, cCity, cZip, cPhone, cFax FROM employee

END The sp_helptext command

To check the existence of a procedure in a particular database, you can use the system procedure

 sp_helptext proc_name

The execute procedure statement To execute the procedure either of the following commands can be

used:

Execute proc_nameOr Exec proc_nameOr proc_name

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 81: An Introduction to Database (MS-SQL)

ParameterA parameter is a placeholder in a query or a stored procedure that accepts a user defined value whenever the query or stored procedure is executed.

 Passing parameters to the procedures Types of parameters

The parameters declared in the parameter declaration section serve as a means for data to be exchanged between the stored procedure and the object that has invoked it (also known as the caller or the invoker).

The stored procedure return data in the following ways: Input parameter – allows the invoker to pass a data

value to the procedureOutput parameter – allows the stored procedure to

pass a data value back to the invokerCopyright © 2008 by BrickRed Technologies Pvt. Ltd.

®

Page 82: An Introduction to Database (MS-SQL)

e.g.CREATE PROCEDURE prcListEmployee @cCity char (15) ASBEGIN

PRINT “List of Employees”SELECT * from employee WHERE cCity = @cCity

END EXECUTE prcListEmployee Delhi

Modifying a stored procedure - Alter Procedure statement is used to modify the stored procedure

 ALTER PROCEDURE prcListEmployee @cCity char (15) ASBEGIN

PRINT “List of Employees”SELECT cEmployeeName, cPhone, vAddress FROM employee WHERE cCity = @cCity

END EXECUTE prcListEmployee Delhi

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 83: An Introduction to Database (MS-SQL)

Deleting a procedure - The Drop Procedure statement is used to delete a procedure

 DROP PROCEDURE proc_name

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 84: An Introduction to Database (MS-SQL)

Ensuring Data consistency:TransactionsA transaction can be defined as a sequence of operations

performed together as a single logical unit of work. A single unit of work must possess the four properties called ACID (Atomicity, Consistency, Isolation and Durability)

 Atomicity : It states that either all the data modifications take place or none.

Consistency : It is a state in which all the data is in a consistent state after a transaction is completed.

Isolation: It states that any data modification made by concurrent transactions must be isolated from the modifications made by other concurrent transactions.

Durability: It states that any change in data by a completed transaction remains permanently in effect in the system.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 85: An Introduction to Database (MS-SQL)

Explicit Transaction: An explicit transaction is one in which both the start and the end of the transaction are defined explicitly. Explicit transactions are specified using the BEGIN TRANSACTION and COMMIT TRANSACTION statements.

 BEGIN TRANSACTION - The begin transaction

statement marks the start of an explicit transactionBEGIN TRANSACTION transaction_name COMMIT TRANSACTION - The commit transaction

statement marks the ending point of an explicit transaction.

COMMIT TRANSACTION transaction_name

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 86: An Introduction to Database (MS-SQL)

ROLLBACK TRANSACTION - The rollback transaction statement roll back an explicit or implicit transaction to the beginning of the transaction, or to a save point within a transaction.

 ROLLBACK TRANSACTION transaction_name SAVE TRANSACTION - The save transaction

statement sets a save point within a transaction. A save point divides a transaction into logical units so that the transaction can return, if part of the transaction is conditionally cancelled. If you rollback a transaction to a save-point, either the transaction must proceed to completion, or it must be cancelled completely.

SAVE TRANSACTION savepoint_nameCopyright © 2008 by BrickRed Technologies Pvt. Ltd.

®

Page 87: An Introduction to Database (MS-SQL)

 e.g. BEGIN TRANSACTION

UPDATE jobfairSET mfee = mfee + 1000WHERE cjobfaircode = ‘0002’

 UPDATE jobfairSET dfairdate = getdate()WHERE cjobfaircode = ‘0001’SAVE TRANSACTION trnjobtransaction

 UPDATE contractrecruiterSET siPercentageCharge = siPercentageCharge + 1WHERE cContractRecruiterCode = ‘0001’

 UPDATE contractrecruiterSET mTotalPaid = mTotalPaid + 1000WHERE cContractRecruiterCode = ‘0001’

IF(SELECT siPercentageCharge FROM contractrecruiter WHERE cContractRecruitercode = ‘0001’) > 15BEGINPRINT ‘Transaction of contract recruiter begin rolled back’ROLLBACK TRANSACTION trnjobtransaction

ENDELSEBEGIN

COMMIT TRANSACTIONPRINT ‘Transaction committed’

END

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 88: An Introduction to Database (MS-SQL)

TriggersA trigger is a block of code that constitutes a set of SQL statements that are activated in response to certain actions. A trigger is always defined on a table, and is said to have fired whenever the data in the underlying table is affected by any of the data manipulation language (DML) statement – INSERT, UPDATE or DELETE. A trigger fires in response to an event like insertion, updation, and deletion of data. It is fired automatically by SQL server whenever any data modification statement is issued and cannot be explicitly invoked or executed.

 CREATE TRIGGER trigger_nameOn table_nameFOR [INSERT | UPDATE | DELETE]ASsql statements

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 89: An Introduction to Database (MS-SQL)

Magic tables - Whenever a trigger fires in response to the insert, delete or update statement, two special tables are created. These are the inserted and the deleted table. They are also referred to as magic tables. These are conceptual tables and are structurally similar to the table on which the trigger is defined.

The inserted table contains a copy of all the records that are inserted in the trigger table. The deleted table contains all the records that have been deleted from the trigger table. Whenever any updation takes place, the trigger uses both the inserted and deleted tables.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 90: An Introduction to Database (MS-SQL)

Types of triggersThe INSERT triggerThe DELETE triggerThe UPDATE trigger INSERT trigger - An insert trigger is fired

whenever an attempt is made to insert a row in the trigger table. When an insert statement is issued a new row is added to both the trigger and inserted tables.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 91: An Introduction to Database (MS-SQL)

e.g. CREATE TRIGGER trginsertrequisition On requisition FOR INSERTASDECLARE @vacancyreported intDECLARE @actualvacancy intSELECT @actualvacancy = iBudgetedStrength –

iCurrentStrengthFROM positionSELECT @vacancyreported = inserted.sinoofvacancyFROM insertedIF (@vacancyreported > @actualvacancy)BEGINPRINT ‘The actual vacancies are less than the vacancies

reported. Hence, cannot insert.’ROLLBACK TRANSACTIONENDRETURN

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 92: An Introduction to Database (MS-SQL)

The DELETE trigger - A delete trigger is fired whenever an attempt is made to delete a row from the trigger table. When a delete statement is issued, the specified rows from the trigger table are deleted and are added to the deleted table. The deleted and trigger tables do not have any rows in common, as in the case of inserted and trigger tables.

  There are three ways of implementing referential integrity using a delete trigger:

 The cascade method – deletes records from the

dependent tables whenever a record is deleted from the master table.

The restrict method – restricts the deletion of records from the dependent tables whenever a record is deleted from the master table.

The nullify method – nullifies the values in specific columns of the dependent tables whenever a record is deleted from the master table.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 93: An Introduction to Database (MS-SQL)

e.g.CREATE TRIGGER trgDeleteContractRecruiter ON contractrecruiterFOR DELETEASPRINT ‘Deletion of contract recruiters is not

allowed’ROLLBACK TRANSACTIONRETURN

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 94: An Introduction to Database (MS-SQL)

Update triggerWhen an update trigger is fired, it uses two logical tables for its operations – the deleted table that contains the original rows (the rows with the values before updating), and the inserted table that stores the new rows (the modified rows). Only after all the rows get updated, are the deleted and inserted tables populated and the trigger fired.

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 95: An Introduction to Database (MS-SQL)

e.g.CREATE TRIGGER trgUpdateContractRecruiterON contractrecruiterFOR UPDATEASDECLARE @avgpercentagecharge intSELECT @avgpercentagechage =

AVG(siPercentageCharge)FROM contractrecruiterIF (@avgpercentagecharge > 11)BEGINPRINT ‘The average cannot be more than 11’ROLLBACK TRANSACTIONENDRETURN

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 96: An Introduction to Database (MS-SQL)

Modifying a trigger

ALTER TRIGGER commandALTER TRIGGER trigger_nameON table_nameFOR [INSERT | DELETE | UPDATE]AS sql_statements Dropping the trigger - A trigger can be

deleted by using the drop trigger statement DROP TRIGGER trigger_name

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®

Page 97: An Introduction to Database (MS-SQL)

Feedback/Suggestions

Copyright © 2008 by BrickRed Technologies Pvt. Ltd. ®