Sie sind auf Seite 1von 92

Data Types

In a Database, each column, local variable, expression, and parameter has a related data
type. A data type is an attribute that specifies the type of data that the object can hold:
integer data, character data, monetary data, data and time data, binary strings, and so on.
Integer Types: To hold the Integer values it provides with tinyint, smallint, int and
bigint data types with sies !, ", # and $ bytes respectively.
Boolean Type: To hold the %oolean values it provides with bit data type that can ta&e a
value of !, ', or ()**.
(ote: The string values T+), and -A*., can be converted to bit values: T+), is
converted to ! and -A*., is converted to '.
Decimal Types: To hold the decimal values it provides with the following types:
/decimal0 (p0 , s1 )1 and numeric0 (p0 , s1 )1
p 2precision3
The maximum total number of decimal digits that can be stored, both to the left
and to the right of the decimal point. The precision must be a value from !
through the maximum precision of 4$. The default precision is !$.
s 2scale3
The maximum number of decimal digits that can be stored to the right of the
decimal point. .cale must be a value from ' through p. .cale can be specified
only if precision is specified. The default scale is '.
.torage sies of Decimal and (umeric types vary, based on the precision.
Precision Storage bytes
1 9 5
10-19 9
20-28 13
29-38 17
(ote: numeric is functionally equivalent to decimal.

-float 0 2 n 3 1 and real
/Approximate/number data types for use with floating point numeric data. -loating point
data is approximate5 therefore, not all values in the data type range can be represented
exactly. 6here n is the number of bits that are used to store the mantissa of the float
!
number in scientific notation and, therefore, dictates the precision and storage sie. If n is
specified, it must be a value between 1 and !. The default value of n is !.
n "alue Precision Storage si#e
1-24 7 digits 4 bytes
25-53 15 digits 8 bytes
$onetary or %urrency Types: To hold the 7urrency values it provides with the
following types which ta&es a scale of # by default:
money
-922,337,203,85,477.5808 to
922,337,203,85,477.5807
8
bytes
smallmon
ey
- 214,748.348 to 214,748.347
4
bytes
Date and Time &alues: To hold the Date and Time values of a day it provides with the
following types:
Data type 'ange (ccuracy
datetime
!anua"y 1, 1753, t#"oug# $ece%be" 31,
9999
3.33
%illiseconds
smalldateti
me
!anua"y 1, 1900, t#"oug# !une , 2079 1 %inute
8alues with the datetime data type are stored internally by the 9icrosoft .:* .erver
"''; Database ,ngine as two #/byte integers. The first # bytes store the number of days
before or after the base date: <anuary !, !=''. The base date is the system reference date.
The other # bytes store the time of day represented as the number of milliseconds after
midnight.
The smalldatetime data type stores dates and times of day with less precision than
datetime. The Database ,ngine stores smalldatetime values as two "/byte integers. The
first " bytes store the number of days after <anuary !, !=''. The other " bytes store the
number of minutes since midnight.
String &alues: To hold the string values it provides with the following types:
c)ar 0 2 n 3 1
"
-ixed/length, non/)nicode character data with a length of n bytes. n must be a
value from ! through $,'''. The storage sie is n bytes.
"arc)ar 0 2 n > ma* 3 1
8ariable/length, non/)nicode character data. n can be a value from ! through
$,'''. ma* indicates that the maximum storage sie is "?4!/! bytes. The storage
sie is the actual length of data entered @ " bytes.
te*t
It was eAual to varchar2max3 this data type will be removed in a future version of
9icrosoft .:* .erver. Avoid using these data types in new development wor& use
varchar2max3 instead.
)nicode Data types for storing 9ultilingual 7haracters are nchar, nvarchar and ntext
where n stands for national.
nc)ar 0 2 n 3 1
-ixed/length )nicode character data of n characters. n must be a value from !
through #,'''. The storage sie is two times n bytes.
n"arc)ar 0 2 n > ma* 3 1
8ariable/length )nicode character data. n can be a value from ! through #,'''.
ma* indicates that the maximum storage sie is "?4!/! bytes. The storage sie, in
bytes, is two times the number of characters entered @ " bytes.
nte*t
It was eAual to nvarchar2max3 this data type will be removed in a future version of
9icrosoft .:* .erver. Avoid using these data types in new development wor& use
nvarchar2max3 instead.
Binary &alues: To hold the binary values li&es images, audio clips and video clips we
use the following types.
binary 0 2 n 3 1
-ixed/length binary data with a length of n bytes, where n is a value from !
through $,'''. The storage sie is n bytes.
"arbinary 0 2 n > ma*3 1
8ariable/length binary data. n can be a value from ! through $,'''. ma* indicates
that the maximum storage sie is "?4!/! bytes. The storage sie is the actual
length of the data entered @ " bytes.
Image
It was eAual to varbinary2max3 this data type will be removed in a future version
of 9icrosoft .:* .erver. Avoid using these data types in new development wor&
use varbinary2max3 instead.
)se c)ar, nc)ar, binary when the sies of the column data entries are consistent.
)se "arc)ar, n"arc)ar, "arbinary when the sies of the column data entries vary
considerably.
4
)se "arc)ar(ma*), n"arc)ar(ma*), "arbinary(ma*) when the sies of the
column data entries vary considerably, and the sie might exceed $,''' bytes.
+t)er Types: Apart from the above it provides some additional types li&e /
timestamp: Is a data type that exposes automatically generated, uniAue binary numbers
within a database. The storage sie is $ bytes. Bou can use the timestamp column of a
row to easily determine whether any value in the row has changed since the last time it
was read. If any change is made to the row, the timestamp value is updated. If no change
is made to the row, the timestamp value is the same as when it was previously read.
,ni-ueidentifier: Is a !C/byte D)ID which is initialied by using the newid23 function
or converting a string constant in the form of xxxxxxxx/xxxx/xxxx/xxxx/xxxxxxxxxxxx
which is used to guarantee that rows are uniAuely identified across multiple copies of the
table.
.ml: Is the data type that stores E9* data. Bou can store *ml instances in a column, or a
variable of *ml type. The stored representation of *ml data type instances cannot exceed
" gigabytes 2D%3 in sie.
Database:
.:* .erver manages the objects in a container &nown as Database, where we can have
multiple databases present in it, each database when created creates " files internally
those or .mdf and .ldf file.
.yntax for creating a database:
/%'/(T/ D(T(B(S/ 0db1name2
/Database names must be uniAue within an instance of .:* .erver.
/Any Fbject name in sAlserver can be of ! through !"$ characters
Tables:
/It is the object, which will store the information in the database in the form of rows and
columns.
.yntax for creating a Table:
-%'/(T/ T(B3/ 0table1name2(
column1name1 0dtype2 45idt)6,
column1name1 0dtype2 45idt)6,
77777778
column1namen 0dtype2 45idt)6)
/Table names must be uniAue within the database.
/7olumn names must be uniAue within the table.
#
/,very table can have maximum of !'"# and minimum of ! column.
/7+,AT, TA%*, %an&27ustid int, 7name varchar2;'3, %al decimal2G,"33
Populating Data into Tables: after the table gets created to populate the data into it we
use
Insert Statement:
.yntax for Insert statement:
-I9S/'T I9T+ 0table1name2 4(col1, col:, 7788coln)6
&(3,/S ("al1, "al:, 778"aln)
,xamples:
I9S/'T I9T+ B(9; &(3,/S (1<1, =&/9;(T>, ?<<)
/In this case we need to provide the values for all the columns in the same order they are
present in the table.
/.tring and Date values have to be enclosed in single Auotes.
I9S/'T I9T+ B(9; (%,STID, %9($/, B(3) &(3,/S (1<:, =S,B(S@>,
A<<)
-This statement is same as above statement.
/If we want to change the order of columns while inserting:
I9S/'T I9T+ B(9; (%9($/, %,STID, B(3) &(3,/S (=S,'/S@>, 1<!,
A<<)
/If we want to insert data only into reAuired columns then:
I9S/'T I9T+ B(9; (%,STID, B(3) &(3,/S (1<?, !A<<)
/In this case the columns into which values are not supplied are filled with (ull value.
/6e can also insert (ullHs explicitly into the column in the following way:
I9S/'T I9T+ B(9; &(3,/S (1<, 9,33, ?<<)
'etrie"ing t)e data from Tables: if we want to retrieve the information from the table
use
Select Statement:
%asic .yntax for .elect statement:
S/3/%T 0 B C %+33IST 2 D'+$ 0T9($/2 4%+9DITI+9S6
/ IJH +epresents all the columns of the table in the same order.
/ 7F**I.T is used for specifying the reAuired no of columns and in reAuired order.
/ 7F(DITIF(. are optional which can be used for retrieving the reAuired rows.
/.,*,7T J -+F9 %A(K
/.,*,7T 7).TID, 7(A9,, %A* -+F9 %A(K
;
/.,*,7T 7(A9,, %A*, 7).TID -+F9 %A(K
/.,*,7T 7).TID A. A77(F, 7(A9,, %A* -+F9 %A(K
/6e can specify an alias name for any reAuired column while retrieving &nown as
7olumn Alias.
/If we want to retrieve reAuired rows then we use a conditional statement where:
/.,*,7T J -+F9 %A(K 6L,+, 7).TIDM!'#
/.,*,7T 7).TID, %A* -+F9 %A(K 6L,+, 7(A9,MH.)+,.LH
/.:* .erver does not have any case restrictions while writing the conditions.
@andling 9ull &alues: The value ()** means the data value for the column is
un&nown or not available, so we cannot use eAuality condition while getting the data
based on null values.
.,*,7T J -+F9 ,9N 6L,+, 7(A9,M()**
/The above statement will not get any result because no " null values can be compared so
to get the data based on (ull values we should use the I. ()** operator as following:
.,*,7T J -+F9 ,9N 6L,+, 7(A9, I. ()**
,pdating data present in t)e tables: if we want to )pdate the data existing in the table
we use
,pdate Statement:
.yntax:
-,PD(T/ 0T9($/2 S/T 0%9($/2E0&(3,/2 4, 7886 4%+9DITI+9S6

(ote: 6e can modify a single column or multiple columns using the update statement all
the rows that satisfy the condition gets affected.
/)NDAT, %A(K .,T 7(A9,MH+A9,.LH 6L,+, 7).TIDM!'#
/)NDAT, %A(K .,T 7(A9,MH+A<,.LH, %A*M4''' 6L,+, 7).TIDM!';
Deleting data present in t)e tables: if we want to delete rows of data present in the table
we use
Delete Statement:
.yntax:
-D/3/T/ D'+$ 0T9($/2 4%+9DITI+9S6
/D,*,T, -+F9 %A(K 6L,+, 7).TIDM!';
/D,*,T, -+F9 %A(K
%onstraints: used to enforce the integrity of the data in the columns, .:* .erver "'';
provides the following mechanisms to enforce the integrity of the data in column:
/(ot (ull
/)niAue
/Nrimary Key
C
/7hec&
/Default
/-oreign Key
9ot 9ull: If it is imposed on a column that column will not allow (ull 8alues into it5 this
can be imposed on any no of columns.
-%'/(T/ T(B3/ 0table1name2(
column1name1 0dtype2 45idt)6 49ot 9ull6,
column1name1 0dtype2 45idt)6 49ot 9ull6,
77777778
column1namen 0dtype2 45idt)6 49ot 9ull6)
+ecreating the ban& table with (ot (ull 7onstraint on it:
%'/(T/ T(B3/ BanF(%ustid int 9ot 9ull, %name "arc)ar(<), Bal
decimal(G,:) 9ot 9ull)
After creating this if we try to insert a null value into the 7ustid or %al columns it will
restrict us:
I(.,+T I(TF %an& 8A*),. 2()**, I+A<)H, 4;''3
I(.,+T I(TF %an& 27).TID, 7(A9,3 8A*),. 2!'!, I+A8IH3
The drawbac& with (ot (ull 7onstraint is even if it restricts null values it will not restrict
duplicate values, if they has to be restricted we use the ,ni-ue %onsraints8
,ni-ue: If it is imposed on a column or columns they will not allow duplicate 8alues
into it.
(ote: )niAue, Nrimary Key, 7hec& and -oreign Key 7onstraints can be imposed in two
different ways:
/7olumn *evel Definition
/Table *evel Definition
7olumn *evel Definition: In this case the constraint definition is immediately followed
after the column definition. The syntax is:
-%'/(T/ T(B3/ 0table1name2(
column1name1 0dtype2 45idt)6 4 4%onstraint 09ame26 0Type2 6,
column1name1 0dtype2 45idt)6 4 4%onstraint 09ame26 0Type2 6,
77777778
column1namen 0dtype2 45idt)6 4 4%onstraint 09ame26 0Type2 6,
+ecreating the ban& table with )niAue 7onstraint on it:
%'/(T/ T(B3/ BanF(%ustid int ,ni-ue, %name "arc)ar(<), Bal
decimal(G,:) 9ot 9ull)
After creating this if we try to insert a duplicate value into the 7ustid column it will
restrict us:
G
I(.,+T I(TF %an& 8A*),. 2!'!, I+A<)H, 4;''3
I(.,+T I(TF %an& 8A*),. 2!'!, I+A8IH, #;''3
(ote: Internally )niAue, Nrimary Key, 7hec& and -oreign Key 7onstraints are identified
by using some uniAue name which has to be given by us or else the system will give a
name, so when we violate these constraints it will show the name of the constraint in the
error message, by seeing which we reAuire to identify on which column we are getting
the problem, but if the table is not created by us or we donHt remember the structure of the
table we cannot identify. .o it is advised to give a name to the constraint so that when it
violates the error message shows the name of the constraint using which we can easily
identify where the violation has been done.
6hile giving a name to the 7onstraint they follow some conventions li&e:
O7olumn(ameP7onstraintTypeQ
OTable(ameP7olumn(ameP7onstraintTypeQ
+ecreating the ban& table with )niAue 7onstraint by giving a name to it:
%'/(T/ T(B3/ BanF(%ustid int %onstraint %usid1,H ,ni-ue, %name
"arc)ar(<), Bal decimal(G,:) 9ot 9ull)

Table *evel Definition: In this case the constraint definition is immediately followed after
the column definition. The syntax is:
-%'/(T/ T(B3/ 0table1name2(
column1name1 0dtype2 45idt)6,
column1name1 0dtype2 45idt)6,
77777778
column1namen 0dtype2 45idt)6,
4 4%onstraint 09ame26 0Type2 (0%ollist2)6,
777777778)
9ote: ( 9ot 9ull %onstraint %annot be defined table le"el8
%'/(T/ T(B3/ BanF(%ustid int, %name "arc)ar(<), Bal decimal(G,:) 9ot
9ull, %onstraint %usid1,H ,ni-ue(%ustid))
/In this case because the constraint is defined in the end of all the columns it cannot
understand to which column the constraint depends so we need to specify the column
name beside the constraint for identification.
/There will not be any difference in execution whether the constraint is defined in table
level or column level.
/6hen we define a constraint in table level we can define composite constraint i.e. a
single constraint on multiple columns.
%'/(T/ T(B3/ BanFDetails(%ity%ode "arc)ar(1<), Branc)%ode
"arc)ar(1<), %onstraint %%1B%1,H ,ni-ue(%ity%ode, Branc)%ode))
I9S/'T I9T+ BanFDetails &alues(=%1>, =B1>)
$
I9S/'T I9T+ BanFDetails &alues(=%1>, =B:>)
I9S/'T I9T+ BanFDetails &alues(=%1>, =B!>)
I9S/'T I9T+ BanFDetails &alues(=%:>, =B1>)
I9S/'T I9T+ BanFDetails &alues(=%:>, =B:>)
I9S/'T I9T+ BanFDetails &alues(=%:>, =B!>)
/In this case all the statements are valid because a composite uniAue constraint chec&s the
uniAueness on the combination of columns, but not on a single column.
The drawbac& with )niAue 7onstraint is even if it restricts duplicate values it will allow a
single null value in to the column. If we want to restricted duplicate values as well as null
values we need to use Primary ;ey %onstraint8
/6hile 7reating a primary &ey constraint we need to &eep this in mind i.e. a table can
contain only a single primary &ey present on it which can be present on a single column
or multiple columns also.
7reating Nrimary Key in column level:
%'/(T/ T(B3/ BanF(%ustid int %onstraint %usid1P; Primary ;ey,
%name "arc)ar(<), Bal decimal(G,:) 9ot 9ull)
7reating Nrimary Key in table level:
%'/(T/ T(B3/ BanF(%ustid int, %name "arc)ar(<), Bal decimal(G,:) 9ot
9ull, %onstraint %usid1P; Primary ;ey(%ustid))
7reating a 7omposite Nrimary Key in table level:
%'/(T/ T(B3/ BanFDetails(%ity%ode "arc)ar(1<), Branc)%ode
"arc)ar(1<), %onstraint %%1B%1P; Primary ;ey(%ity%ode, Branc)%ode))
%)ecF %onstraint: If we want to chec& the values present in a column to be according to
a specified value we use this constraint.
/If we want to restrict the %al in the ban& table should be some specified values then we
can use the constraint as following:
7L,7K 2%alQM!'''3 RQ 7hec&ing %al should be greater than eAual to !'''
7L,7K 2%al %,T6,,( !''' A(D ====3 /Q 7hec&ing %al should be within the
range of !''' and ====
7L,7K 2%A* I( 24''', ;''', G'''33 /Q 7hec&ing the %al .hould be within any
of the three values only
7reating 7hec& 7onstraint in column level:
%'/(T/ T(B3/ BanF(%ustid int, %name "arc)ar(<), Bal decimal(G,:)
%onstraint Bal1%; %)ecF (Bal2E1<<<))
7reating 7hec& 7onstraint in table level:
%'/(T/ T(B3/ BanF(%ustid int, %name "arc)ar(<), Bal decimal(G,:),
%onstraint Bal1%; %)ecF(Bal B/TI//9 1<<< (9D JJJJ))
Default &alue: The default value for any column if a not null constraint is not present on
it is S()**T, which can be changed by using the Default 7lause while creating the table
as following:
=
%'/(T/ T(B3/ BanF(%ustid int, %name "arc)ar(<), Bal decimal(G,:)
Default 1<<<)
/In the above case if have not specified any value to the %al column while inserting then
it ta&es !''' as default
I9S/'T I9T+ BanF (%ustid, %name) &(3,/S (1<1, ='a"i>)
Identity Dunction: Denerally for any column if we want to insert only uniAue values
then we can hand over the tas& to the identity function, so that it ta&es the responsibility
of inserting a uniAue value in to the column as following:
%olname 0dtype2 45idt)6 Identity 4(Seed, Incr)6
.eed R It is the starting value for the identity function.
Incr R It is the difference between to subseAuent values generated by the function.
/%oth of them are optional, if not specified ! and ! are ta&en as values.
/6hen we use the identity function on a column we cannot explicitly insert any values
into the column using the insert statement.
/A table can have only one identity column present in it.
/Denerally we use this on Nrimary Key 7olumns.
%'/(T/ T(B3/ BanF(%ustid int identity(1<1, 1), %name "arc)ar(<), Bal
decimal(G,:))
/In this case when we insert rows into the table then it automatically generates a identity
value starting from !'!.
I9S/'T I9T+ BanF (%name, Bal) &(3,/S (='aKu>, !<<)
Doreign ;ey %onstraint: it is a column or combination of columns that is used to
establish and enforce a lin& between the data in two tables. In a foreign &ey reference, a
lin& is created between two tables when the column2s3 in a table reference the column2s3
that hold the primary &ey of other table, which becomes a foreign &ey in the first table.
-or example, the Dept8Deptno table below has a lin& to the /mp8Deptno table because
there is a logical relationship between Dept table and /mp table. The Deptno column in
the /mp table matches the primary &ey column of the Dept table. The Deptno column in
the /mp table is the foreign &ey to the Dept table. In this case the value that is going to
be inserted into the Deptno column of the /mp table should be present in the Deptno
column of the Dept table or should be a null values.
!'
Dept
Emp
/ In this case the Dept table is called as Narent table and ,mp table is called as
7hild table.
/ Dept.Deptno is called as +eference Key column on which either Nrimary Key
7onstraint or )niAue 7onstraint has to be imposed.
/ ,mp.Deptno is called as -oreign Key column on which the -oreign Key
7onstraint has to be imposed, with this only the lin& gets established between the
" tables.
%reate Table Dept (Deptno int %onstraint Deptno1PF Primary ;ey, D9ame
"arc)ar(<), 3oc "arc)ar(<))
18 Insert into Dept "alues (1<, L$arFetingL, L$umbaiL)
:8 Insert into Dept "alues (:<, LSalesL, L%)ennaiL)
!8 Insert into Dept "alues (!<, LDinanceL, LDel)iL)
?8 Insert into Dept "alues (?<, LProductionL, L;olFotaL)
/7reating -oreign Key 7onstraint in column level:
%reate table /mp (/mpno int, /name "arc)ar(1<<), Mob "arc)ar(1<<), $gr
int, @ireDate datetime, Sal $oney, %omm $oney, Deptno int %onstraint
Deptno1'ef 'eferences Dept (Deptno))
/7reating -oreign Key 7onstraint in column level: while defining constraint in table level
we need to explicitly use the -oreign Key clause to specify the -oreign Key 7olumn:
%reate table /mp (/mpno int, /name "arc)ar(1<<), Mob "arc)ar(1<<), $gr
int, @ireDate datetime, Sal $oney, %omm $oney, Deptno int,
%onstraint Deptno1'ef Doreign ;ey (Deptno) 'eferences Dept (Deptno))
/(ow when we try to insert values into the ,mp table the Deptno what we give should be
only the # values 2!', "', 4', #'3 present in the dept table or a null value, if we try to
insert any other value the insert statement fails.
!!
18 Insert into /mp &alues (1<<1, LSures)L, LPresidentL, 9,33, L<1N<1NGOL,
<<<, 9,33, 1<)
:8 Insert into /mp &alues (1<<:, L'ames)L, L$anagerL, 1<<1, L<1N<1NGOL,
?<<<, 9,33, :<)
!8 Insert into /mp &alues (1<<!, L'a"iL, L$anagerL, 1<<1, L<1N<1NGOL,
!<<, 9,33, !<)
?8 Insert into /mp &alues (1<<?, L&iKayL, L$anagerL, 1<<1, L<1N<1NGOL,
?<<<, 9,33, ?<)
8 Insert into /mp &alues (1<<, L(KayL, LSalesmanL, 1<<!, L<:N<?NGJL,
!<<<, 9,33, <)
/In this case the first # statements gets executed but last statement fails because the
Deptno given is not present in the dept table.
The -oreign Key constraint enforces referential integrity by guaranteeing that
changes cannot be made to data in the primary &ey table if those changes invalidate the
lin& to data in the foreign &ey table. If an attempt is made to delete the row in a primary
&ey table or to change a primary &ey value, the action will fail when the deleted or
changed primary &ey value corresponds to a value in the -F+,ID( K,B constraint of
another table. To successfully change or delete a row in a -F+,ID( K,B constraint, you
must first either delete the foreign &ey data in the foreign &ey table or change the foreign
&ey data in the foreign &ey table, which lin&s the foreign &ey to different primary &ey
data.
%y using cascading referential integrity constraints, you can define the actions
that the .:* .erver "''; ta&es when a user tries to delete or update a &ey value in the
master table to which existing foreign &eys point.
The +,-,+,(7,. clauses of the 7+,AT, TA%*, statements support the F(
D,*,T, and F( )NDAT, clauses:
/F( D,*,T, O(F A7TIF( > 7A.7AD, > .,T ()** > .,T D,-A)*TQ
/F( )NDAT, O(F A7TIF( > 7A.7AD, > .,T ()** > .,T D,-A)*TQ
(F A7TIF( is the default if F( D,*,T, or F( )NDAT, is not specified.
F( D,*,T, (F A7TIF(: .pecifies that if an attempt is made to delete a &ey value in
the master table, which is referenced by foreign &eys in other tables, an error is raised and
the D,*,T, statement will not execute.
F( )NDAT, (F A7TIF(: .pecifies that if an attempt is made to update a &ey value in
the master table, which is referenced by foreign &eys in other tables, an error is raised and
the )NDAT, statement will not execute.
!"
6hen (F A7TIF( is specified we can delete or update or delete rows in the master
table if they are referenced by child table rows, but we can perform those operations
when we use 7A.7AD,, .,T ()** A(D .,T D,-A)*T 7*A).,.:
F( D,*,T, 7A.7AD,: .pecifies that if an attempt is made to delete a &ey value in the
master table, which is referenced by foreign &eys in other tables, all rows that contain
those foreign &eys in child table are also deleted.
F( )NDAT, 7A.7AD,: .pecifies that if an attempt is made to update a &ey value in
the master table, which is referenced by foreign &eys in other tables, all the foreign &ey
values will also be updated to the new value specified for the &ey.
F( D,*,T, .,T ()**: .pecifies that if an attempt is made to delete a &ey value in the
master table, which is referenced by foreign &eys in other tables, all rows that contain
those foreign &eys in child table are set to ()**, provided the foreign &ey column
allows ()** values into it.
F( )NDAT, .,T ()**: .pecifies that if an attempt is made to update a &ey value in
the master table, which is referenced by foreign &eys in other tables, all rows that contain
those foreign &eys in child table are set to ()**, provided the foreign &ey column
allows ()** values into it.
F( D,*,T, .,T D,-A)*T: .pecifies that if an attempt is made to delete a &ey value
in the master table, which is referenced by foreign &eys in other tables, all rows that
contain those foreign &eys in child table are set to default value. All foreign &ey columns
of the target table must have a default definition for this constraint to execute. If there is
no explicit default value set, ()** becomes the implicit default value of the column.
F( )NDAT, .,T D,-A)*T: .pecifies that if an attempt is made to update a &ey value
in the master table, which is referenced by foreign &eys in other tables, all rows that
contain those foreign &eys in child table are set to default value. All foreign &ey columns
of the target table must have a default definition for this constraint to execute. If there is
no explicit default value set, ()** becomes the implicit default value of the column.
6e can use any of the rules beside the column as following:
Deptno int %onstraint Deptno1'ef 'eferences Dept (Deptno) on delete
cascade on update cascade
In the same way you can use any rule there and also not mandatory to specify both the
delete and update rule, we can use any rule what we reAuire.
(lter %ommand: After creating a table if we want to ma&e any modifications to the
structure of the table we use the Alter 7ommand. )sing alter command we can perform
the following:
/IncreaseUDecrease the width of a column.
/7hange the data type of a column.
/7hange (ull to (ot (ull and (ot (ull to (ull
!4
/Add a new column to the table.
/Drop an existing column from the table.
/Add a constraint to a column of the table.
/Drop an existing constraint present on a column from the table.
/To perform the first 4 operations the syntax is:
(3T/' T(B3/ 0T9($/2 (3T/' %+3,$9 0%+39($/2 0DTPP/2
4IIDT@6 49,33 C 9+T 9,336
-irst create a table as following:
%'/(T/ T(B3/ Students (S9+ int, Sname "arc)ar(<), %lass int)
Increasing the width of a column:
(3T/' T(B3/ Students (3T/' %+3,$9 Sname "arc)ar(1<<)
Decreasing the width of a column:
(3T/' T(B3/ Students (3T/' %+3,$9 Sname "arc)ar(:)
7hanging the data type of the column:
(3T/' T(B3/ Students (3T/' %+3,$9 Sname n"arc)ar(:)
Adding a (ot (ull 7onstraint:
(3T/' T(B3/ Students (3T/' %+3,$9 Sname n"arc)ar(:) 9ot 9ull
+emoving a (ot (ull 7onstraint:
(3T/' T(B3/ Students (3T/' %+3,$9 Sname n"arc)ar(:) 9ull
.yntax to add a new column:
(3T/' T(B3/ 0T9($/2 (DD 0%+39($/2 0DTPP/2 40IIDT@26
4 4%+9ST'(I9T 0%+9S 9($/26 0%+9S TPP/2 6
Adding a column to the table with out any constraint:
(3T/' T(B3/ Students (DD Dees $oney
Adding a column to the table with a constraint:
(3T/' T(B3/ Students (DD Sid int %onstraint Sid1,H ,9IH,/
.yntax to drop an existing column:
(3T/' T(B3/ 0T9($/2 D'+P %+3,$9 0%+39($/2
Dropping the .id 7olumn:
(3T/' T(B3/ Students D'+P %+3,$9 Sid
.yntax to Add a 7onstraint:
(3T/' T(B3/ 0T9($/2 (DD 4 %+9ST'(I9T 0%+9 9($/2 6 0%+9S
TPP/2 (%+33IST)
Adding a chec& constraint on the -ees column:
(3T/' T(B3/ Students (DD %onstraint Dees1%; %)ecF (Dees21<<)
Adding a primary &ey constraint on the .no column:
(3T/' T(B3/ Students (3T/' %+3,$9 S9+ I9T 9+T 9,33
(3T/' T(B3/ Students (DD %onstraint Sno1P; Primary ;ey(S9+)
.yntax to Drop a 7onstraint:
(3T/' T(B3/ 0T9($/2 D'+P %+9ST'(I9T 0%+9S 9($/2
!#
Dropping the chec& constraint present on the -ees column:
(3T/' T(B3/ Students D'+P %onstraint Dees1%;
Drop %ommand: If we want to destroy the existing tables present in the database we use
the Drop 7ommand.
.yntax: D'+P T(B3/ 0T9($/2
Dropping the .tudents Table:
D'+P T(B3/ Students
Truncate %ommand: +emoves all rows from a table. T+)(7AT, TA%*, is
functionally the same as the D,*,T, statement with no 6L,+, clause specified.
.yntax: T',9%(T/ T(B3/ 0T9($/2
Truncating the ,9N Table:
T',9%(T/ T(B3/ Students
The difference between Truncate and Delete is:
Truncate table is faster in execution.
Truncate will reset the identity function if present on the table to initial value
again which will not happen in delete.
D,9%TI+9S: .:* .erver "''; provides built/in functions that can be used to perform
certain operations. -unctions can be used or included in the following:
/ The select list of a Auery that uses a .,*,7T statement to return a value.
/ A 6L,+, clauses search condition of a .,*,7T statement to limit the rows that
Aualify for the Auery.
.yntax for executing a function:
.,*,7T O-un (ameQ 2 0 OexpressionsQ 1 3
/The expression can be a constant values or a name of a column.
-unctions can be classified into " types:
/.ingle +ow -unctions
/Droup -unctions
A single row function executes once for each row that is present in the table where as
group functions ta&e multiple rows into consideration and returns a single value as
output.
.ingle +ow -unction 7ategories:
/9athematical -unctions
/.tring -unctions
/Date and Time -unctions
/.ystem -unctions
!;
9athematical -unctions: These functions perform a calculation, usually based on input
values that are provided as arguments, and return a numeric value5 they ta&e SnT as input
where n is a numeric expression.
A%. 2n3: A mathematical function that returns the absolute 2positive3 value of the
specified numeric expression.
.elect A%.2!'3 Fuput: !'
.elect A%.2/!'3 Fuput: !'
7,I*I(D 2n3: +eturns the smallest integer greater than, or eAual to, the specified numeric
expression.
.,*,7T 7,I*I(D2!;.C3 F)TN)T: !C
.,*,7T 7,I*I(D2!;.C3 F)TN)T: /!;
7,I*I(D 2n3: +eturns the largest integer less than or eAual to the specified numeric
expression.
.,*,7T -*FF+2!;.C3 F)TN)T: !;
.,*,7T -*FF+2!;.C3 F)TN)T: /!C
*FD 2n3: +eturns the natural logarithm of the specified expression, i.e. base/e
.,*,7T *FD2!'3 F)TN)T: ".4'";$;'="==#';
*FD!' 2n3: +eturns base/!' logarithm of the specified expression, i.e. base e
.,*,7T *FD!'2!'3 F)TN)T: !
NI23: +eturns the constant value of NI.
.,*,7T NI23 F)TN)T: 4.!#!;="C;4;$=G=
NF6,+2n, m3: +eturns the value of the specified expression n to the specified power m.
.,*,7T NF6,+2!', 43 F)TN)T: !'''
+A(D 2 0.,,D1 3: +eturns a random float value from ' through !.
/ .,,D: Is an integer expression that gives the seed value. If seed is not specified, the
Database ,ngine assigns a seed value at random. -or a specified seed value, the result
returned is always the same.
.,*,7T +A(D23 /,ach time we execute we get a random value.
.,*,7T +A(D2!''3 /,ach time we execute we get the same value.
+F)(D ( n , length 0 ,function 1 ): +eturns a numeric expression, rounded to the
specified length or precision.
.,*,7T +F)(D2!;C.;CG, "3 F)TN)T: !;C.;G
.,*,7T +F)(D2!;C.;CG, !3 F)TN)T: !;C.C
.,*,7T +F)(D2!;C.;CG, '3 F)TN)T: !;G
/If the seed is positive rounding will be done after the decimal, if it is negative rounding
will be done before the decimal:
!C
.,*,7T +F)(D2!;C.;CG, /!3 F)TN)T: !C'
.,*,7T +F)(D2!;C.;CG, /"3 F)TN)T: "''
/If we specify the optional parameter function that is an integer value we can decide to
truncate the value or round the value. If it is ' 2default3 rounds the value and value greater
than ' truncates the value.
.,*,7T +F)(D2!;C.;CG, ", !3 F)TN)T: !;C.;C
.,*,7T +F)(D2!;C.;CG, /", !3 F)TN)T: !''
.ID((n): +eturns the positive 2@!3, ero 2'3, or negative 2/!3 sign of the specified
expression.
/ If nO' it returns /!
/ If nM' it returns '
/ If nQ' it returns !
.,*,7T .ID(2/!''3 F)TN)T: /!
.,*,7T .ID(2'3 F)TN)T: '
.,*,7T .ID(2!''3 F)TN)T: !
.:+T2n3: +eturns the sAuare root of the specified expression.
.,*,7T .:+T2$!3 F)TN)T: =
.,*,7T .:+T24'3 F)TN)T: ;.#GG"";;G;';!CC
.:)A+,2n3: +eturns the sAuare of the specified expression.
.,*,7T .:)A+,24;3 F)TN)T: !"";
/Apart from the above it provides with trigonometric function li&e 7F., 7FT, .I(, TA(,
A7F., A.I(, ATA( for which we need to provide the degrees.
.tring -unctions: These functions perform an operation on a string input value and return
a string or numeric value.
A.7II2s3: +eturns the A.7II code value of the leftmost character of the expression.
A.7II2IAH3 F)TN)T: C;
A.7II2I%7DH3 F)TN)T: CC
7LA+2n3: 7onverts the given A.7II code to a character.
7LA+2=G3 F)TN)T: a
(7LA+2n3: +eturns the )nicode character with the specified integer code ranging
between ' to C;, ;4;, as defined by the )nicode standard.
7LA+24''3 F)TN)T: V
7LA+I(D,E2search exp, string exp 0 , startPlocation 1 ): +eturns the starting position of
the search exp in the string exp which can also be a column name.
7LA+I(D,E2IFH, IL,**F 6F+*DH3 F)TN)T: ;
/In this case it returns ; as output because it starts its search from the beginning of the
string, we can change it by using the start location optional parameter.
7LA+I(D,E2IFH, IL,**F 6F+*DH, C3 F)TN)T: $
!G
/6A: to get the details of employees whose name contains the character I9H in it.
.ol: .,*,7T J -+F9 ,9N 6L,+, 7LA+I(D,E2I9H, ,(A9,3Q'
*,-T2s, n3: +eturns the left part of the string with the specified number of characters.
.,*,7T *,-T2IL,**FH, 43 F)TN)T: L,*
/6A: to get the details of employees whose name contains the first " characters as I8,H.
.ol: .,*,7T J -+F9 ,9N 6L,+, *,-T2,(A9,, "3MH8,H
+IDLT2s, n3: +eturns the right part of the string with the specified number of characters.
.,*,7T +IDLT2IL,**FH, 43 F)TN)T: **F
/6A: to get the details of employees whose name ends with characters ITTH.
.ol: .,*,7T J -+F9 ,9N 6L,+, +IDLT2,(A9,, "3MHTTH
.)%.T+I(D2s, start, length3: +eturns a part of a string from string s starting from start
position, where length is the no of chars to be pic&ed.
.,*,7T .)%.T+I(D2IL,**FH, !, 43 F)TN)T: L,*
.,*,7T .)%.T+I(D2IL,**FH, 4, 43 F)TN)T: **F
.,*,7T .)%.T+I(D2IL,**FH, ", 43 F)TN)T: ,**
/6A: to get the details of employees whose names 4
rd
and #
th
characters are ITIH.
.ol: .,*,7T J -+F9 ,9N 6L,+, +IDLT2*,-T2,(A9,, #3, "3MHTIH
.ol: .,*,7T J -+F9 ,9N 6L,+, .)%.T+I(D2,(A9,, 4, "3MHTIH
*,(2s3: +eturns the number of characters of the specified string expression, excluding
trailing blan&s.
.,*,7T *,(2IL,**FH3 F)TN)T: ;
.,*,7T *,(2I L,**FH3 F)TN)T: $
/6A: to get the details of employees whose names was ; characters in length
.ol: .,*,7T J -+F9 ,9N 6L,+, *,(2,(A9,3M;
.,*,7T *,(2IL,**F I3 F)TN)T: ;
*F6,+2s3: +eturns a character expression after converting the given character data to
lowercase.
.,*,7T *F6,+2ILelloH3 F)TN)T: hello
)NN,+2s3: +eturns a character expression after converting the given character data to
uppercase.
.,*,7T )NN,+2ILelloH3 F)TN)T: L,**F
*T+I92s3: +eturns a character expression after it removes leading blan&s.
.,*,7T *,(2*T+I92I L,**FH33 F)TN)T: ;
.,*,7T WL,**F W @ *T+I92W 6F+*DW3 F)TN)T: L,**F 6F+*D
+T+I92s3: +eturns a character expression after it removes trailing blan&s.
.,*,7T +T+I92WL,**F W3 @ W 6F+*DW F)TN)T: L,**F 6F+*D
+,N*A7,2s!, s", s43: +eplaces all occurrences of the s" in s! with s4.
!$
.,*,7T +,N*A7,2IL,**FH, I*H, IEH3 F)TN)T: L,EEF
+,N*I7AT,2s, n3: +epeats the expression IsH for specified InH number of times.
.,*,7T +,N*I7AT,2IL,*H, "3 F)TN)T: L,*L,*
+,8,+.,2s3: +eturns the reverse of the given string IsH.
.,*,7T +,8,+.,2IL,**FH3 F)TN)T: F**,L
.F)(D,E2s3: +eturns a four/character 2.F)(D,E3 code to evaluate the similarity of
two strings. .F)(D,E converts an alphanumeric string to a four/character code to find
similar/sounding words or names. The first character of the code is the first character of
strings and the second through fourth characters of the code are numbers.
.,*,7T .F)(D,E 2W.mithW3, .F)(D,E 2W.mythW3
/Denerally we use then when we perform comparison of words, which are sounded in the
same way but have different spelling li&e color X colour. .uppose in a table the ename of
a person is smith we will get the result even if the statement is written as following:
.,*,7T J -+F9 ,9N 6L,+, .F)(D,E2,(A9,3M.F)(D,E2I.9BTLH3
DI--,+,(7,2.!, ."3: +eturns an integer value that indicates the difference between the
.F)(D,E values of two character expressions. The return value ranges from ' through
#: ' indicates wea& or no similarity, and # indicates strong similarity or the same values.
.,*,7T .F)(D,E2I.9ITLH3, .F)(D,E2W.9BTLW3,
DI--,+,(7,2W.9ITLW,W.9BTLW3
.NA7,2n3: +eturns a string with specified InH number of repeated spaces.
.,*,7T IL,**FH @ .NA7,2!3 @ I6F+*DH F)TN)T: L,**F 6F+*D
.T)--2s, start, length, replacePstr3: +eplaces specified length of characters from
specified starting point with replacePstr in the string IsH
.,*,7T .T)--2IA%EE7DEEH, 4, 4, IBBH3 F)TN)T: A%BBDEE
Date and Time -unctions: The following functions perform an operation on a date and
time input value and return a string, numeric, or date and time value.
D,TDAT,23: +eturns the current date and time of the server in .:* .erver standard
internal format.
.,*,7T D,TDAT,23
DAB2date3: +eturns an integer representing the DAB of the specified date, which has to
be specified in standard .:* .erver date format ImmUddUyyH.
.,*,7T DAB2D,TDAT,233
.,*,7T DAB2I!'U"#UG$H3 F)TN)T: "#
9F(TL2date3: +eturns an integer representing the 9F(TL of the specified date, which
has to be specified in standard .:* .erver date format ImmUddUyyH.
.,*,7T 9F(TL2D,TDAT,233
.,*,7T 9F(TL2I!'U"#UG$H3 F)TN)T: !'
!=
B,A+2date3: +eturns an integer representing the B,A+ of the specified date, which has
to be specified in standard .:* .erver date format ImmUddUyyH.
.,*,7T B,A+2D,TDAT,233
.,*,7T B,A+2I!'U"#UG$H3 F)TN)T: !=G$
DAT,(A9,2datepart, date3: +eturns a character string representing the specified
datepart of the specified date, datepart is the parameter that specifies the part of the date
to return. The following table lists dateparts and abbreviations recognied by .Al .erver:
Datepart (bbre"iations
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw
hour hh
minute mi, n
second ss, s
millisecond ms
.,*,7T DAT,(A9,2mm, I!'U"#UG$H3 F)TN)T: Fctober
.,*,7T DAT,(A9,2dd, I!'U"#UG$H3 F)TN)T: !'
DAT,NA+T2datepart, date3: This is same as DAT,(A9, function but the only
difference is 5eeFday 2d53 of DAT,NA+T function returns a number that corresponds to
the day of the wee&, for example: .unday M !, .aturday M G, where as in the case of
DAT,(A9, returns the value in string format that is .unday, 9onday, Y .aturday.
"'
DAT,ADD2datepart, number, date3: +eturns a new datetime value based on adding an
interval to the specified date, datepart is the value that has to be added and number is the
interval.
.,*,7T DAT,ADD2dd, 4', D,TDAT,233 RAdds 4' days to D,TDAT,23.
.,*,7T DAT,ADD2mm, !C, D,TDAT,233 RAdds !C months to D,TDAT,23.
DAT,DI--2datepart, startdate, enddate3: +eturns the difference between the start and end
dates in the give datepart format.
.,*,7T DAT,DI--2yy, I!'U"#UG$H, D,TDAT,233
D,T)T7DAT,23/+eturns the datetime value representing the current )T7 time
27oordinated )niversal Time or Dreenwich 9ean Time3.
.,*,7T D,T)T7DAT,23
7onversion -unctions: ,xplicitly converts an expression of one data type to another. 6e
has two conversion functions 7A.T and 7F(8,+T, both provide similar functionality.
.yntax for 7A.T:
7A.T 2 expression A. dataPtype 0 2length 3 13
.,*,7T 7A.T2!'.C#=C A. I(T3 F)TN)T: !'
.,*,7T 7A.T2!'.4#=C$#G A. money3 F)TN)T: !'.4#=G
.yntax for 7F(8,+T:
7F(8,+T 2 data_type 0 2 length 3 1 , expression 0 , style 1 3
.,*,7T 7F(8,+T2I(T, !'.C#=C3 F)TN)T: !'
.,*,7T 7F(8,+T28A+7LA+2;'3, D,TDAT,233
.tyle is an optional parameter that can be used to specify a date format used to convert
datetime or smalldatetime data to character. 6hen style is ()**, the result returned is
also ()**. .tyle can be used as following:
.,*,7T 7F(8,+T28A+7LA+2;'3, D,TDAT,23, !'!3
.,*,7T 7F(8,+T28A+7LA+2;'3, D,TDAT,23, !'"3
/,ach style will give the output of the date in a different format the default style it uses is
!''. The style values can be ranging between !''/!!#, !"', !"!, !"C, !"G, !4' and !4!
or ' to $, !', !!, !" and !# in this case century part will not returned.
.,*,7T 7F(8,+T28A+7LA+2;'3, D,TDAT,23, !3
.ystem -unctions:
I.()9,+I72 expression 3: Determines whether an expression is a valid numeric type. If
it is numeric it returns ! else return '.
.,*,7T I.()9,+I72!''3 F)TN)T: !
.,*,7T I.()9,+I72I!''H3 F)TN)T: !
.,*,7T I.()9,+I72I!''AH3 F)TN)T: '
"!
I.DAT, 2expression3: Determines whether an input expression is a valid date or not. If it
is a valid date it returns ! else return '. 8alid date in the sense the expression, which is
present in mmUddUyy format.
.,*,7T I.DAT,2W!"U"!U=$W3 F)TN)T: !
.,*,7T I.DAT,2W"!U!"U=$W3 F)TN)T: '
I.()** 2expression!, expression"3: if expression! is null then it returns expression".
.,*,7T I.()**2!'', "''3 F)TN)T: !''
.,*,7T I.()**2()**, "''3 F)TN)T: "''
.,*,7T ,9N(F, ,(A9,, .A*, 7F99, .A* @ 7F99 A. 0TFTA* .A*1
-+F9 ,9N
/In above case if any of the value in the comm. Is null it returns null in the Total .al
because any arithmetic operations performed on a null value results to null only at this
time the statement has to be written as following:
.,*,7T ,9N(F, ,(A9,, .A*, 7F99, .A* @ I.()**27F99, '3 A.
0TFTA* .A*1 -+F9 ,9N
7FA*,.7, 2expression!, expression", YY expression n3: +eturns the first not null
expression in the list of expressions given, similar to isnull but we can give multiple
values here.
.,*,7T 7FA*,.7,2()**, !'', ()**, "''3 F)TN)T: !''
.,*,7T ,9N(F, ,(A9,, .A*, 7F99, .A* @ 7FA*,.7,27F99, '3 A.
0TFTA* .A*1 -+F9 ,9N
DATA*,(DTL 2expression3 : +eturns the number of bytes used to represent any
expression.
.,*,7T DATA*,(DTL2!''3 F)TN)T: #
.,*,7T DATA*,(DTL2IL,**FH3 F)TN)T: ;
LF.TP(A9,23: +eturns the name of the wor&station.
.,*,7T LF.TP(A9,23
ID,(TP7)++,(T2WtablePnameW3: +eturns the last identity value generated for a
specified table by the identity function.
.,*,7T ID,(TP7)++,(T2I%A(KH3
ID,(TP.,,D2WtablePnameW3: +eturns the seed value that was specified when the identity
function in a table was created.
.,*,7T ID,(TP.,,D2I%A(KH3
ID,(TPI(7+2WtablePnameW3: +eturns the increment value that was specified when the
identity function in a table was created.
.,*,7T ID,(TPI(7+2I%A(KH3
(,6ID2 3: 7reates a uniAue value of type uniAueidentifier.
.,*,7T (,6ID23
""
()**I-2expression!, expression"3: +eturns the first expression if the two expressions
are not eAuivalent. If the expressions are eAuivalent, returns a null value.
.,*,7T ()**I-2!'', "''3 F)TN)T: !''
.,*,7T ()**I-2!'', !''3 F)TN)T: ()**
+F67F)(TP%ID23: +eturns the number of rows affected by the last statement
executed. If we use this after a select statement it will return us the number of rows the
select statement has returned.
.,*,7T J -+F9 ,9N
.,*,7T +F67F)(TP%ID -+F9 ,9N
ANNP(A9,23: +eturns the name of the application from where the statement is
executed.
.,*,7T ANNP(A9,23
7A.,: ,valuates a list of conditions and returns one of multiple possible result
expressions. It has two formats:
/The simple 7A., function compares an expression to a set of simple expressions to
determine the result.
/The searched 7A., function evaluates a set of %oolean expressions to determine the
result.
/ %oth formats support an optional ,*., argument.
7A., OexpressionQ
6L,( whenPexpression TL,( resultPexpression
6L,( whenPexpression TL,( resultPexpression
YYYYYYYYYY
,*., elsePresultPexpression
,(D
/In this case if the expression matches with any of the whenPexpression it returns the
corresponding resultPexpression, if it does not match with any then it returns
elsePresultPexression.
.,*,7T ,9N(F, ,(A9,, .A*, <F%,
27A., <F%
6L,( IN+,.ID,(TH TL,( I%ID %F..H
6L,( I9A(AD,+H TL,( I%F..H
6L,( IA(A*B.TH TL,( I.7I,(TI.TH
,*., I,9N*FB,,H
,(D3 A. 7F99,(T. -+F9 ,9N
.,*,7T ,9N(F, ,(A9,, <F%, .A*,
27A., .ID(2.A*/4'''3
6L,( ! TL,( IA%F8, TA+D,TH
6L,( ' TL,( IF( TA+D,TH
6L,( R! TL,( I%,*F6 TA+D,TH
"4
,(D3 A. 7F99,(T. -+F9 ,9N
/The above statement can be written in one more way also by using the second format of
the 7A., function.
7A.,
6L,( condition TL,( resultPexpression
6L,( condition TL,( resultPexpression
YYYYYYYYYY
,*., elsePresultPexpression
,(D
.,*,7T ,9N(F, ,(A9,, <F%, .A*,
27A.,
6L,( .A*Q4''' TL,( IA%F8, TA+D,TH
6L,( .A*M4''' TL,( IF( TA+D,TH
6L,( .A*O4''' TL,( I%,*F6 TA+D,TH
,(D3 A. 7F99,(T. -+F9 ,9N
.et Fperators:
7F)(T2expression3: +eturns the number of items in a group.
.,*,7T 7F)(T2J3 -+F9 ,9N
.,*,7T 7F)(T2J3 -+F9 ,9N 6L,+, D,NT(FM"'
.,*,7T 7F)(T27F993 -+F9 ,9N
7F)(TP%ID2expression3: 7F)(TP%ID wor&s li&e the 7F)(T function. The only
difference between the two functions is their return values. 7F)(TP%ID always returns
a bigint data type value. 7F)(T always returns an int data type value.
.,*,7T 7F)(TP%ID2J3 -+F9 ,9N
.)92expression3: +eturns the sum of all the values. .)9 can be used with numeric
columns only. (ull values are ignored
.,*,7T .)92.A*3 -+F9 ,9N
A8D2expression3: +eturns the average of the values in a group. (ull values are ignored.
.,*,7T A8D2.A*3 -+F9 ,9N
9AE2expression3: +eturns the maximum value in the expression.
.,*,7T 9AE2.A*3 -+F9 ,9N
9I(2expression3: +eturns the minimum value in the expression.
.,*,7T 9I(2.A*3 -+F9 ,9N
.TD,82expression3: +eturns the statistical standard deviation of all values in the
specified expression.
"#
.,*,7T .TD,82.A*3 -+F9 ,9N
8A+2expression3: +eturns the statistical variance of all values in the specified expression.
.,*,7T 8A+2.A*3 -+F9 ,9N
Fperators: An operator is a symbol specifying an action that is performed on one or more
expressions. The lists the operator categories that .:* .erver supports:
/Arithmetic Fperators
/Assignment Fperator
/7omparison Fperators
/*ogical Fperators
/7oncatenation Fperator
Arithmetic Fperators: Arithmetic operators perform mathematical operations on two
expressions of one or more of the data types of the numeric data type category. Those are:
@ / Addition
/ / .ubtraction
J / 9ultiplication
U / Division
Z / 9odulo
Assignment Fperators: The eAual sign 2M3 is the only assignment operator.
7omparison Fperators: 7omparison operators test whether two expressions are the same.
7omparison operators can be used on all expressions except expressions of the te*t,
nte*t, or image data types. Those are:
M / ,Aual to
Q / Dreater than
O / *ess than
QM / Dreater than or eAual to
OM / *ess than or eAual to
OQ / eAual to
[M / not eAual to
[O / not less than
[Q / not greater than
*ogical Fperators: *ogical operators test for the truth of some condition. *ogical
operators, li&e comparison operators, return a Boolean value of T+), or -A*.,.
Those are:
A** T+), if all of a set of comparisons are T+),
A(D T+), if both %oolean expressions are T+),
A(B T+), if any one of a set of comparisons are T+),
%,T6,,( T+), if the operand is within a range
,EI.T. T+), if a subAuery contains any rows
I( T+), if the operand is eAual to one of a list of expressions.
*IK, T+), if the operand matches a pattern
";
(FT +everses the value of any other %oolean operator
F+ T+), if either %oolean expression is T+),
.F9, T+), is some of a set of comparisons are T+),
.tring 7oncatenation Fperator: The plus sign 2@3 is the string concatenation operator that
enables string concatenation.
/6A: to find the details of employees whose job is 7*,+K.
.ol: .,*,7T J -+F9 ,9N 6L,+, <F%MH7*,+KH
/6A: to find the details of all employees except .A*,.9A(.
.ol: .,*,7T J -+F9 ,9N 6L,+, <F% [M I.A*,.9A(H
2F+3
.ol: .,*,7T J -+F9 ,9N 6L,+, <F% OQ I.A*,.9A(H
/6A: to find the details of employees who are earning more than 4'''
.ol: .,*,7T J -+F9 ,9N 6L,+, .A*Q4'''
/6A: to find the details of employees who are earning less than ";''
.ol: .,*,7T J -+F9 ,9N 6L,+, .A*O";''
/6A: to find the details of employees who are earning with in a range of ";'' and #'''
.ol: .,*,7T J -+F9 ,9N 6L,+, .A*QM";'' A(D .A*OM#'''
.ol: .,*,7T J -+F9 ,9N 6L,+, .A* %,T6,,( ";'' A(D #'''
/%etween operator is used for specifying with a range of values to test.
/6A: to find the details of employees who are earning less than !;'' as well as more
than 4;''
.ol: .,*,7T J -+F9 ,9N 6L,+, .A*O!;'' F+ .A*Q4;''
.ol: .,*,7T J -+F9 ,9N 6L,+, .A* (FT %,T6,,( !;'' A(D 4;''
/6A: to find the details of employees whose jobs are 7*,+K, 9A(AD,+ A(D
.A*,.9A(
.ol: .,*,7T J -+F9 ,9N 6L,+, <F%MH7*,+KH F+ <F%MH9A(AD,+H F+
<F%MH.A*,.9A(H
.ol: .,*,7T J -+F9 ,9N 6L,+, <F% I( 2H7*,+KH, H9A(AD,+H,
H.A*,.9A(H3
/In Fperator Determines whether a specified value matches any value in the list.
/6A: to find the details of all employees except N+,.ID,(T A(D 9A(AD,+.
.ol: .,*,7T J -+F9 ,9N 6L,+, <F% [M H9A(AD,+H A(D <F% [M
HN+,.ID,(TH
.ol: .,*,7T J -+F9 ,9N 6L,+, <F% (FT I( 2H9A(AD,+H, HN+,.ID,(TH3
"C
/6A: to find the details of employees who name starts with character ..
.ol: .,*,7T J -+F9 ,9N 6L,+, ,(A9, *IK, I.ZH
/*i&e Fperator determines whether a specific character string matches a specified pattern.
A pattern can include regular characters and wildcard characters. During pattern
matching, regular characters must exactly match the characters specified in the character
string. Lowever, wildcard characters can be matched with arbitrary fragments of the
character string. )sing wildcard characters ma&es the *IK, operator more flexible than
using the M and [M string comparison operators.
Z / it represents any string of ero or more characters.
/6A: to find the details of employees whose name contains 9 in it.
.ol: .,*,7T J -+F9 ,9N 6L,+, ,(A9, *IK, IZ9ZH
/6A: to find the details of employees whose name is .9ITL, when the spelling of the
name is not &nown exactly as .9ITL F+ .9BTL.
.ol: .,*,7T J -+F9 ,9N 6L,+, ,(A9, *IK, I.9PTLH
F+
.ol: .,*,7T J -+F9 ,9N 6L,+, .F)(D,E2,(A9,3M.F)(D,E2I.9BTLH3
P2underscore3 / it represents any single character.
6A: to find the details of employees whose name starts with a characters between A to
..
.ol: .,*,7T J -+F9 ,9N 6L,+, ,(A9, *IK, I0A/.1ZH
0 1 R it represents any single character within the specified range 20a/f13 or set
20abcdef13.
6A: to find the details of employees whose name starts with any of the character
SA%7D,T.
.ol: .,*,7T J -+F9 ,9N 6L,+, ,(A9, *IK, I0A%7D,1ZH
6A: to find the details of employees whose name starts with a characters not between A
to ..
.ol: .,*,7T J -+F9 ,9N 6L,+, ,(A9, *IK, I0?A/.1ZH
6A: to find the details of employees whose name starts with characters apart from
SA%7D,T
.ol: .,*,7T J -+F9 ,9N 6L,+, ,(A9, *IK, I0?A%7D,1ZH
F+
.ol: .,*,7T J -+F9 ,9N 6L,+, ,(A9, (FT *IK, I0A%7D,1ZH
6A: to find the details of employees whose job is 7*,+K and earning 4'''.
.ol: .,*,7T J -+F9 ,9N 6L,+, <F%MH7*,+KH A(D .A*M4'''
"G
6A: to find the details of employees whose job is 9A(AD,+ as well as earning more
than 4'''.
.ol: .,*,7T J -+F9 ,9N 6L,+, <F%MH9A(AD,+H F+ .A*Q4'''
6A: to find the details of employees whose salary is not eAual to 4'''.
.ol: .,*,7T J -+F9 ,9N 6L,+, (FT .A*M4'''
.et Fperators: 7ombines the results of two or more Aueries into a single result set.
The following are basic rules for combining the result sets of two Aueries by using .,T
Fperators:
The number and the order of the columns must be the same in all Aueries.
The data types must be compatible.
)(IF(: 7ombines the results of two or more Aueries into a single result set that includes
all the rows that belong to all Aueries in the union.
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM!'
)(IF(
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM4'
)(IF( A**: These is same as )(IF( but in this case duplicates will not be eliminated.
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM!'
)(IF( A**
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM4'
I(T,+.,7T: +eturns any distinct values that are returned by both the Auery on the left
and right sides of the I(T,+.,7T operand.
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM!'
I(T,+.,7T
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM4'
,E7,NT: +eturns any distinct values from the Auery to the left of the ,E7,NT operand
that are not also returned from the right Auery.
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM!'
,E7,NT
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM4'
7*A).,.: .:* .erver provides with the following clauses that can be used in the
.,*,7T statements:
6L,+,
D+F)N %B
LA8I(D
F+D,+ %B
The complete syntax of the .,*,7T statement loo&s as following:
"$
.,*,7T OselectPlistQ -+F9 OtnameQ
0 6L,+, searchPcondition 1
0 D+F)N %B groupPbyPexpression 1
0 LA8I(D searchPcondition 1
0 F+D,+ %B orderPexpression 0 A.7 > D,.7 1 1
6L,+, 7lause: The 6L,+, clause is a filter that defines the conditions each row in
the source tables must meet to Aualify for the .,*,7T. Fnly rows that meet the
conditions contribute data to the result set. Data from rows that do not meet the
conditions is not used.
.,*,7T J -+F9 ,9N 6L,+, <F%MH9A(AD,+H
.,*,7T J -+F9 ,9N 6L,+, D,NT(FM"'
D+F)N %B 7lause: The D+F)N %B clause partitions the result set into groups based on
the values in the columns of the group_by_list. -or example, the /mp table has 4 values
in Deptno column. A D+F)N %B Deptno clause partitions the result set into 4 groups,
one for each value of Deptno.
6A: to find the highest salaries for each department.
.ol: .,*,7T D,NT(F, 9AE2.A*3 -+F9 ,9N D+F)N %B D,NT(F
6A: to find the highest salaries for each job.
.ol: .,*,7T <F%, 9AE2.A*3 -+F9 ,9N D+F)N %B <F%
6A: to find the highest salaries for each department in it for each job.
.ol: .,*,7T D,NT(F, <F%, 9AE2.A*3 -+F9 ,9N D+F)N %B D,NT(F, <F%
(ote: 6hile using the D+F)N %y clause the selectPlist of the Auery should contain only
the following:
/Droup -unctions or Aggregate -unctions
/7olumns used in the Droup %y 7lause
/7onstants.
6A: to find the number of employees wor&ing for each department.
.ol: .,*,7T D,NT(F, 7F)(T2J3 -+F9 ,9N D+F)N %B D,NT(F
6A: to find the number of employees wor&ing for each department only if the number is
greater than 4.
.ol: .,*,7T D,NT(F, 7F)(T2J3 -+F9 ,9N D+F)N %B D,NT(F LA8I(D
7F)(T2J3Q4
LA8I(D 7lause: The LA8I(D clause is an additional filter that is applied to the result
set. *ogically, the LA8I(D clause filters rows from the intermediate result set built from
applying any -+F9, 6L,+,, or D+F)N %B clauses in the .,*,7T statement.
LA8I(D clauses are typically used with a D+F)N %B clause.
"=
6A: to find the number of 7ler&Hs wor&ing for each department.
.ol: .,*,7T D,NT(F, 7F)(T2J3 -+F9 ,9N 6L,+, <F%MH7*,+KH D+F)N %B
D,NT(F
6A: to find the number of 7ler&Hs wor&ing for each department only if the count is
greater than !.
.ol: .,*,7T D,NT(F, 7F)(T2J3 -+F9 ,9N 6L,+, <F%MH7*,+KH D+F)N %B
D,NT(F LA8I(D 7F)(T2J3Q!
F+D,+ %B order_list0 A.7 > D,.7 1
The F+D,+ %B clause defines the order in which the rows in the result set are sorted.
order_list specifies the result set columns that ma&e up the sort list. The A.7 and D,.7
&eywords are used to specify if the rows are sorted in an ascending or descending
seAuence.
.,*,7T J -+F9 ,9N F+D,+ %B .A*
.,*,7T J -+F9 ,9N F+D,+ %B .A* D,.7
.,*,7T J -+F9 ,9N F+D,+ %B .A*, 7F99
.)%:),+B: A subAuery is a Auery that is nested inside a .,*,7T, I(.,+T, )NDAT,,
or D,*,T, statement, or inside another subAuery. A subAuery can be used anywhere an
expression is allowed. In this case first the inner Auery executes and basing upon the
result generated by it the outer Auery executes to generate the final output.
6A: to find the details of employees earning the highest salary.
.ol: .,*,7T J -+F9 ,9N 6L,+, .A*M
2.,*,7T 9AE2.A*3 -+F9 ,9N3
6A: to find the details of employees earning the second highest salary.
.ol: .,*,7T J -+F9 ,9N 6L,+, .A*M
2.,*,7T 9AE2.A*3 -+F9 ,9N 6L,+, .A*O
2.,*,7T 9AE2.A*3 -+F9 ,9N33
6A: to find the details of employees wor&ing in sales department.
.ol: .,*,7T J -+F9 ,9N 6L,+, D,NT(FM
2.,*,7T D,NT(F -+F9 D,NT 6L,+, D(A9,MH.A*,.H3
6A: to find the details of employees wor&ing in 9umbai.
.ol: .,*,7T J -+F9 ,9N 6L,+, D,NT(FM
2.,*,7T D,NT(F -+F9 D,NT 6L,+, *F7MH9)9%AIH3
6A: to find the details of employees who are earning more than the highest salary of
deptno 4'
.ol: .,*,7T J -+F9 ,9N 6L,+, .A*Q
2.,*,7T 9AE2.A*3 -+F9 ,9N 6L,+, D,NT(FM4'3
4'
F+
.,*,7T J -+F9 ,9N 6L,+, .A*Q
A** 2.,*,7T .A* -+F9 ,9N 6L,+, D,NT(FM4'3
/In this case we can use the A** operator which will compare an expression with set of
values, where the expression has to satisfy the condition with all the values.
6A: to find the details of employees who are earning less than the lowest salary of
deptno "'
.ol: .,*,7T J -+F9 ,9N 6L,+, .A*O
2.,*,7T 9I(2.A*3 -+F9 ,9N 6L,+, D,NT(FM"'3
F+
.,*,7T J -+F9 ,9N 6L,+, .A*O
A**2.,*,7T .A* -+F9 ,9N 6L,+, D,NT(FM"'3
6A: to find the details of employees who are earning less than the highest salary of
deptno !'
.ol: .,*,7T J -+F9 ,9N 6L,+, .A*O
2.,*,7T 9AE2.A*3 -+F9 ,9N 6L,+, D,NT(FM!'3
F+
.,*,7T J -+F9 ,9N 6L,+, .A*O
A(B2.,*,7T .A* -+F9 ,9N 6L,+, D,NT(FM!'3
/In the place of A(B we can use .F9, operator also.
/ In this case we can use the A(BU.F9, operator. which will compare an expression
with set of values, where the expression has to satisfy the condition with at least a single
value.
6A: to find the details of employees who are earning the highest salary in each
department.
.,*,7T J -+F9 ,9N 6L,+, .A* I(
2.,*,7T 9AE2.A*3 -+F9 ,9N D+F)N %B D,NT(F3
6A: to find the details of seniors in each department.
.,*,7T J -+F9 ,9N 6L,+, LI+,DAT, I(
2.,*,7T 9I(2LI+,DAT,3 -+F9 ,9N D+F)N %B D,NT(F3
7orrelated .ubAueries: 9any Aueries can be evaluated by executing the subAuery once
and substituting the resulting value or values into the 6L,+, clause of the outer Auery.
In Aueries that include a correlated subAuery 2also &nown as a repeating subAuery3, the
subAuery depends on the outer Auery for its values. This means that the subAuery is
executed repeatedly, once for each row that might be selected by the outer Auery.
6A: to find the details of employees earning the highest salary.
.ol: .,*,7T J -+F9 ,9N , 6L,+, 'M
2.,*,7T 7F)(T2DI.TI(7T .A*3 -+F9 ,9N 6L,+, .A*Q,..A*3
4!
6A: to find the details of employees earning the second highest salary.
.ol: .,*,7T J -+F9 ,9N , 6L,+, !M
2.,*,7T 7F)(T2DI.TI(7T .A*3 -+F9 ,9N 6L,+, .A*Q,..A*3
/In this case if we want the n th highest salary we need to substitute n/! value in the
where condition of the outer Auery.
6A: to find the details of departments in which employees are wor&ing.
.ubAuery: .,*,7T J -+F9 D,NT 6L,+, D,NT(F I(
2.,*,7T DI.TI(7T D,NT(F -+F9 ,9N3
7orrelated .ubAuery: .,*,7T J -+F9 D,NT 6L,+, ,EI.T.
2.,*,7T D,NT(F -+F9 ,9N 6L,+,
,9N.D,NT(FMD,NT.D,NT(F3
/,EI.T. is an operator which is used to specifies a subAuery to test for the existence of
rows.
6A: to find the details of departments in which employees are not wor&ing.
.ubAuery: .,*,7T J -+F9 D,NT 6L,+, D,NT(F (FT I(
2.,*,7T DI.TI(7T D,NT(F -+F9 ,9N3
7orrelated .ubAuery: .,*,7T J -+F9 D,NT 6L,+, (FT ,EI.T.
2.,*,7T D,NT(F -+F9 ,9N 6L,+,
,9N.D,NT(FMD,NT.D,NT(F3
6A: to find the details of employees who have subordinates under them.
.ubAuery: .,*,7T J -+F9 ,9N 6L,+, ,9N(F I(2
.,*,7T DI.TI(7T 9D+ -+F9 ,9N3
7orrelated .ubAuery: .,*,7T J -+F9 ,9N , 6L,+, ,EI.T. 2
.,*,7T J -+F9 ,9N 9 6L,+, ,.,9N(FM9.9D+3
6A: to find the details of employees who doesnHt have any subordinates under them.
.ubAuery: .,*,7T J -+F9 ,9N 6L,+, ,9N(F (FT I(2
.,*,7T DI.TI(7T 9D+ -+F9 ,9N3
7orrelated .ubAuery: .,*,7T J -+F9 ,9N , 6L,+, (FT ,EI.T. 2
.,*,7T J -+F9 ,9N 9 6L,+, ,.,9N(FM9.9D+3
<FI(.: %y using joins, you can retrieve data from two or more tables based on logical
relationships between the tables. <oins indicate how database 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 Auery by:
.pecifying the column from each table to be used for the join. A typical join
condition specifies a foreign &ey from one table and its associated &ey in the other
table.
.pecifying a logical operator 2for example, M or OQ,3 to be used in comparing
values from the columns.
4"
Types of <oins:
!. ,Aui/<oins
". (on ,Aui/<oins
4. .elf <oins
#. 7artesian <oins
;. Futer <oins
*eft Futer <oin
+ight Futer <oin
,Aui/<oins: It returns the specified columns from both the tables, and returns only the
rows for which there is an eAual value in the join column.
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N ,, D,NT D
6L,+, ,.D,NT(FMD.D,NT(F
/The above statement is &nown, as old/style join statement, which will combine the tables
basing on eAuality condition i.e. the Deptno column in the ,mp table, has to have an
exact match of Deptno in the Dept table, then these " rows combine and get retrieved. In
the new/style we call this as Inner <oin where we write the statement as following:
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N , I((,+ <FI( D,NT D
F( ,.D,NT(FMD.D,NT(F
/In the same way if we want to combine multiple table in old/style we write following:
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7,
DD.DID, DD.7F99,(T.
-+F9 ,9N ,, D,NT D, D,NTD,TAI*. DD
6L,+, ,.D,NT(FMD.D,NT(F A(D D.D,NT(FMDD.D,NT(F
/The same statement in the new/style we write as following:
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7,
DD.DID, DD.7F99,(T.
-+F9 ,9N , I((,+ <FI( D,NT D
F( ,.D,NT(FMD.D,NT(F
I((,+ <FI( D,NTD,TAI*. DD
F( D.D,NT(FMDD.D,NT(F
44
(on ,Aui/<oins: Bou can also join values in two columns that are not eAual. The same
operators and predicates used for eAui/joins can be used for not/eAui joins.
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*,
...A*D+AD,, ..*F.A*, ..LI.A*
-+F9 ,9N ,, .A*D+AD, .
6L,+, ,..A* %,T6,,( ..*F.A* A(D ..LI.A*
/6e can write the above statement using inner join in the new style as following:
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*,
...A*D+AD,, ..*F.A*, ..LI.A*
-+F9 ,9N , I((,+ <FI( .A*D+AD, .
F( ,..A* %,T6,,( ..*F.A* A(D ..LI.A*
.elf <oin: If a table has a reflexive relationship in the database, you can join it to itself
automatically which is &nown as self join.
.,*,7T
DI.TI(7T ,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F
-+F9 ,9N ,, ,9N 9
6L,+, ,.,9N(FM9.9D+
/6e can write the above statement using inner join in the new style as following:
.,*,7T
DI.TI(7T ,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F
-+F9 ,9N , I((,+ <FI( ,9N 9
F( ,.,9N(FM9.9D+
7artesian <oin: A 7artesian join that does not have a 6L,+, clause produces the
7artesian product of the tables involved in the join. The sie of a 7artesian product result
set is the number of rows in the first table multiplied by the number of rows in the second
table. This is also &nown as cross/join. Lowever, if a 6L,+, clause is added, the cross
join behaves as an inner join.
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N ,, D,NT D
/6e can write the above statement in the new style as following:
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N , 7+F.. <FI( D,NT D
4#
Futer <oin: %y default, when we join multiple tables using inner join what we get is the
matching data from the tables, if we want to include data rows in the result set that do not
have a match in the joined table, we can us outer join.
The old/style of outer joins have been classified into " types as *eft Futer <oin and +ight
Futer <oin.
6e use *eft Futer <oin to get the matching information plus unmatched information from
left hand side table, in the same way we use +ight Futer <oin to get the matching
information plus unmatched information from right hand side table.
*eft hand side table and right hand side tables are referred in the order we write in the
from clause, first table is *L. table and second table is +L. table.
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N ,, D,NT D
6L,+, ,.D,NT(FMJD.D,NT(F
/In the above case we get the matching information plus unmatched information from
Dept table.
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N ,, D,NT D
6L,+, ,.D,NT(FJMD.D,NT(F
/In the above case we get the matching information plus unmatched information from
,mp table.
/.uppose we have unmatched information in both the sides we cannot retrieve it at the
same time to over come this in the new/style of join statement they have introduced -ull
Futer join. .o the new/style supports use the following:
*,-T F)T,+ <FI(
+IDLT F)T,+ <FI(
-)** F)T,+ <FI(
/)se *eft Futer <oin to get the unmatched information from left hand side table as
following:
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N , *,-T F)T,+ <FI( D,NT D
F( ,.D,NT(FMD.D,NT(F
/)se +ight Futer <oin to get the unmatched information from right hand side table as
following:
4;
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N , +IDLT F)T,+ <FI( D,NT D
F( ,.D,NT(FMD.D,NT(F
/)se -ull Futer <oin to get the unmatched information from both the tables as following:
.,*,7T
,.,9N(F, ,.,(A9,, ,..A*, ,.D,NT(F,
D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N , -)** F)T,+ <FI( D,NT D
F( ,.D,NT(FMD.D,NT(F
-inally concluding in the new/style we have only 4 types of joins those are Inner <oins,
7ross <oins and Futer <oins in the place of ,Aui/<oins, (on ,Aui/<oins, .elf <oins,
7artesian <oins and Futer <oins which are present in the old/style.
Transactions
A transaction is a single unit of wor&.
If a transaction is successful, all of the data modifications made during the
transaction are committed and become a permanent part of the database.
If a transaction encounters errors and must be canceled or rolled bac&, then all of
the data modifications are erased.
.:* .erver operates in the following transaction modes:
!. Autocommit transactions: ,ach individual statement is a transaction.
". ,xplicit transactions: ,ach transaction is explicitly started with the %,DI(
T+A(.A7TIF( statement and explicitly ended with a 7F99IT or
+F**%A7K statement.
4. Implicit transactions: A new transaction is implicitly started when the prior
transaction completes, but each transaction is explicitly completed with a
7F99IT or +F**%A7K statement.
%y Default .:* .erver uses Auto7ommit Transactions i.e. after executing each
statement it will automatically 7ommit it.
If we want to use the ,xplicit Transactions before executing the statements we
need to start with a %egin Transaction statement and then decide whether it has to
be commited or rolledbac&, until the transaction ends the records gets loc&ed.
If we want to use the Implicit Transactions we should use the following
.tatement:
.,T I9N*I7ITPT+A(.A7TIF(. F( > F--
4C
6hen F(, .,T I9N*I7ITPT+A(.A7TIF(. sets the connection into implicit
transaction mode. 6hen F--, it returns the connection to autocommit transaction
mode.
To 9anage the Transactions we have the T7* 2Transaction 7ontrol *anguage3
with 4 commands in it 7ommit, +ollbac& and .ave Transaction.
7ommit: 9ar&s the end of a successful implicit or explicit transaction. 7F99IT
T+A(.A7TIF( ma&es all data modifications performed since the start of the
transaction a permanent part of the database, frees the resources held by the transaction.
%egin Transaction
D,*,T, -+F9 ,9N 6L,+, ,9N(FM!'!;
7F99IT
+ollbac&: +olls bac& an explicit or implicit transaction to the beginning of the
transaction, or to a savepoint inside the transaction.
%egin Transaction
D,*,T, -+F9 ,9N 6L,+, ,9N(FM!'!#
+F**%A7K
.ave Transaction: A user can set a savepoint, or mar&er, within a transaction. The
savepoint defines a location to which a transaction can return if part of the transaction is
conditionally canceled. If a transaction is rolled bac& to a savepoint, it must proceed to
completion with more Transact/.:* statements if needed and a 7F99IT
T+A(.A7TIF( statement, or it must be canceled altogether by rolling the transaction
bac& to its beginning. To cancel an entire transaction, use the +F**%A7K
T+A(.A7TIF( statements.
BEGIN TRANSACTION
UPDATE EMP SET SAL=5000 WHERE EMPNO=1001
SAVE TRANSACTION S1
UPDATE EMP SET SAL=5000 WHERE EMPNO=1002
SAVE TRANSACTION S2
UPDATE EMP SET SAL=5000 WHERE EMPNO=1003
ROLLBACK TRANSACTION S2 OR Rollba! ROLLBACK TRANSACTION S1
COMMIT
/In the above case either the last statement gets rolled bac& or the last " statements gets
rolled bac& and commits the rest.
%reating a table from an e*isting table: 6e can create a table from an existing table
maintain a copy of the actual table before manipulating the data.
.yntax: .,*,7T O J > O7F**I.T Q I(TF O(,6 T(A9,Q -+F9 OF*D T(A9,Q
07F(DITIF(.1
.,*,7T J I(TF (,6P,9N -+F9 ,9N
4G
/In this case it creates a table (,6P,9N by copying all the rows and columns of the
,9N table.
.,*,7T ,9N(F, ,(A9,, .A*, D,NT(F I(TF T,.TP,9N -+F9 ,9N
/In this case it creates a table T,.TP,9N with only the specified columns from the ,9N
table.
.,*,7T J I(TF .A*,.P,9N -+F9 ,9N 6L,+, D,NT(FM2.,*,7T
D,NT(F -+F9 D,NT 6L,+, D(A9,MH.A*,.H3
/In this case it creates a table .A*,.P,9N with only the information of sales department
from the ,9N table.
.,*,7T J I(TF D)99BP,9N -+F9 ,9N 6L,+, !M"
/In this case it creates the D)99BP,9N table with out any data in it.
%opying data from one e*isting table to anot)er table: 6e can copy the data from one
table into another table by using a combination of insert and select statement as
following:
.yntax: I(.,+T I(TF OT(A9,Q 0 27F**I.T3 1
.,*,7T O J > O7F**I.TQ -+F9 OT(A9,Q 07F(DITIF(.1
I(.,+T I(TF D)99BP,9N .,*,7T J -+F9 ,9N
/In this case all the rows of ,9N table is copied into D)99BP,9N table.
I(.,+T I(TF D)99BP,9N 2,9N(F, ,(A9,, .A*, D,NT(F3
.,*,7T ,9N(F, ,(A9,, .A*, D,NT(F -+F9 ,9N 6L,+,
D,NT(FM4'
/In this case it copies only the selected columns into the D)99BP,9N table from the
,9N table.
&I/IS
A view can be thought of as either a virtual table or a stored Auery, li&e a real
table, a view consists of a set of named columns and rows of data.
)nless a view is indexed, its data is not stored in the database as a distinct object.
6hat is stored in the database is a .,*,7T statement.
The result set of the .,*,7T statement forms the virtual table returned by the
view.
A user can use this virtual table by referencing the view name in Transact/.:*
statements the same way a table is referenced.
The rows and columns of data come from tables referenced in the Auery defining
the view and are produced dynamically when the view is referenced.
A view acts as a filter on the underlying tables referenced in the view.
4$
The Auery that defines the view can be from one or more tables or from other
views in the current or other databases.
There are no restrictions on Auerying through views and few restrictions on
modifying data through them.
Synta*: %'/(T/ &I/I 0view_name> 4(column 4,888n])6
4IIT@ 0"ie51attribute2 4,888n66
(S select_statement
4IIT@ %@/%; +PTI+96
)nder the "ie51attribute we have the following options:
4/9%'PPTI+96
4S%@/$(BI9DI9Q6
Types of 8iews:
.imple 8iews
7omplex 8iews
.imple 8iews:
/ These 8iews as based upon a single table, which access the data from the single table.
/ They contain a .ub :uery which retrieves the data from one base table.
7+,AT, 8I,6 .I9N*,P8I,6
A. .,*,7T ,9N(F, ,(A9,, .A*, D,NT(F -+F9 ,9N
/Fnce the view is created we can access the data from it as if it was a table as following:
.,*,7T J -+F9 .I9N*,P8I,6
.,*,7T ,9N(F, ,(A9,, .A*, .A*J!" A. 0A(()A* .A*1, D,NT(F
-+F9 .I9N*,P8I,6
.,*,7T D,NT(F, 9AE2.A*3 -+F9 ,9N D+F)N %B D,NT(F
/6e can also perform D9* operations on the .imple 8iews which will effect on the base
table.
I(.,+T I(TF .I9N*,P8I,6 8A*),.2!"4#, I.A(TF.LH, #4'', "'3
D,*,T, -+F9 .I9N*,P8I,6 6L,+, D,NT(FM"'
)NDAT, ,9N .,T .A*M;C'' 6L,+, ,9N(FM!''!
/All the columns that are referenced in the view can be modified through the view.
/6e cannot perform insert operations on the view if the view does not contain all the not
null columns of the base table.
7omplex 8iews:
/ If the 8iew is based on multiple tables it is a complex view
/ If it is based on a single table with any of the following:
o Droup %y 7lause
4=
o Laving 7lause
o Droup -unctions
o Distinct -unction
o -unction 7alls
7+,AT, 8I,6 ,9NPD,NT
A.
.,*,7T ,.,9N(F, ,.,(A9,, ,..A*, D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N , I((,+ <FI( D,NT D
F( ,.D,NT(FMD.D,NT(F
7+,AT, 8I,6 ,9NPD+AD,
A.
.,*,7T ,.,9N(F, ,.,(A9,, ,..A*, ..D+AD,, ..*F.A*, ..LI.A*
-+F9 ,9N , I((,+ <FI( .A*D+AD, .
F( ,..A* %,T6,,( ..*F.A* A(D ..LI.A*
7+,AT, 8I,6 ,9NP9A(AD,+.
A.
.,*,7T ,.,(A9, @ W 6F+K. )(D,+ W @ 9.,(A9,
-+F9 ,9N , I((,+ <FI( ,9N 9
F( ,.9D+M9.,9N(F
7+,AT, 8I,6 ,9NP.A*A+I,.
A.
.,*,7T ,9N(F, ,(A9,, D,NT(F, .A* A. 9F(TL*B, .A*J!" A.
A(()A* -+F9 ,9N
7+,AT, 8I,6 ,9NPD,.ID(ATIF(.
A.
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM!'
)(IF(
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM"'
)(IF(
.,*,7T <F% -+F9 ,9N 6L,+, D,NT(FM4'
7+,AT, 8I,6 ,9NP9AEP.A*
A.
.,*,7T D,NT(F, 9AE2.A*3 A. 0LIDL .A*1 -+F9 ,9N D+F)N %B
D,NT(F
/If we want to perform manipulations on the 7omplex 8iews we have the following
restrictions:
Any modifications, including )NDAT,, I(.,+T, and D,*,T, statements, must
reference columns from only one base table.
#'
The columns being modified in the view must reference the underlying data in the
table columns directly. They cannot be derived in any other way, such as through:
o An aggregate function
o A computation5 the column cannot be computed from an expression using
other columns. 7olumns formed using set operators amount to a
computation and are also not updatable.
The columns being modified cannot be affected by D+F)N %B, LA8I(D, or
DI.TI(7T clauses.
/6e can also classify views as )pdateable 8iews and (on )pdateable 8iews:
/ A 8iew, which allows manipulations on it, is &nown as )pdateable 8iew.
/ A 8iew, which will not allow manipulations on it, is &nown as (on )pdateable
8iew.
6ith 7hec& Fption:
/ -orces all data modification statements executed against the view to follow the
criteria set within select statement.
/ The 7lause specifies that D9* operations are not allowed on rows that the 8iew
cannot .elect
/ 6hen a row is modified through a view, the 6ITL 7L,7K FNTIF( ma&es sure
the data remains visible through the view after the modification is committed.
7+,AT, 8I,6 .A*,.P,9N
A.
.,*,7T ,9N(F, ,(A9,, .A*, D,NT(F -+F9 ,9N 6L,+,
D,NT(FM"'
I(.,+T I(TF .A*,.P,9N 8A*),.2!';', I+A<)H, 4;'', 4'3
/The above insert statement executes even if it does not satisfy the condition in the 8iew,
if this has to be restricted the view has to be created by using 6ith 7hec& Fption clause.
A*T,+ 8I,6 .A*,.P,9N
A.
.,*,7T ,9N(F, ,(A9,, .A*, D,NT(F -+F9 ,9N 6L,+, D,NT(FM"'
6ITL 7L,7K FNTIF(
/If we want to ma&e any modifications to the existing view we can use the alter view
statement.
&ie5 (ttributes:
,ncryption: After creating a view if we want to see the view definition that can be found
in the .B.7F99,(T. .ystem Table.
#!
.,*,7T T,ET -+F9 .B.7F99,(T. 6L,+,
F%<,7TP(A9,2ID3MH.A*,.P,9NH
If we want to hide the definition from other persons we can use the ,ncryption option
while creating the view or alter the view after creation to add the clause:
A*T,+ 8I,6 .A*,.P,9N
6ITL ,(7+BNTIF(
A.
.,*,7T ,9N(F, ,(A9,, .A*, D,NT(F -+F9 ,9N 6L,+, D,NT(FM"'
6ITL 7L,7K FNTIF(
.chemabinding:
/ 6hen .7L,9A%I(DI(D is specified, the base table or tables cannot be
modified in a way that would affect the view definition.
/ The view definition itself must first be modified or dropped to remove
dependencies on the table that is to be modified.
/ 6hen you use .7L,9A%I(DI(D, the select statement must include the two/
part names 2schema8object) of tables that are referenced.
/ 6e need to specify the column names individual in the select statement, cannot
use SJT in the select statement.
/ All referenced objects must be in the same database.
/ 8iews or tables that participate in a view created with the .7L,9A%I(DI(D
clause cannot be dropped unless that view is dropped or changed so that it no
longer has schema binding.
7+,AT, 8I,6 ,9NP%I(D
6ITL .7L,9A%I(DI(D
A.
.,*,7T ,9(F, ,(A9,, <F%, 9D+ -+F9 D%F.,9N

/After the view is created ,9N table cannot be dropped are the column referred in the
views cannot be altered using the alter command.
I9D/./S
/ *i&e an index in a boo&, an index in a database lets you Auic&ly find specific
information in a table or indexed view.
/ An index contains &eys built from one or more columns in the table, or view, and
pointers that map to the storage location of the specified data.
/ These &eys are stored in a structure 2%/tree3 that enables .:* .erver to find the row
or rows associated with the &ey values Auic&ly and efficiently.
/ 6e can significantly improve the performance of database Aueries and applications by
creating well/designed indexes to support your Aueries.
/ Indexes can reduce the amount of data that must be read to return the Auery result set.
/ Indexes can also enforce uniAueness on the rows in a table, ensuring the data integrity
of the table data.
#"
Types of indexes:
7lustered:
/ 7lustered indexes sort and store the data rows in the table or view based on their
&ey values.
/ These are the columns included in the index definition.
/ There can be only one clustered index per table, because the data rows themselves
can be sorted in only one order.
/ The only time the data rows in a table are stored in sorted order is when the table
contains a clustered index.
/ 6hen a table has a clustered index, the table is called a clustered table.
/ A table can have only ! 7lustered index on it, which will be created when a
primary &ey constraint is used in a table.
(onclustered:
/ (onclustered indexes have a structure separate from the data rows.
/ A nonclustered index contains the nonclustered index &ey values and each &ey
value entry has a pointer to the data row that contains the &ey value.
/ The pointer from an index row in a nonclustered index to a data row is called a
row locator.
/ If a table has no clustered index, its data rows are stored in an unordered structure
called a heap.
/ The structure of the row locator depends on whether the data pages are stored in a
heap or a clustered table.
/ -or a heap, a row locator is a pointer to the row.
/ -or a clustered table, the row locator is the clustered index &ey.
/ A table can have "#= (onclustered indexes on it, which will be created whenever
a uniAue constraint is used in the table.
Low Indexes are used:
6ell/designed indexes can reduce dis& IUF operations and consume fewer system
resources therefore improving Auery performance. Indexes can be helpful for a variety of
Aueries that contain .,*,7T, )NDAT,, or D,*,T, statements. 6hen this Auery is
executed, the Auery optimier evaluates each available method for retrieving the data and
selects the most efficient method. The method may be a table scan, or may be scanning
one or more indexes if they exist.
6hen performing a table scan, the Auery optimier reads all the rows in the table,
and extracts the rows that meet the criteria of the Auery. A table scan generates many dis&
IUF operations and can be resource intensive. Lowever, a table scan could be the most
efficient method if, for example, the result set of the Auery is a high percentage of rows
from the table.
6hen the Auery optimier uses an index, it searches the index &ey columns, finds
the storage location of the rows needed by the Auery and extracts the matching rows from
#4
that location. Denerally, searching the index is much faster than searching the table
because unli&e a table, an index freAuently contains very few columns per row and the
rows are in sorted order.
The Auery optimier typically selects the most efficient method when executing
Aueries. Lowever, if no indexes are available, the Auery optimier must use a table scan.
Bour tas& is to design and create indexes that are best suited to your environment so that
the Auery optimier has a selection of efficient indexes from which to select.
T)e follo5ing tasFs maFe up SH3 Ser"er recommended strategy for creating
inde*es:
18 Design t)e inde*
Index design is a critical tas&. Index design includes determining which columns
to use, selecting the index type 2for example, clustered or nonclustered3, selecting
appropriate index options, and determining filegroup or partition scheme
placement. -or more information, see Designing Indexes.
:8 Determine t)e best creation met)od8 Inde*es are created in t)e follo5ing
5ays:
/ %y defining a N+I9A+B K,B or )(I:), constraint on a column by
using 7+,AT, TA%*, or A*T,+ TA%*,
/ The .:* .erver "''; Database ,ngine automatically creates a uniAue
index to enforce the uniAueness reAuirements of a N+I9A+B K,B or
)(I:), constraint. %y default, a uniAue clustered index is created to
enforce a N+I9A+B K,B constraint, unless a clustered index already
exists on the table, or you specify a uniAue nonclustered index. %y default,
a uniAue nonclustered index is created to enforce a )(I:), constraint
unless a uniAue clustered index is explicitly specified and a clustered
index on the table does not exist.
/ An index created as part of a N+I9A+B K,B or )(I:), constraint is
automatically given the same name as the constraint name.
/ %y creating an index independent of a constraint by using the 7+,AT,
I(D,E statement, you must specify the name of the index, table, and
columns to which the index applies. Index options and index location,
filegroup or partition scheme, can also be specified. %y default, a
nonclustered, nonuniAue index is created if the clustered or uniAue options
are not specified.
!8 %reate t)e inde*:
/ 6hether the index will be created on an empty table or one that contains data is
an important factor to consider. 7reating an index on an empty table has no
performance implications at the time the index is created5 however, performance
will be affected when data is added to the table.
##
/ 7reating indexes on large tables should be planned carefully so database
performance is not hindered. The preferred way to create indexes on large tables
is to start with the clustered index and then build any nonclustered indexes.
.yntax for creating a Index:
%'/(T/ 4,9IH,/6 4%3,ST/'/D C 9+9%3,ST/'/D6 I9D/.
index_name +9 0table1name C "ie51name2 (column 4(S% C D/S%6 4,888n 6)

7+,AT, )(I:), 7*).T,+,D I(D,E ,(FPI(D F( ,9N2,9N(F3
/In this case it creates a uniAue clustered index on the empno column.
7+,AT, I(D,E ,(A9,PI(D F( ,9N2,(A9,3
/In this case it creates a non/uniAue non/clustered index on the ename column.
I(D,E,D 8I,6.
An indexed view is a view that has been materialied, this means it has been
computed and stored.
Bou index a view by creating a uniAue clustered index on it.
Indexed views dramatically improve the performance of some types of Aueries.
Indexed views wor& best for Aueries that aggregate many rows.
They are not well/suited for underlying data sets that are freAuently updated
8iews are also &nown as virtual tables. The result set of a standard view is not stored
permanently in the database. -or a standard view, the overhead of dynamically building
the result set for each Auery that references a view can be significant for views that
involve complex processing of large numbers of rows, such as aggregating lots of data, or
joining many rows. If such views are freAuently referenced in Aueries, you can improve
performance by creating a uniAue clustered index on the view, which is &now as Indexed
8iew. 6hen a uniAue clustered index is created on a view, the result set is stored in the
database just li&e a table with a clustered index is stored.
Another benefit of creating an index on a view is existing Aueries can benefit from the
improved efficiency of retrieving data from the indexed view without having to be
recoded.
As modifications are made to the data in the base tables, the data modifications are
reflected in the data stored in the indexed view. The reAuirement that the clustered index
of the view be uniAue improves the efficiency with which .:* .erver can find the rows
in the index that are affected by any data modification.
If we want to create an Indexed 8iew we need to do the following:
7reate a 8iew by using the with .chema%inding Fption.
7reate a )niAue 7lustered Index on the 8iew
#;
7+,AT, 8I,6 I(DP8I,6
6ITL .7L,9A%I(DI(D
A.
.,*,7T D,NT(F, .)92I.()**2.A*, '33 A. 0TFTA* .A*1, 7F)(TP%ID2J3
A. 0TFTA* +,7F+D.1 -+F9 D%F.,9N D+F)N %B D,NT(F
7+,AT, )(I:), 7*).T,+,D I(D,E D,NT(FPI(D F(
I(DP8I,62D,NT(F3
/Fnce the index is created on the view it will internally the store the information of the
8iew physicially in a location, any manupulation performed on the base table reflects to
the the 8iew also.
TSH3 P'+Q'($$I9Q
T.:* 2Transact .:*3 Nrogramming is an Nrocedural *anguage ,xtension to .:*
which is &nown as N*U.:* in Fracle.
It extends .:* by adding programming structures and subroutines available in
any high level language.
It has syntax and rules that determine how programming statements wor&
together.
6e can control the program flow by using conditional statements li&e I- and
6hile loop
+untime ,rror Landling is provided using the try catch mechanism
+eusability of the code is available by defining objects such as Nrocedures and
-unctions.
.:* 7ommands can be embedded inside the programs.
Nrogram %loc&s can be of " types:
!. Anonymous %loc&s
". .ub/Nrogram %loc&s
Anonymous %loc&s: They are unnamed bloc& of code for execution which can be written
at a point where they are to be executed. They can be written on a :uery window and
execute.
.ub/Nrogram %loc&s: These are nothing but named bloc& of code for execution, where
the program bloc&s are given a name for identification. These will be stored on the
database which provides the reusability of code.
Nrogram %loc&s li&e in any other language provides option for variable declaration,
program logic using conditional statements and displaying the results to the user, in the
same way we can define programs in .:* .erver also.
#C
Declaring 8ariables: 6hile declaring variables it has to be preceded with \ symbol.
.yntax: D,7*A+, \OvarQ 0A.1 OdataPtypeQ 0,Yn1
D,7*A+, \E I(T
D,7*A+, \.A* A. 9F(,B
D,7*A+, \,(A9, 8A+7LA+2;'3, \<F% 8A+7LA+2;'3
Assinging 8alues to 8ariables: 8alues can be assigned by using a .,T statement.
.yntax: .,T \OvarQ M OvalueQ
.,T \EM!''
.,T \,(A9,MH.7FTTH
Nrinting 8alues: If we want to print the values we can use the Nrint statement.
.yntax: Nrint \OvarQ
Nrint \E
Nrint \,name
7onditional .tatements:
If 7 /lse If 7 /lse: Imposes conditions on the execution of a Transact/.:* statement.
The Transact/.:* statement that follows an I- &eyword and its condition are executed if
the condition is satisfied: the %oolean expression returns T+),. The optional ,*.,
&eyword introduces another Transact/.:* statement that is executed when the I-
condition is not satisfied: the %oolean expression returns -A*.,.
I- %ooleanPexpression
0 %,DI( 1
O sAlPstatement > statementPbloc& Q
0 ,(D 1
0 ,*., I- %ooleanPexpression
0 %,DI( 1
O sAlPstatement > statementPbloc& Q
0 ,(D 1
,*.,
0 %,DI( 1
O sAlPstatement > statementPbloc& Q 1
0 ,(D 1
/If there are multiple statements being enclosed between each bloc& then we can put them
under %egin and ,nd .tatements.
D,7*A+, \6,,K I(T
.,T \6,,KMDAT,NA+T2D6, D,TDAT,233
I- \6,,KM!
N+I(T W.)(DABW
,*., I- \6,,KM"
N+I(T W9F(DABW
#G
,*., I- \6,,KM4
N+I(T WT),.DABW
,*., I- \6,,KM#
N+I(T W6,D(,.DABW
,*., I- \6,,KM;
N+I(T WTL)+.DABW
,*., I- \6,,KMC
N+I(T W-+IDABW
,*., I- \6,,KMG
N+I(T W.AT)+DABW
%(S/ D,9%TI+9: The case function what we have discussed under the .ystem
-unctions can also be used here as following:
D,7*A+, \6,,K I(T
.,T \6,,KMDAT,NA+T2D6, D,TDAT,233
.,*,7T 7A., \6,,K
6L,( ! TL,( W.)(DABW
6L,( " TL,( W9F(DABW
6L,( 4 TL,( WT),.DABW
6L,( # TL,( W6,D(,.DABW
6L,( ; TL,( WTL)+.DABW
6L,( C TL,( W-+IDABW
6L,( G TL,( W.AT)+DABW
,(D
/This can be written in the second style of the 7A., .tatement also that has been
discussed in the .:* as following:
D,7*A+, \6,,K I(T
.,T \6,,KMDAT,NA+T2D6, D,TDAT,233
.,*,7T 7A.,
6L,( \6,,KM! TL,( W.)(DABW
6L,( \6,,KM" TL,( W9F(DABW
6L,( \6,,KM4 TL,( WT),.DABW
6L,( \6,,KM# TL,( W6,D(,.DABW
6L,( \6,,KM; TL,( WTL)+.DABW
6L,( \6,,KMC TL,( W-+IDABW
6L,( \6,,KMG TL,( W.AT)+DABW
,(D
I)ile 3oop: .ets a condition for the repeated execution of an .:* statement or
statement bloc&. The statements are executed repeatedly as long as the specified
condition is true. The execution of statements in the 6LI*, loop can be controlled from
inside the loop with the %+,AK and 7F(TI(), &eywords.
6LI*, %ooleanPexpression
#$
0 %,DI( 1
O sAlPstatement > statementPbloc& Q
0 %+,AK 1
O sAlPstatement > statementPbloc& Q
0 7F(TI(), 1
O sAlPstatement > statementPbloc& Q
0 ,(D 1
/If there are multiple statements being enclosed then we can put them under %egin and
,nd .tatements.
%+,AK: 7auses an exit from the innermost 6LI*, loop. Any statements that appear
after the ,(D &eyword, mar&ing the end of the loop, are executed.
7F(TI(),: 7auses the 6LI*, loop to restart, ignoring any statements after the
7F(TI(), &eyword.
Nrogram !:
D,7*A+, \E I(T
.,T \EM'
6LI*, \EO!'
%,DI(
.,T \EM\E@!
N+I(T \E
,(D
Nrogram ":
D,7*A+, \E I(T
.,T \EM'
6LI*, \EO!'
%,DI(
.,T \EM\E@!
I- \EMC %+,AK
N+I(T \E
,(D
/In this case the brea& statement brings the control out of the loop printing from ! to ;.
Nrogram 4:
D,7*A+, \E I(T
.,T \EM'
6LI*, \EO!'
%,DI(
.,T \EM\E@!
I- \EMC 7F(TI(),
N+I(T \E
,(D
#=
/In this case the continue statement will s&ip the print statement when the value of x is C
so prints from ! to ; and G to !'.
7omments in T.:*: 7omments will be ignored will executing the program, they will
increase the readability and aids understanding of the program.
.ingle *ine 7omments 2//3
9ulti *ine 7omments 2UJ Y.. JU3
Assinging values from columns into variables: Till now we were assigning static values
to the variables using the .,T statement, but we can also assign values from a column
into the variables as following:
.,*,7T \OvarQMOcolPnameQ 0, YYn1 -+F9 OtablePnameQ 07F(DITIF(.1
.,*,7T \,(A9,M,(A9, -+F9 ,9N 6L,+, ,9N(FM!''!
/A simple T.:* program which ta&es the ,mpno and prints the (ame and .alary.
D,7*A+, \,9N(F I(T, \,(A9, 8A+7LA+2;'3, \.A* 9F(,B
.,T \,9N(FM!'';
.,*,7T \,(A9,M,(A9,, \.A*M.A* -+F9 ,9N 6L,+,
,9N(FM\,9N(F
N+I(T \,(A9, @ W ,A+(. W @ 7A.T2\.A* A. 8A+7LA+3
/A Nrogram which ta&es the ,mpno and increments the .alary of the person on the
following criteria:
If <ob is Nresident increment with !'Z
If <ob is 9anager increment with $Z
If <ob is Analyst increment with CZ
If <ob is any thing other incrment with ;Z
D,7*A+, \,9N(F I(T, \<F% 8A+7LA+2;'3
.,T \,9N(FM!'';
.,*,7T \<F%M<F% -+F9 ,9N 6L,+, ,9N(FM\,9N(F
I- \<F%MWN+,.ID,(TW
)NDAT, ,9N .,T .A* M .A* @ .A* J '.! 6L,+,
,9N(FM\,9N(F
,*., I- \<F%MW9A(AD,+W
)NDAT, ,9N .,T .A* M .A* @ .A* J '.'$ 6L,+,
,9N(FM\,9N(F
,*., I- \<F%MWA(A*B.TW
)NDAT, ,9N .,T .A* M .A* @ .A* J '.'C 6L,+,
,9N(FM\,9N(F
,*.,
)NDAT, ,9N .,T .A* M .A* @ .A* J '.'; 6L,+,
,9N(FM\,9N(F
;'
/In the above case which empno has been provided for the variable \,9N(F first it will
chec& for the <F% of the employee and then it will increment the salary on the specified
criteria .
/The problem in the above case is we can increment only one ,mployee .alary at a time
but if we want to increase the .alary of 9ultiple ,mloyees at the same time it is not
possible, as multiple rows cannot be effected within the program to over come this we
use %ursors.
/ Fperations in a relational database act on a complete set of rows. The set of rows
returned by a .,*,7T statement consists of all the rows that satisfy the conditions in the
6L,+, clause of the statement. This complete set of rows returned by the statement is
&nown as the result set. Applications, especially interactive online applications, cannot
always wor& effectively with the entire result set as a unit. These applications need a
mechanism to wor& with one by one row at a time. %ursors are an extension to result sets
that provide that mechanism.
7ursor extend result processing by:
Allowing positioning at specific rows of the result set.
+etrieving one row or bloc& of rows from the current position in the result set.
.upporting data modifications to the rows at the current position in the result set.
.upporting different levels of visibility to changes made by other users to the
database data that is presented in the result set.
Nroviding Transact/.:* statements in scripts, stored procedures, and triggers
access to the data in a result set.
%ursor Process: Transact/.:* 7ursors follows a general process that is used with all
.:* .erver cursors:
!. Associate a cursor with the result set of a Transact/.:* statement, and define
characteristics of the cursor, such as whether the rows in the cursor can be
updated.
". ,xecute the Transact/.:* statement to populate the cursor.
4. +etrieve the rows in the cursor you want to see. The operation to retrieve one row
or one bloc& of rows from a cursor is called a fetch. Nerforming a series of fetches
to retrieve rows in either a forward or bac&ward direction is called scrolling.
#. Fptionally, perform modification operations 2update or delete3 on the row at the
current position in the cursor.
;. 7lose the 7ursor
The 7ursor Nrocess has the following steps involved in it:
Declare a 7ursor
Fpen a 7ursor
-etch data from the 7ursor
7lose the 7ursor
De/allocate the 7ursor
;!
Declaring a %ursor: Defines the attributes of a Transact/.:* server cursor, such as its
scrolling behavior and the Auery used to build the result set on which the cursor operates.
D,7*A+, cursor_name 7)+.F+
0 *F7A* > D*F%A* 1
0 -F+6A+DPF(*B > .7+F** 1
0 .TATI7 > K,B.,T > DB(A9I7 > -A.TP-F+6A+D 1
0 +,ADPF(*B > .7+F**P*F7K. > FNTI9I.TI7 1
0 TBN,P6A+(I(D 1
-F+ select_statement
0 -F+ )NDAT, 0 F- column_name 0 ,...n 1 1 1
*F7A*: .pecifies that the scope of the cursor is local to the program in which the cursor
was created.
D*F%A*: .pecifies that the scope of the cursor is global to the connection. The cursor
name can be referenced in any program by the connection. The cursor is only implicitly
deallocated at disconnect.
If neither D*F%A* nor *F7A* is specified, the default is ta&en as D*F%A*.
-F+6A+DPF(*B: .pecifies that the cursor can only be scrolled from the first to the
last row. -,T7L (,ET is the only supported fetch option. 6hen neither
-F+6A+DPF(*B nor .7+F** is specified, -F+6A+DPF(*B is the default, unless
the &eywords .TATI7, K,B.,T, or DB(A9I7 are specified. .TATI7, K,B.,T, and
DB(A9I7 cursors default to .7+F**.
.7+F**: .pecifies that the cursor can scroll from first to the last row as well as last to
first row also. It .upports C fetch methods li&e -,T7L (,ET, -,T7L N+IF+, -,T7L
-I+.T, -,T7L *A.T, -,T7L A%.F*)T, n and -,T7L +,*ATI8, n.
.TATI7: Defines a cursor that ma&es a temporary copy of the data to be used by the
cursor. All reAuests to the cursor are answered from this temporary table in tempdb5
therefore, modifications made to base tables are not reflected in the data returned by
fetches made to this cursor, and this cursor does not allow modifications
K,B.,T: .pecifies that the membership and order of rows in the cursor are fixed when
the cursor is opened. The set of &eys that uniAuely identify the rows is built into a table in
tempdb &nown as the Feyset. 7hanges to non&ey values in the base tables, either made
by the cursor or committed by other users, are visible as we scroll around the cursor.
Inserts made by other users are not visible. If a row is deleted, an attempt to fetch the row
returns an \\-,T7LP.TAT). of /". )pdates of &ey values from outside the cursor
resemble a delete of the old row followed by an insert of the new row.
;"
DB(A9I7: Defines a cursor that reflects all data changes made to the rows in its result
set as you scroll around the cursor. The data values, order, and membership of the rows
can change on each fetch.
-A.TP-F+6A+D: .pecifies a -F+6A+DPF(*B, +,ADPF(*B cursor with
performance optimiations enabled. -A.TP-F+6A+D cannot be specified if .7+F**
or -F+P)NDAT, is also specified.
+,ADPF(*B: Nrevents updates made through this cursor. This option overrides the
default capability of a cursor to be updated.
.7+F**P*F7K.: .pecifies that positioned updates or deletes made through the cursor
are guaranteed to succeed. 9icrosoft .:* .erver loc&s the rows as they are read into the
cursor to ensure their availability for later modifications. .7+F**P*F7K. cannot be
specified if -A.TP-F+6A+D is also specified.
FNTI9I.TI7: .pecifies that positioned updates or deletes made through the cursor do
not succeed if the row has been updated in the table since it was read into the cursor. .:*
.erver does not loc& rows as they are read into the cursor. It instead uses comparisons of
timestamp column values, or a chec&sum value if the table has no timestamp column, to
determine whether the row was modified after it was read into the cursor. If the row was
modified, the attempted positioned update or delete fails. FNTI9I.TI7 cannot be
specified if -A.TP-F+6A+D is also specified.
TBN,P6A+(I(D: .pecifies that a warning message is sent to the client if the cursor is
implicitly converted from the reAuested type to another.
-F+ )NDAT, 0F- column name 0,...n11: Defines updatable columns within the cursor. If
F- columnPname 0,...n1 is supplied, only the columns listed allow modifications. If
)NDAT, is specified without a column list, all columns can be updated, unless the
+,ADPF(*B concurrency option was specified.
+pening a %ursor: Fpens a Transact/.:* server cursor and populates the cursor by
executing the Transact/.:* statement specified on the D,7*A+, 7)+.F+.
Synta*: +P/9 0cursor1name2
Detc)ing data from t)e %ursor: +etrieves a specific row from a Transact/.:* server
cursor into specified variables.
.yntax:
D/T%@ 4 9/.T C P'I+' C DI'ST C 3(ST C (BS+3,T/ n C '/3(TI&/ n 6
D'+$ 0cursor1name2 I9T+ R"ariable1name 4 ,888n 6
(,ET: +eturns the result row immediately following the current row and increments the
current row to the row returned. If -,T7L (,ET is the first fetch against a cursor, it
returns the first row in the result set. (,ET is the default cursor fetch option.
;4
N+IF+: +eturns the result row immediately preceding the current row, and decrements
the current row to the row returned. If -,T7L N+IF+ is the first fetch against a cursor,
no row is returned and the cursor is left positioned before the first row.
-I+.T: +eturns the first row in the cursor and ma&es it the current row.
*A.T: +eturns the last row in the cursor and ma&es it the current row.
A%.F*)T, n: If n is positive, it returns the specified nth row from the front of the
cursor. If n is negative, it returns the specified nth row from the bac& of the cursor.
+,*ATI8, n: If n is positive, returns the row n rows beyond the current row. If n is
negative, returns the row n rows prior to the current row.
If any of the used fetch statement is successful it returns the status of it which will be
stored in a implicit variable \\-,T7LP.TAT). 2this does not reAuires to be declared3
which can be any of the following values:
' / The -,T7L statement was successful
/! / The -,T7L statement failed or the row was beyond the result set
/" / The row fetched is missing
%losing a %ursor: 7loses an open cursor by releasing the current result set and freeing
any cursor loc&s held on the rows on which the cursor is positioned. 7*F., leaves the
data structures available for reopening, but fetches and positioned updates are not
allowed until the cursor is reopened. 7*F., must be issued on an open cursor5 7*F.,
is not allowed on cursors that have only been declared or are already closed.
Synta*: %lose 0cursor1name2
Deallocating a %ursor: +emoves a cursor reference. 6hen the last cursor reference is
deallocated, .:* .erver releases the data structures comprising the cursor.
Synta*: Deallocate 0cursor1name2
,sing a Simple %ursor:
D,7*A+, ,9N7)+ 7)+.F+ -F+ .,*,7T ,(A9,, .A* -+F9 ,9N
D,7*A+, \,(A9, 8A+7LA+2;'3, \.A* 9F(,B
FN,( ,9N7)+
-,T7L (,ET -+F9 ,9N7)+ I(TF \,(A9,, \.A*
6LI*, \\-,T7LP.TAT).M'
%,DI(
N+I(T W.A*A+B F- W @ \,(A9, @ W I. W @ 7A.T2\.A* A. 8A+7LA+3
-,T7L (,ET -+F9 ,9N7)+ I(TF \,(A9,, \.A*
,(D
7*F., ,9N7)+
D,A**F7AT, ,9N7)+
;#
,sing a %ursor to ,pdate all t)e ro5s of t)e Table:
This program will explain you how we can update all the rows of the table basing on
some conditions, similar to the program we have written before discussing cursors but
there only a single row has been modified.
D,7*A+, ,9N7)+ 7)+.F+ -F+ .,*,7T ,9N(F, <F% -+F9 ,9N
D,7*A+, \,9N(F I(T, \<F% 8A+7LA+2;'3
FN,( ,9N7)+
-,T7L (,ET -+F9 ,9N7)+ I(TF \,9N(F, \<F%
6LI*, \\-,T7LP.TAT).M'
%,DI(
I- \<F%MWN+,.ID,(TW
)NDAT, ,9N .,T .A* M .A* @ .A* J '.! 6L,+, ,9N(FM\,9N(F
,*., I- \<F%MW9A(AD,+W
)NDAT, ,9N .,T .A* M .A* @ .A* J '.'$ 6L,+, ,9N(FM\,9N(F
,*., I- \<F%MWA(A*B.TW
)NDAT, ,9N .,T .A* M .A* @ .A* J '.'C 6L,+, ,9N(FM\,9N(F
,*.,
)NDAT, ,9N .,T .A* M .A* @ .A* J '.'; 6L,+, ,9N(FM\,9N(F
-,T7L (,ET -+F9 ,9N7)+ I(TF \,9N(F, \<F%
,(D
7*F., ,9N7)+
D,A**F7AT, ,9N7)+
,sing a Qlobal %ursor:
Program 1:
D,7*A+, ,9N7)+ 7)+.F+ D*F%A*
-F+ .,*,7T ,(A9,, .A*, 7F99 -+F9 ,9N
D,7*A+, \,(A9, 8A+7LA+2;'3, \.A* 9F(,B, \7F99 9F(,B,
\TFT.A* 9F(,B
FN,( ,9N7)+
-,T7L (,ET -+F9 ,9N7)+ I(TF \,(A9,, \.A*, \7F99
6LI*, \\-,T7LP.TAT).M'
%,DI(
.,T \TFT.A*M\.A* @ I.()**2\7F99, '3
N+I(T \,(A9, @ W ,A+(. W @ 7A.T2\TFT.A* A. 8A+7LA+3 @ W
,8,+B 9F(TLW
-,T7L (,ET -+F9 ,9N7)+ I(TF \,(A9,, \.A*, \7F99
,(D
7*F., ,9N7)+
;;
/In the above case because it was a Dlobal cursor we are not using any Deallocate 7ursor
statement, now we use the same cursor in other programs with of declaring it as
following:
Program ::
D,7*A+, \,(A9, 8A+7LA+2;'3, \.A* 9F(,B, \7F99 9F(,B,
\A((.A* 9F(,B
FN,( ,9N7)+
-,T7L (,ET -+F9 ,9N7)+ I(TF \,(A9,, \.A*, \7F99
6LI*, \\-,T7LP.TAT).M'
%,DI(
.,T \A((.A*M2\.A* @ I.()**2\7F99, '33 J !"
N+I(T \,(A9, @ W ,A+(. W @ 7A.T2\A((.A* A. 8A+7LA+3 @ W
,8,+B B,A+W
-,T7L (,ET -+F9 ,9N7)+ I(TF \,(A9,, \.A*, \7F99
,(D
7*F., ,9N7)+
/6e donHt reAuire to Deallocate the 7ursor any where it gets deallocated when we close
the connection.
,sing a Static %ursor:
D,7*A+, ,9N7)+ 7)+.F+ .TATI7
-F+ .,*,7T .A* -+F9 ,9N 6L,+, ,9N(FM!'';
D,7*A+, \.A* 9F(,B
FN,( ,9N7)+
)NDAT, ,9N .,T .A*MC''' 6L,+, ,9N(FM!'';
-,T7L (,ET -+F9 ,9N7)+ I(TF \.A*
N+I(T \.A*
7*F., ,9N7)+
D,A**F7AT, ,9N7)+
/In this case after opening the cursor we have performed an update of .al on the ,9N
table but still the cursor contains the old value but not the new value, so it prints the old
.alary value only.
,sing a Dynamic %ursor:
D,7*A+, ,9N7)+ 7)+.F+ DB(A9I7
-F+ .,*,7T .A* -+F9 ,9N 6L,+, ,9N(FM!'';
D,7*A+, \.A* 9F(,B
FN,( ,9N7)+
;C
)NDAT, ,9N .,T .A*M#''' 6L,+, ,9N(FM!'';
-,T7L (,ET -+F9 ,9N7)+ I(TF \.A*
N+I(T \.A*
7*F., ,9N7)+
D,A**F7AT, ,9N7)+
/In this case after opening the cursor we have performed an update of .al on the ,9N
table but the cursor contains the new value but not the new value, so it prints the new
.alary value only.
,sing Scroll %ursor:
D,7*A+, ,9N7)+ 7)+.F+
.7+F**
-F+ .,*,7T ,9N(F -+F9 ,9N
D,7*A+, \,9N(F I(T
FN,( ,9N7)+
-,T7L (,ET -+F9 ,9N7)+ I(TF \,9N(F
N+I(T \,9N(F
-,T7L *A.T -+F9 ,9N7)+ I(TF \,9N(F
N+I(T \,9N(F
-,T7L N+IF+ -+F9 ,9N7)+ I(TF \,9N(F
N+I(T \,9N(F
-,T7L -I+.T -+F9 ,9N7)+ I(TF \,9N(F
N+I(T \,9N(F
-,T7L A%.F*)T, !" -+F9 ,9N7)+ I(TF \,9N(F
N+I(T \,9N(F
-,T7L A%.F*)T, /!' -+F9 ,9N7)+ I(TF \,9N(F
N+I(T \,9N(F
-,T7L +,*ATI8, 4 -+F9 ,9N7)+ I(TF \,9N(F
N+I(T \,9N(F
-,T7L +,*ATI8, /; -+F9 ,9N7)+ I(TF \,9N(F
N+I(T \,9N(F
7*F., ,9N7)+
D,A**F7AT, ,9N7)+
/As we have declared the cursor as scroll all the -etch methods can be used on it.
S,B-P'+Q'($S
A .ub/Nrogram is a new bloc& of code which can be reused. 6e have " types of .ub/
Nrograms in .:* .erver:
!. Nrocedures
". -unctions
;G
Procedures:
A stored procedure is a saved collection of Transact/.:* statements or a
reference to a 9icrosoft .(,T -ramewor& common language runtime 27*+3
method that can ta&e and return user/supplied parameters.
Nrocedures can be created for permanent use or for temporary use within a
session, local temporary procedure, or for temporary use within all sessions,
global temporary procedure.
.tored procedures can also be created to run automatically when an instance of
.:* .erver starts.
.yntax:
7+,AT, > A*T,+ N+F7,D)+, OprocedurePnameQ
0 2 Rparameter! OdataPtypeQ 0 E default 1 0 F)T > F)TN)T 1,
Rparameter" OdataPtypeQ 0 E default 1 0 F)T > F)TN)T 1,
YYYYYYYY.
Rparametern OdataPtypeQ 0 E default 1 0 F)T > F)TN)T 1 3 1
0 6ITL OprocedurePoptionsQ 1
A.
%,DI(
OstatementsQ
,(D
A*T,+: 9odifies a previously created procedure that was created by executing the
7+,AT, N+F7,D)+, statement. A*T,+ N+F7,D)+, does not change permissions
and does not affect any dependent stored procedures or triggers.
Nrocedure Fptions: The Nrocedure provide to options that can be used while creating the
procedures. They are:
!. ,ncryption
". +ecompile
+,7F9NI*,: Indicates that the Database ,ngine does not cache a plan for this
procedure and the procedure is compiled at run time. To instruct the Database ,ngine to
discard plans for individual Aueries inside a stored procedure, use the +,7F9NI*,
Auery hint. )se the +,7F9NI*, Auery hint when atypical or temporary values are used
in only a subset of Aueries that belong to the stored procedure.
Important: %ecause the .:* .erver "''; Auery optimier typically selects the best
execution plan for a Auery, we recommend that hints, including OAueryPhintQ, be used
only as a last resort by experienced developers and database administrators.
,(7+BNTIF(: Indicates that .:* .erver will convert the original text of the 7+,AT,
N+F7,D)+, statement to an obfuscated format. The output of the obfuscation is not
directly visible in any of the catalog views in .:* .erver "'';. )sers that have no access
to system tables or database files cannot retrieve the obfuscated text.
;$
/Nrocedure contains " parts in it: !. Leader ". %ody
/Leader part is the content above the A. &eyword.
/%ody part is the content below the A. &eyword.
Nassing Narameters to Nrocedures: As if we are passing parameters to functions in
languages, we can also pass parameters to Nrocedures. They are the means to pass a value
to the procedure or returns from a procedure.
Narameter 9odes: These will specify whether ther parameter is passed into the procedure
or returned out of the procedure. .:* .erver supports to Narameter 9odes:
I( 9FD, 2D,-A)*T3
F)T F+ F)TN)T 9FD,
I( 9FD,: Nasses a value into the procedure for execution, this is best suitable for
constants X expressions. The value of it can be changed with in the program but cannot
be returned. It is the default mode if nothing is specified
F)T 9FD,: Nasses a value bac& from the program after the execution of the procedure.
The value of this option can be returned to the calling ,E,7)T, statement. )se
F)TN)T parameters to return values to the caller of the procedure. te*t, nte*t, and
image parameters cannot be used as F)TN)T parameters
.yntax for executing the Nrocedure:
/./% C /./%,T/ 4 4RparameterE6 0value> 4+,TP,T6 4D/D(,3T6 4,7n6 6
A .imple Nrocedure:
7+,AT, N+F7,D)+, N+F7!
A.
%,DI(
N+I(T W9B -I+.T N+F7,D)+,W
,(D
/,xecuting the above procedure:
,E,7 N+F7! F+ ,E,7)T, N+F7!
A Nrocedure which accepts arguments:
A*T,+ N+F7,D)+, N+F7"2\E I(T, \B I(T3
A.
%,DI(
D,7*A+, \] I(T
.,T \]M\E@\B
N+I(T WThe .)9 of the " (umbers is: W @ 7A.T2\] A. 8A+7LA+3
,(D
/,xecuting the above procedure in " ways:
;=
!. ,E,7 N+F7" !'', ;'
". ,E,7 N+F7" \EM!'', \BM;'
A Nrocedure with Default 8alues:
7+,AT, N+F7,D)+, N+F742\E I(T M !'', \B I(T3
A.
%,DI(
D,7*A+, \] I(T
.,T \]M\E@\B
N+I(T WThe .)9 of the " (umbers is: W @ 7A.T2\] A. 8A+7LA+3
,(D
/,xecuting the above procedure:
!. ,E,7 N+F74 "'', ";
". ,E,7 N+F74 \EM"'', \BM";
4. ,E,7 N+F74 \EMD,-A)*T, \BM";
#. ,E,7 N+F74 \BM";
/In the 4
rd
and #
th
case it uses the default value of !'' to the varibale E which has been
given while creating the procedure.
A Nrocedure with F)TN)T Narameter:
7+,AT, N+F7,D)+, N+F7#2\E I(T, \B I(T, \] I(T F)TN)T3
A.
%,DI(
.,T \]M\E@\B
,(D
/ ,xecuting the above procedure:
D,7*A+, \A I(T
,E,7)T, N+F7# ;'', ";', \A F)TN)T
N+I(T \A
/A Nrocedure for Inserting values into the ,mp Table:
7+,AT, N+F7,D)+, InsertP,mp2\,mpno int, \,name varchar2;'3, \.al
money, \Deptno int3
As
%egin
I(.,+T I(TF ,mp 2,mpno, ,name, .al, Deptno3 8A*),. 2\,mpno,
\,name, \.al, \deptno3
,nd
/ ,xecuting the above Nrocedure:
,E,7 InsertP,mp !'!C, I.udha&arH, ";'', !'
/A Nrocedure for Inserting values into the ,mp Table but with 8alidations:
/This is same as the previous one but with the following validations present in it:
/,mpno cannot be ()** value.
/,mpno cannot be duplicated.
C'
/.alary cannot be less than ";''.
/Deptno should be present in the Dept Table.
7+,AT, N+F7,D)+, InsertP,mp2\,mpno int, \,name varchar2;'3, \.al
money, \Deptno int3
As
%egin
I- \,mpno I. ()**
%egin
Nrint I,mpno cannot be ()**H
+eturn
,nd
I- ,xists2.,*,7T J -+F9 ,mp 6L,+, ,mpnoM\,mpno3
%egin
Nrint I,mpno cannot be DuplicatedH
+eturn
,nd
I- \.alO";'' %egin
Nrint I.alary cannot be less than ";''H
+eturn
,nd
I- (ot ,xists2.,*,7T J -+F9 Dept 6L,+, DeptnoM\Deptno3
%egin
Nrint IDeptno not found in the Dept TableH
+eturn
,nd
I(.,+T I(TF ,mp 2,mpno, ,name, .al, Deptno3 8A*),. 2\,mpno,
\,name, \.al, \deptno3
,nd
/A Nrocedure which ta&es the ,mpno and returns the Nrovident -und and Nrofessional
Tax at !"Z and ;Z respectively on the .alary.
7+,AT, N+F7,D)+, Deductions2\,mpno int, \N- money F)TN)T, \NT
money F)TN)T3
As
%egin
Declare \.al 9oney
.,*,7T \.alM.al -+F9 ,mp 6L,+, ,mpnoM\,mpno
.,T \N-M\.al J '.!"
.,T \NTM\.al J '.';
,nd
C!
/,xecuting the above Nrocedure:
Declare \8N- money, \8NT money
,E,7 Deductions !'';, \8N- F)TN)T, \8NT F)TN)T
Nrint \8N-
Nrint \8NT
/A Nrocedure which ta&es the ,mpno and prints the (et .alary of the ,mployee.
7+,AT, N+F7,D)+, (etP.al2\,mpno int3
As
%egin
Declare \8.al money, \(.al money, \8N- money, \8NT money
,E,7 Deductions \,mpno, \8N- F)TN)T, \8NT F)TN)T
.,*,7T \.alM.al -+F9 ,mp 6L,+, ,mpnoM\,mpno
.,T \(.al M \8.al / \8N- / \8NT
Nrint I(et .alary of the ,mployee is: I @ 7ast2\(.al as 8archar3
,nd
/,xecuting the above Nrocedure:
,E,7 (etP.al !'';
/A Nrocedure which will Insert values into the Dept table by generating a uniAue Deptno.
7+,AT, N+F7,D)+, InsertPDept2\Dname varchar2;'3, \*oc varchar2;'33
As
%egin
Declare \Deptno int
.elect \Deptno M I.()**29AE2Deptno3, '3 @ !' -+F9 Dept
I(.,+T I(TF Dept 8alues 2\Deptno, \Dname, \*oc3
,nd
/,xecuting the above Nrocedure:
,E,7 InsertPDept I+esearchH, ILyderabadH
/A Nrocedure which is used from transferring amount from one account to the other
within the %an& table:
7+,AT, N+F7,D)+, -undsPTransfer2\.rcID int, \DestID int, \Amt
money3
As
%egin
)NDAT, %A(K .,T %al M %al / \Amt 6L,+, 7).TIDM\.rcID
)NDAT, %A(K .,T %al M %al @ \Amt 6L,+, 7).TIDM\DestID
,nd
/,xecuting the above Nrocedure:
C"
,E,7 -undsPTransfer !'!, !'", ;''
/ In the above case if the .rcID or DestID are not present in the table then it will
deduct the amount from the other or add the amount from the other to avoid this
we need to use transaction management.
/ To manage the transaction first we need to identify which statement is executed
and which failed for this we use the function RR'+I%+,9T8
/ RR'+I%+,9T returns the number of rows affected by the last statement.
/9anaging Transactions in the Nrocedure:
7+,AT, N+F7,D)+, -undsPTransfer2\.rcID int, \DestID int, \Amt
money3
As
%egin
Declare \7ount! int, \7ount" int
%egin Transaction
)NDAT, %A(K .,T %al M %al / \Amt 6L,+, 7).TIDM\.rcID
.et \7ount!M\\+F67F)(T
)NDAT, %A(K .,T %al M %al @ \Amt 6L,+, 7).TIDM\DestID
.et \7ount"M\\+F67F)(T1
I- \7F)(T!M\7F)(T"
%egin
7F99IT
N+I(T IT+A(.A7TIF( 7F99IT,DH
,nd
,*.,
%egin
+F**%A7K
N+I(T IT+A(.A7TIF( +F**,D %A7KH
,nd
,nd
@andling /rrors in Procedures:
/ In .:* .erver when a error occurs, the statement that caused the error is
terminated, but the execution of the stored procedure or batch continues.
/ 6hen stored procedures and batches are executed within the scope of a T+B
bloc&, batch abort errors can be handled by the T+BY7AT7L construct.
/ ,rrors in Transact/.:* code can be processed using a T+BY7AT7L construct
similar to the exception/handling features of the languages.
/ A T+BY7AT7L construct consists of two parts: a T+B bloc& and a 7AT7L
bloc&.
/ 6hen an error condition is detected in a Transact/.:* statement contained in a
T+B bloc&, control is passed to a 7AT7L bloc& where it can be processed.
C4
/ After the 7AT7L bloc& handles the exception, control is then transferred to the
first Transact/.:* statement that follows the ,(D 7AT7L statement.
/ If the ,(D 7AT7L statement is the last statement in a stored procedure or
trigger, control is returned to the code that invo&ed the stored procedure or trigger.
/ Transact/.:* statements in the T+B bloc& following the statement that generates
an error will not get executed.
/ If there are no errors inside the T+B bloc&, control passes to the statement
immediately after the associated ,(D 7AT7L statement.
/ If the ,(D 7AT7L statement is the last statement in a stored procedure or
trigger, control is passed to the statement that invo&ed the stored procedure or
trigger.
/ A T+B bloc& starts with the %,DI( T+B statement and ends with the ,(D T+B
statement.
/ Fne or more Transact/.:* statements can be specified between the %,DI( T+B
and ,(D T+B statements.
/ A 7AT7L bloc& must follow a T+B bloc& immediately.
/ A 7AT7L bloc& starts with the %,DI( 7AT7L statement and ends with the
,(D 7AT7L statement.
/ In Transact/.:*, each T+B bloc& is associated with only one 7AT7L bloc&.
/A Nrocedure which can cause ,rror:
7+,AT, N+F7,D)+, Div2\E int, \B int3
As
%egin
Declare \] int
.,T \]M'
.,T \]M\EU\B
N+I(T WThe Futput is: W @ 7ast2\] as varchar3
,(D
/,xecuting the above procedure:
,E,7 DI8E !'', "'
,E,7 DI8E !'', '
/The first execution will print the result of ; but the second time execution will raise an
error because we cannot divide a number by ero, in this case still it will try to print the
result as ', because even if the error is encountered it will not stop the execution of the
program, if we want to stop the execution of the program when an error raises the code
has to be written in the following way:
7+,AT, N+F7,D)+, Div2\E int, \B int3
As
%egin
%egin Try
Declare \] I(T
C#
.,T \]M'
.,T \]M\EU\B
N+I(T WThe Futput is: W @ 7ast2\] as varchar3
,nd Try
%egin 7atch
Nrint ,rrorP9essage23
,nd 7atch
,nd
/,xecuting the above procedure:
,E,7 DI8E !'', "'
,E,7 DI8E !'', '
/ ,very error has # properties to it, they are:
o 9sg id
o 9sg str
o .everity
o .tate
-or ,xample try the following statement:
Nrint !''U'
/This will display the following error message:
9sg $!4#, *evel !C, .tate !,
Divide by ero error encountered.
/In this the 9sg id is $!4#, 9sg str is SDivide by ero error encounteredT, .everity *evel
is !C and .tate is !.
9sg id: ID of the message, which is uniAue across server. 9essage IDs less than ;''''
are system messages.
9sg str: ,rror message that has to be displayed when the error raises.
.everity *evel: .everity level that is associated with the error. .everity levels can range
between ' and ";. .everity levels from "' through "; are considered fatal. If a fatal
severity level is encountered, the client connection is terminated after receiving the
message, and the error is logged in the error and application logs.
.tate: Is an arbitrary integer from ! through !"G. If the same user/defined error is raised
at multiple locations, using a uniAue state number for each location can help find which
section of code is raising the errors.
'aising /rrors $anually: 6e can also raise errors manually at some reAuired
situations. It is used to return messages bac& to applications using the same format as a
system error or warning message generated by the .:* .erver Database ,ngine. -or
raising an error manually we use the 'aiserror .tatement.
C;
It generates an error message and initiates error processing for the session. +AI.,++F+
can either reference a user/defined message stored in the sys.messages catalog view or
build a message dynamically. The message is returned as a server error message to the
calling application or to an associated 7AT7L bloc& of a T+BY7AT7L construct.
+AI.,++F+ can return either:
A user/defined error message that has been created using the sp1addmessage
system stored procedure.
A message string specified in the +AI.,++F+ statement.
+AI.,++F+ can also:
Assign a specific error number, severity, and state.
+eAuest that the error be logged in the Database ,ngine error log and the
9icrosoft 6indows application log.
.ubstitute argument values into the message text, much li&e the 7 language printf
function.
Synta*: +AI.,++F+ 2 msgPid > msgPstr > \localPvariable, severity, state
0, argument 0 ,...n 1 1 3
0 6ITL option 0 ,...n 1 1
msgPid: Is a user/defined error message number stored in the sys.messages catalog view
using spPaddmessage. ,rror numbers for user/defined error messages should be greater
than ;''''. 6hen msgPid is not specified, +AI.,++F+ raises an error message with an
error number
of ;''''.
msgPstr: Is a user/defined message with formatting similar to the printf function in the 7
standard library. The error message can have a maximum of ",'#G characters. 6hen
msg_str is specified, +AI.,++F+ raises an error message with an error number of
;''''.
msgPstr is a string of characters with optional embedded conversion specifications. ,ach
conversion specification defines how a value in the argument list is formatted and placed
into a field at the location of the conversion specification in msgPstr. The parameters that
can be used in msg_str are:
d or i .igned Integer
s .tring
u )nsigned Integer
These type specifications are based on the ones originally defined for the printf function
in the 7 standard library. The type specifications used in +AI.,++F+ message strings
map to Transact/.:* data types, while the specifications used in printf map to 7
language data types.
\localPvariable: Is a variable of any valid character data type that contains a string
formatted in the same manner as msgPstr. \localPvariable must be c)ar or "arc)ar.
CC
.everity: Is the user/defined severity level associated with this message. 6hen using
msgPid to raise a user/defined message created using sp1addmessage, the severity
specified on +AI.,++F+ overrides the severity specified in sp1addmessage.
Any user can specify severity levels from ' through !$. 9embers of the sysadmin fixed
server role permissions can only specify severity levels from != through ";, for which the
6ITL *FD option is reAuired.
.tate: Is an arbitrary integer from ! through !"G. A negative value for state defaults to !.
The value ' or values larger than !"G generate an error.
Argument: Are the parameters used in the substitution for variables defined in msgPstr or
the message corresponding to msgPid. There can be ' or more substitution parameters,
but the total number of substitution parameters cannot exceed "'. ,ach substitution
parameter can be a local variable or any of these data types: tinyint, smallint, int, c)ar,
"arc)ar, nc)ar, n"arc)ar, binary, or "arbinary. (o other data types are supported.
Fption: Is a custom option for the error and can be one of the values in the following
table.
!. *FD: *ogs the error in the error log and the application log for the
instance of the 9icrosoft .:* .erver Database ,ngine. ,rrors logged in
the error log are currently limited to a maximum of ##' bytes. Fnly a
member of the sysadmin fixed server role can specify 6ITL *FD.
". (F6AIT: .ends messages immediately to the client.
4. .,T,++F+: .ets the \\,++F+ and ,++F+P()9%,+ values to
msgPid or ;'''', regardless of the severity level.
The errors generated by +AI.,++F+ operate the same as errors generated by the
Database ,ngine code. The values specified by +AI.,++F+ are reported by the
,++F+P*I(,, ,++F+P9,..AD,, ,++F+P()9%,+, ,++F+PN+F7,D)+,,
,++F+P.,8,+ITB, ,++F+P.TAT,, and \\,++F+ system functions. 6hen
+AI.,++F+ is run with a severity of !! or higher in a T+B bloc&, it transfers control to
the associated 7AT7L bloc&.
The error is returned to the caller if +AI.,++F+ is run:
Futside the scope of any T+B bloc&.
6ith a severity of !' or lower in a T+B bloc&.
6ith a severity of "' or higher that terminates the database connection.
7AT7L bloc&s can use +AI.,++F+ to rethrow the error that invo&ed the 7AT7L bloc&
by using system functions such as ,++F+P()9%,+ and ,++F+P9,..AD, to
retrieve the original error information. \\,++F+ is set to ' by default for messages
with a severity from ! through !'.
CG
/A procedure to divide " numbers and will raise an error when the divisor is !.
7+,AT, N+F7,D)+, Divx2\E int, \B int3
As
%egin
Declare \] I(T
.,T \]M'
I- \BM!
+AI.,++F+ 2W7A((FT DI8ID, %B !W, !;, !3
.,T \]M\EU\B
N+I(T WThe Futput is: W @ 7ast2\] as varchar3
,nd
/,xecuting the above procedure:
,E,7 DI8E !'', "'
,E,7 DI8E !'', !
/In the above case the +AI.,++F+ statement raises the error but still next statements
get executed. .o if we want to stop the execution on the same line the code has to be
enclosed with in the Try and 7atch bloc&s.
7+,AT, N+F7,D)+, Divx2\E int, \B int3
As
%egin
%egin Try
Declare \] I(T
.,T \]M'
I- \BM!
+AI.,++F+ 2W7A((FT DI8ID, %B !W, !;, !3
.,T \]M\EU\B
N+I(T WThe Futput is: W @ 7ast2\] as varchar3
,nd Try
%egin 7atch
N+I(T ,++F+P9,..AD,23
,nd 7atch
,nd
/,xecuting the above procedure:
,E,7 DI8E !'', !
/In the above case when the error is raised the control transfers to the catch bloc& and
prints the error message associated with the error.
/If we want to customie the error message with formatting we can use the +aiserror
statement as following:
+AI.,++F+ 2W7A((FT DI8ID, Zd 6ITL ZdW, !;, !, \E, \B3
C$
/In this case substituting the value of variable \E at the first Z d location and the \y at
second Z d location it will generate the error message.
/6e can also use the S6ITL *FDT option at the end of the string to write the error
message into the .:* .erver *og -ile as following:
+AI.,++F+ 2W7A((FT DI8ID, Zd 6ITL ZdW, !;, !, \E, \B3 6ITL *FD
/After running the procedure which will generate the error go and verify under the
following location in the Fbject ,xplorer of the 9anagement .tudio i.e. under the
9anagement node, .:* .erver logs node, 7urrent node clic& on it where we find the
error message.
Pre-defined /rrors: All the predefined error list of sAl server can be found in the
.B..9essages 7atalog 8iew. :uery on the database with the following statement where
we can view the list of predefined errors:
-S/3/%T B D'+$ SPS8$/SS(Q/S
/This will display the list of errors with their errorPid, severity level, errorPmsg and
languagePid.
/6e can also insert our own user defined error messages into it and use them when
reAuired, but because this is a .ystem 7atalog 8iew we cannot directly insert records into
it, so .:* .erver provides a predefined Nrocedure .NPAdd9essage which when called
will insert the record into the 7atalog 8iew.
SP1(dd$essage: .tores a new user/defined error message in an instance of the .:*
.erver Database ,ngine. 9essages stored using spPaddmessage can be viewed using the
sys8messages catalog view.
.yntax: sp1addmessage 4 Rmsgnum E 6 msg1id ,
4 Rse"erity E 6 se"erity ,
4 Rmsgte*t E 6 LmsgL
4 , 4 Rlang E 6 LlanguageL 6
4 , 4 R5it)1log E 6 L5it)1logL 6
4 , 4 Rreplace E 6 LreplaceL 6
4 Rmsgnum E 6 msg1id: Is the ID of the message. msg_id is int with a default of ()**.
msg_id for user/defined error messages can be an integer between ;',''! and
",!#G,#$4,C#G. The combination of msg_id and language must be uniAue5 an error is
returned if the ID already exists for the specified language.
4 Rse"erity E 6 se"erity: Is the severity level of the error. severity is smallint with a
default of ()**. 8alid levels are from ! through ";.
4 Rmsgte*t E 6 LmsgL: Is the text of the error message. msg is n"arc)ar(:) with a
default of ()**.
C=
4 Rlang E 6 LlanguageL: Is the language for this message. %ecause multiple languages
can be installed on the same server, language specifies the language in which each
message is written. 6hen language is omitted, the language is the default language for
the session.
4 @with_log = 6 S LT',/L C LD(3S/L 6 T: Is whether the message is to be written to the
6indows application log when it occurs. The @with_log is "arc)ar()with a default of
-A*.,. If T+),, the error will be written in to the 6indows application log. If a
message is written to the 6indows application log, it is also written to the Database
,ngine error log file.
4 Rreplace E 6 LreplaceL: If specified as the string replace, an existing error message is
overwritten with new message text and severity level. \replace is varchar2G3 with a
default of ()**. This option must be specified if msgPid already exists. If you replace a
)... ,nglish message, the severity level is replaced for all messages in all other
languages that have the same msgPid.
/./% sp1addmessage <<<1, 1A, =%annot Di"ide t)e 9umber by +ne>
/The above statement will insert a record into the .B..9essages .ystem 7atalog after it
was inserted we can use the raiseerror statement as following in our previous procedure:
'aiserror(<<<1, 1A, 1)
/.o when the error is raised the corresponding error message is pic&ed out from the
7atalog 8iew and displayed to the user.
/Add Nrocedure, which will delete a record from the dept table for the given deptno and
will raise an error if the deptno has any child records in the emp table.
7+,AT, N+F7,D)+, DeletePDept2\Deptno int3
As
%egin
I- ,EI.T.2.,*,7T J -+F9 ,mp 6L,+, DeptnoM\Deptno3
+aiserror2I7hild +ecords -oundH, !;, !3
,*.,
D,*,T, -+F9 Dept 6L,+, DeptnoM\Deptno
,nd
/After creating a Nrocedure at any time if we want to view the content of it write the
following statement:
SP1@/3PT/.T 0procedure1name2
SP1@/3PT/.T Delete1Dept
%reating a Procedure using Iit) /ncryption +ption:
G'
7+,AT, N+F7,D)+, DeletePDept2\Deptno int3
6ITL ,(7+BNTIF(
As
%egin
I- ,EI.T.2.,*,7T J -+F9 ,mp 6L,+, DeptnoM\Deptno3
+aiserror2I7hild +ecords -oundH, !;, !3
,*.,
D,*,T, -+F9 Dept 6L,+, DeptnoM\Deptno
,nd
-If the Nrocedure is created by using the 6ith ,ncryption Fption even if we use the
.NPL,*NT,ET also we cannot view the content of it.
Procedures:
A -unction is also .tored %loc& of code similar to a Nrocedure.
A -unction is a %loc& of 7ode which will return only a single value.
A -unction is not a stand alone executable li&e a Nrocedure it can be executed in
some other context also.
A -unction can be used in a .elect .tatement.
9odifications to database tables, operations on cursors that are not local to the
function are examples of actions that cannot be performed in a function.
Try and 7atch .tatements cannot be used in the -unctions.
A user/defined function ta&es ero or more input parameters and returns either a
scalar value or a table5 a function can have a maximum of !'"# input parameters.
)ser/defined functions do not support output parameters.
6hen a parameter of the function has a default value, the &eyword D,-A)*T
must be specified when calling the function to get the default value.
-unctions are of 4 types:
!. .calar -unctions
". Inline Table/valued -unctions
4. 9ultistatement Table/valued -unctions
.calar -unctions: -unctions are scalar/valued if the +,T)+(. clause specifies one of
the scalar data types.
Synta*: 7+,AT, -)(7TIF( OfunctionPnameQ
( 0 RparameterPname 0 A. 1 dataPtype 0 E default 1 0 ,...n 1 1 )
+,T)+(. dataPtype
0 6ITL OfunctionPoptionQ 0 ,...n 1 1
0 A. 1
%,DI(
functionPbody
+,T)+( scalarPexpression
,(D
G!
functionPoptions can be any of these two:
!. ,ncryption
". .chemabinding
,(7+BNTIF(: Indicates that the Database ,ngine encrypts the catalog view columns
that contain the text of the 7+,AT, -)(7TIF( statement.
.7L,9A%I(DI(D: .pecifies that the function is bound to the database objects that it
references. The binding of the function to the objects it references is removed only when
one of the following actions occurs:
The function is dropped.
The function is modified by using the A*T,+ statement with the
.7L,9A%I(DI(D option not specified.
/A -unction that ta&es the ,mpno and +eturns the total salary of the employee.
7+,AT, -)(7TIF( D,TPT.A* 2\,9N(F I(T3
+,T)+(. 9F(,B
A.
%,DI(
D,7*A+, \T.A* 9F(,B
.,*,7T \T.A*M.A* @ I.()** 27F99, '3 -+F9 ,9N 6L,+,
,9N(FM\,9N(F
+,T)+( \T.A*
,(D
.yntax for 7alling a .calar -unction:
.,*,7T OownerQ.OfunctionPnameQ2 Olist of valuesQ 3
7alling the above function:
.,*,7T D%F.D,TPT.A*2!'';3
Inline Table/valued -unctions: These functions can return a table as an output. In inline
table/valued functions, the TA%*, return value is defined through a single .,*,7T
statement. Inline functions do not have associated return variables.

Synta*: 7+,AT, -)(7TIF( OfunctionPnameQ
( 0 RparameterPname 0 A. 1 dataPtype 0 E default 1 0 ,...n 1 1 )
+,T)+(. TA%*,
0 6ITL OfunctionPoptionQ 0 ,...n 1 1
0 A. 1
%,DI(
functionPbody
+,T)+( 0 2 1 selectPstmt 0 3 1
G"
,(D
/A function which ta&es the deptno and returns the list of employees wor&ing in it by
joining ,mp and Dept tables.
7+,AT, -)(7TIF( D,TP,DPDATA2\D,NT(F I(T3
+,T)+(. TA%*,
A.
+,T)+( 2.,*,7T ,.,9N(F, ,(A9,, ,..A*, D.D,NT(F, D.D(A9,,
D.*F7 -+F9 ,9N , I((,+ <FI( D,NT D F( ,.D,NT(FMD.D,NT(F
6L,+, ,.D,NT(FM\D,NT(F3
.yntax for 7alling a Table 8alued -unctions:
.,*,7T O J > OcollistQ -+F9 OfunctionPnameQ2 Olist of valuesQ 3
7alling the above function:
.,*,7T J -+F9 D,TP,DPDATA2!'3
.,*,7T ,9N(F, ,(A9,, D,NT(F, D(A9, -+F9 D,TP,DPDATA2"'3
9ultistatement Table/valued -unctions: These function are same as Inline Table/valued
but the body of this functions can contain multiple statement in it and the structure of the
table can be defined by us.
Synta*: 7+,AT, -)(7TIF( OfunctionPnameQ
( 0 RparameterPname 0 A. 1 dataPtype 0 E default 1 0 ,...n 1 1 )
+,T)+(. RreturnPvariable TA%*, O tablePtypePdefinition Q
0 6ITL OfunctionPoptionQ 0 ,...n 1 1
0 A. 1
%,DI(
functionPbody
+,T)+(
,(D
/A function which, ta&es the ,mpno and calculates the Total .alary and Annual .alary of
the employee and returns them.
7+,AT, -)(7TIF( D,TP,9NDATA2\,9N(F I(T3
+,T)+(. \9BTA%*, TA%*,2TFT.A* 9F(,B, A((.A* 9F(,B3
A.
%,DI(
D,7*A+, \.A* 9F(,B, \7F99 9F(,B
D,7*A+, \T.A* 9F(,B, \A.A* 9F(,B
.,*,7T \.A*M.A*, \7F99M7F99 -+F9 ,9N 6L,+,
,9N(FM\,9N(F
.,T \T.A*M\.A* @ I.()**2\7F99, '3
.,T \A.A*M2\.A* @ I.()**2\7F99, '33 J !"
G4
I(.,+T I(TF \9BTA%*, 8A*),.2\T.A*, \A.A*3
+,T)+(
,(D
7alling the above function:
.,*,7T J -+F9 D,TP ,9NDATA2!'';3
T'IQQ/'S
9icrosoft .:* .erver "''; provides two primary mechanisms for enforcing
business rules ,data integrity,log/file maintemance: constraints and triggers.
A trigger is a special type of stored procedure that automatically ta&es effect when
a language event executes.
.:* .erver includes two general types of triggers: D9* triggers and DD*
triggers.
DD* triggers are new to .:* .erver "'';. These triggers are invo&ed when a
data definition language 2DD*3 event ta&es place in the server or database.
D9* triggers are invo&ed when a data manipulation language 2D9*3 event ta&es
place in the database. D9* events include I(.,+T, )NDAT,, or D,*,T,
statements that modify data in a specified table or view.
A D9* trigger can Auery other tables and can include complex Transact/.:*
statements. The trigger and the statement that fires it are treated as a single
transaction, which can be rolled bac& from within the trigger. If a server error is
detected 2for example, insufficient dis& space3, the entire transaction
automatically rolls bac&.
D9* triggers are useful in these ways:
They can cascade changes through related tables in the database5 however, these
changes can be executed more efficiently using cascading referential integrity
constraints.
They can guard against malicious or incorrect I(.,+T, )NDAT,, and D,*,T,
operations and enforce other restrictions that are more complex than those defined
with 7L,7K constraints.
)nli&e 7L,7K constraints, D9* triggers can reference columns in other tables.
-or example, a trigger can use a .,*,7T 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.
They can evaluate the state of a table before and after a data modification and ta&e
actions based on that difference.
9ultiple D9* triggers of the same type 2I(.,+T, )NDAT,, or D,*,T,3 on a
table allow multiple, different actions to ta&e place in response to the same
modification statement.
G#
Types of D9* Triggers:
(DT/' Triggers: A-T,+ triggers are executed after the action of the I(.,+T,
)NDAT,, or D,*,T, statement is performed. .pecifying A-T,+ is the same as
specifying -F+, which is the only option available in earlier versions of 9icrosoft .:*
.erver. A-T,+ triggers can be specified only on tables.
I9ST/(D +D Triggers: I(.T,AD F- triggers are executed in place of the usual
triggering action. I(.T,AD F- triggers can also be defined on views with one or more
base tables, where they can extend the types of updates a view can support.
A trigger is a special &ind of stored procedure that automatically executes when an event
occurs in the database server. D9* triggers execute when a user tries to modify data
through a data manipulation language 2D9*3 event. D9* events are I(.,+T, )NDAT,,
or D,*,T, statements on a table or view. DD* triggers execute in response to a variety
of data definition language 2DD*3 events. These are primarily 7+,AT,, A*T,+, and
D+FN statements. D9* and DD* triggers can be created in the .:* .erver "'';
Database ,ngine directly from Transact/.:*. .:* .erver allows for creating multiple
triggers for any specific statement.
.yntax: 7+,AT, T+IDD,+ triggerPname
F( table > view
0 6ITL ,(7+BNTIF( 1
-F+ > A-T,+ > I(.T,AD F-
0 I(.,+T 1 0 , 1 0 )NDAT, 1 0 , 1 0 D,*,T, 1
A.
%,DI(
sAlPstatements
,(D
table > view: Is the table or view on which the D9* trigger is executed and is sometimes
referred to as the trigger table or trigger view. A view can be referenced only by an
I(.T,AD F- trigger.
6ITL ,(7+BNTIF(: ,ncrypts the text of the 7+,AT, T+IDD,+ statement.
A-T,+: .pecifies that the D9* trigger be fired only when all operations specified in the
triggering .:* statement have executed successfully. All referential cascade actions and
constraint chec&s also must succeed before this trigger fires. A-T,+ is the default when
-F+ is the only &eyword specified. A-T,+ triggers cannot be defined on views.
I(.T,AD F-: .pecifies that the D9* trigger be executed instead of the triggering .:*
statement, therefore, overriding the actions of the triggering statements. At most, one
I(.T,AD F- trigger per I(.,+T, )NDAT,, or D,*,T, statement can be defined on a
table or view. I(.T,AD F- triggers are not allowed on updatable views that use 6ITL
7L,7K FNTIF(. .:* .erver raises an error when an I(.T,AD F- trigger is added to
G;
an updatable view 6ITL 7L,7K FNTIF( specified. The user must remove that option
by using A*T,+ 8I,6 before defining the I(.T,AD F- trigger.
0 D,*,T, 1 0 , 1 0 I(.,+T 1 0 , 1 0 )NDAT, 1: .pecifies the data modification statements
that activate the D9* trigger when it is tried against this table or view. At least one
option must be specified. Any combination of these options in any order is allowed in the
trigger definition. -or I(.T,AD F- triggers, the D,*,T, option is not allowed on
tables that have a referential relationship specifying a cascade action F( D,*,T,.
.imilarly, the )NDAT, option is not allowed on tables that have a referential relationship
specifying a cascade action F( )NDAT,.
/A Trigger that will restrict the operations to be performed before = A.9 and after ; N.9
7+,AT, T+IDD,+ ,9NPT+D
F( ,9N A-T,+ I(.,+T, )NDAT,, D,*,T,
A.
%,DI(
D,7*A+, \DT I(T
.,T \DTMDAT,(A9,2LL, D,TDAT,233
I- \DT (FT %,T6,,( = A(D !C
%,DI(
+F**%A7K
+AI.,++F+2W7A((FT N,+-F+9 D9* FN,+ATIF(. (F6W, !;, !3
,(D
,(D
/After the trigger is created try to perform any D9* Fperations on the ,9N table before
= A.9 and after ; N.9 the Trigger will fire and restrict the operations.
6hen we try to perform any D9* Fperation on a table when a trigger is present
on it the values of the D9* statement will be captured in the trigger inside "
9agic Tables Inserted and Deleted that have the same structure of the table.
The deleted table stores copies of the affected rows during D,*,T, and
)NDAT, statements. During the execution of a D,*,T, or )NDAT, statement,
rows are deleted from the trigger table and transferred to the deleted table. The
deleted table and the trigger table ordinarily have no rows in common.
The inserted table stores copies of the affected rows during I(.,+T and
)NDAT, statements. During an insert or update transaction, new rows are added
at the same time to both the inserted table and the trigger table. The rows in the
inserted table are copies of the new rows in the trigger table.
An update transaction is similar to a delete operation followed by an insert
operation5 the old rows are copied to the deleted table first, and then the new rows
are copied to the trigger table and to the inserted table.
/A trigger that will convert the D(ame and *oc into upper case when the user insert in
lower case.
GC
7+,AT, T+IDD,+ D,NTP7F(8,+TPT+D
F( D,NT A-T,+ I(.,+T
A.
%,DI(
D,7*A+, \D,NT(F I(T
D,7*A+, \D(A9, 8A+7LA+2;'3
D,7*A+, \*F7 8A+7LA+2;'3
.,*,7T \D,NT(FMD,NT(F,\ D(A9,MD(A9,, \*F7M*F7 -+F9
I(.,+T,D
)NDAT, D,NT .,T D(A9,M)NN,+2\D(A9,3, *F7M)NN,+2\*F73
6L,+, D,NT(FM\D,NT(F
,(D
/To test the trigger execute the following statement which will convert the data into upper
case in the table:
I(.,+T I(TF D,NT 8A*),.2;', IresearchH ,HhyderabadH3
/The above trigger can be written in the following way also:
7+,AT, T+IDD,+ D,NTP7F(8,+TPT+D"
F( D,NT I(.T,AD F- I(.,+T
A.
%,DI(
I(.,+T I(TF D,NT
.,*,7T D,NT(F, )NN,+2D(A9,3, )NN,+2*F73 -+F9 I(.,+T,D
,(D
/A Trigger which will generate a uniAue Deptno when the user inserts a record into the
dept table only by specifying D(ame and *oc when a primary &ey constraint is present
on the Deptno column.
7+,AT, T+IDD,+ D,NTPD,(,+AT,PT+D
F( D,NT I(.T,AD F- I(.,+T
A.
%,DI(
D,7*A+, \D,NT(F I(T
.,*,7T \D,NT(FMD,NT(F -+F9 I(.,+T,D
I- \D,NT(F I. ()**
.,*,7T \D,NT(FMI.()**29AE2D,NT(F3, '3 @ !' -+F9 D,NT
I(.,+T I(TF D,NT .,*,7T \D,NT(F, D(A9,, *F7 -+F9 I(.,+T,D
,(D
/To test the following Trigger execute the following statement:
I(.,+T I(TF D,NT2D(A9,, *F73 8A*),.2W+,.,A+7LW, WLBD,+A%ADW3
GG
/A program which will restrict the Delete operation if the <ob of the person is 9anager.
A*T,+ T+IDD,+ ,9NPD,*,T,PT+D
F( ,9N A-T,+ D,*,T,
A.
%,DI(
D,7*A+, \<F% 8A+7LA+2;'3
.,*,7T \<F%M<F% -+F9 D,*,T,D
I- \<F%MW9A(AD,+W
%,DI(
+F**%A7K
+AI.,++F+2W7A((FT D,*,T, 9A(AD,+ -+F9 TL, TA%*,W, !;, !3
,(D
,(D
/To test the following Trigger execute the following statement:
D,*,T, -+F9 ,9N 6L,+, ,9N(FM!''"
A Trigger which will restrict to update the .alary of the ,mployee if the (ew .alary is
less than the Fld .alary.
7+,AT, T+IDD,+ ,9NP)NDAT,PT+D
F( ,9N A-T,+ )NDAT,
A.
%,DI(
D,7*A+, \F*D.A* 9F(,B
D,7*A+, \(,6.A* 9F(,B
.,*,7T \F*D.A*M.A* -+F9 D,*,T,D
.,*,7T \(,6.A*M.A* -+F9 I(.,+T,D
I- \F*D.A* Q \(,6.A*
%,DI(
+F**%A7K
+AI.,++F+2W(,6 .A* 7A((FT %, *,.. TLA( F*D .A*W, !;, !3
,(D
,(D
(,.T,D T+IDD,+.: Triggers can be nested to a maximum of 4" levels. If a trigger
changes a table on which there is another trigger, the second trigger is activated and can
then call a third trigger, and so on. To disable nested triggers, set the nested triggers
option of sp1configure to ' 2off3. The default configuration allows for nested triggers.
/A Trigger which will fire when a record is inserted into the ,mp table which verifies
whether the given Deptno is present in the Dept table or not if not it will insert a record
into it.
7+,AT, T+IDD,+ ,9NP(,.T,DPT+D
G$
F( ,9N A-T,+ I(.,+T
A.
%,DI(
D,7*A+, \D,NT(F I(T
.,*,7T \D,NT(FMD,NT(F -+F9 I(.,+T,D
I- (FT ,EI.T.2.,*,7T J -+F9 D,NT 6L,+, D,NT(FM\D,NT(F3
I(.,+T I(TF D,NT 8A*),.2\D,NT(F, ()**, ()**3
,(D
/A Trigger which will fire when a record is inserted into the Dept table which verifies
whether the given Deptno is present in the DeptDetails table or not if not it will insert a
record into it.
7+,AT, T+IDD,+ D,NTP(,.T,DPT+D
F( D,NT A-T,+ I(.,+T
A.
%,DI(
D,7*A+, \D,NT(F I(T
D,7*A+, \DID I(T
.,*,7T \D,NT(FMD,NT(F -+F9 I(.,+T,D
I- (FT ,EI.T.2.,*,7T J -+F9 D,NTD,TAI*. 6L,+,
D,NT(FM\D,NT(F3
%,DI(
.,*,7T \DIDM9AE2DID3@ ! -+F9 D,NTD,TAI*.
I(.,+T I(TF D,NTD,TAI*. 8A*),.2\DID, \D,NT(F, ()**3
,(D
,(D
/After creating the " Triggers if we try to insert a record into the ,mp table with a Deptno
not present in the Dept table it will insert a record into the Dept table which will
internally chec& whether the Deptno is present in the DeptDetails table or not and inserts
a records into it if not present.
Instead of Triggers on %omple* &ie5s 5)ic) are not updatable:
7+,AT, 8I,6 ,9NPD,NT
A.
.,*,7T ,.,9N(F, ,.,(A9,, ,..A*, D.D,NT(F, D.D(A9,, D.*F7
-+F9 ,9N , I((,+ <FI( D,NT D F( ,.D,NT(FMD.D,NT(F
/After creating the view try to execute the following insert which will fail because
complex views are by default non updatable:
I(.,+T I(TF ,9NPD,NT 8A*),.2!!'', I+A<)H, #;'', ;', IITH, I%A(D*F+,H3
G=
/If the above statement has to execute we need to define a Instead of trigger on the view
so that the 8iew become updatable.
7+,AT, T+IDD,+ 8I,6PI(.,+TPT+D
F( ,9NPD,NT I(.T,AD F- I(.,+T
A.
%,DI(
I(.,+T I(TF ,9N2,9N(F, ,(A9,, .A*, D,NT(F3
.,*,7T ,9N(F, ,(A9,, .A*, D,NT(F -+F9 I(.,+T,D
I(.,+T I(TF D,NT2D,NT(F, D(A9,, *F73
.,*,7T D,NT(F, D(A9,, *F7 -+F9 I(.,+T,D
,(D
/In the same way a trigger which will allow delete operations to be performed on the
8iew:
7+,AT, T+IDD,+ 8I,6PD,*,T,PT+D
F( ,9NPD,NT I(.T,AD F- D,*,T,
A.
%,DI(
D,7*A+, \D,NT(F I(T
D,7*A+, \7F)(T I(T
.,*,7T \D,NT(FMD,NT(F -+F9 D,*,T,D
.,*,7T \7F)(TM7F)(T2J3 -+F9 ,9N 6L,+, D,NT(FM\D,NT(F
D,*,T, -+F9 ,9N 6L,+, D,NT(FM\D,NT(F
I- \7F)(TM!
D,*,T, -+F9 D,NT 6L,+, D,NT(FM\D,NT(F
,(D
S($P3/ T(B3/S
These are the samples tables that are used in the examples in the above:
Dept Table with out 7onstraints:
7reate Table Dept2Deptno int, D(ame varchar2;'3, *oc varchar2;'33
Dept Table with 7onstraints:
7reate Table Dept2Deptno int 7onstraint DeptnoPN& Nrimary Key, D(ame
varchar2;'3, *oc varchar2;'33
,mp Table with out 7onstraints:
7reate table ,mp2,mpno int,,name varchar2!''3,<ob varchar2!''3,9gr
int,LireDate datetime,.al 9oney,7omm 9oney,Deptno int3
,mp Table with 7onstraints:
$'
7reate table ,mp2,mpno int 7onstraint ,mpnoPN& Nrimary Key,,name
varchar2!''3,<ob varchar2!''3, 9gr int 7onstraint 9grP+ef +eferences
,mp2,mpno3,LireDate datetime,.al 9oney 7onstraint .alP7hec& 7hec& 2sal
between !;'' and G;''3,7omm 9oney,Deptno int, 7onstraint DeptnoP+ef
-oreign Key 2Deptno3 +eferences Dept2Deptno33
DeptDetails Table with out 7onstraints:
7reate table DeptDetails 2Did int, deptno int, comments varchar2$'''33
DeptDetails Table with 7onstraints:
7reate table DeptDetails 2Did int primary &ey, deptno int references dept2deptno3,
comments varchar2$'''33
.algrade Table:
7reate Table .alDrade2Drade int 7onstraint DradePN& Nrimary Key, *o.al
9oney, Lisal 9oney3
Data in Dept Table:
Insert into Dept values2!', W9ar&etingW, W9umbaiW3
Insert into Dept values2"', W.alesW, W7hennaiW3
Insert into Dept values24', W-inanceW, WDelhiW3
Insert into Dept values2#', WNroductionW, WKol&otaW3
Data in ,mp Table:
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!''!, W.cottW, WNresidentW, ()**, W'!U'!UG$W, ;''', ()**, !'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!''", W7lar&W, W9anagerW, !''!, W'!U'!UG$W, #''', ()**, !'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!''4, W.mithW, W9anagerW, !''!, W'!U'!UG$W, 4;'', ;'', "'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!''#, W8ijayW, W9anagerW, !''!, W'!U'!UG$W, #''', ()**, 4'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!'';, WAjayW, W.alesmanW, !''4, W'"U'#UG=W, 4''', 4'', "'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!''C, W.atishW, W.alesmanW, !''4, W'"U'$UG$W, #''', C'', "'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!''G, W8en&atW, W.alesmanW, !''4, W'#U!;UG$W, 44'', ', "'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!''$, W8inodW, W7ler&W, !''4, W'!U!;UG$W, "#'', ()**, "'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!''=, W.uneelW, W7ler&W, !''#, W';U!"U$4W, "''', ()**, 4'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!'!', W.rinivasW, WAnalystW, !''#, W'4U'!UG=W, 4#'', ()**, 4'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!'!!, WNra&ashW, WAnalystW, !''#, W'4U'!UG=W, 4C'', ()**, 4'3
$!
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!'!", W9adanW, WAnalystW, !''#, W'!U'=U$!W, 4!'', ()**, 4'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!'!4, W+aviW, W7ler&W, !''", W'!U'CUG$W, !$'', ()**, !'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!'!#, W+ajuW, W7ler&W, !'';, W'CU'!UG$W, "4'', ()**, "'3
Insert into ,mp 2,mpno, ,name, <ob, 9gr, LireDate, .al, 7omm, Deptno3
8alues2!'!;, W+ameshW, W7ler&W, !'!!, W'$U""UG$W, ";'', ()**, 4'3
Data in DeptDetails Table:
Insert into DeptDetails values2!, !', WThis department is located in 9umbai and
mainly involved in mar&etingW3
Insert into DeptDetails values2", "', WThis department is located in 7hennai and
mainly involved in .alesW3
Insert into DeptDetails values24, 4', WThis department is located in Delhi and
mainly involved in -inanceW3
Insert into DeptDetails values2#, #', WThis department is located in Kol&ota and
mainly involved in NroductionW3
Data in .algrade Table:
Insert into .alDrade 8alues2!, !4'', !$''3
Insert into .alDrade values2", !$'', "G''3
Insert into .alDrade values24, "G'', 4;''3
Insert into .alDrade values2#, 4;'', ;'''3
Insert into .alDrade values2;, ;''', $'''3
%+DD ',3/S
-or a system to Aualify as a relational database management system 2+D%9.3, that
system must use its relational facilities 2exclusively3 to manage the database.
'ule 1: The information rule:
All information in the database is to be represented in one and only one way, namely by
values in column positions within rows of tables.
'ule : : The guaranteed access rule:
All data must be accessible with no ambiguity. This rule is essentially a restatement of the
fundamental reAuirement for primary &eys. It says that every individual scalar value in
the database must be logically addressable by specifying the name of the containing table,
the name of the containing column and the primary &ey value of the containing row.
'ule !: .ystematic treatment of null values:
The D%9. must allow each field to remain null 2or empty3. .pecifically, it must support
a representation of ^missing information and inapplicable information^ that is systematic,
$"
distinct from all regular values 2for example, ^distinct from ero or any other number,^ in
the case of numeric values3, and independent of data type. It is also implied that such
representations must be manipulated by the D%9. in a systematic way.
'ule ?: Active online catalog based on the relational model:
The system must support an online, inline, relational catalog that is accessible to
authoried users by means of their regular Auery language. That is, users must be able to
access the databaseWs structure 2catalog3 using the same Auery language that they use to
access the databaseWs data.
'ule : The comprehensive data sublanguage rule:
The system must support at least one relational language that
2a3 Las a linear syntax
2b3 7an be used both interactively and within application programs,
2c3 .upports data definition operations 2including view definitions3, data manipulation
operations 2update as well as retrieval3, security and integrity constraints, and transaction
management operations 2begin, commit, and rollbac&3.
'ule A: The view updating rule:
All views that are theoretically updatable must be updatable by the system.
'ule G: Ligh/level insert, update, and delete:
The system must support set/at/a/time insert, update, and delete operators. This means
that data can be retrieved from a relational database in sets constructed of data from
multiple rows andUor multiple tables. This rule states that insert, update, and delete
operations should be supported for any retrievable set rather than just for a single row in a
single table.
'ule O: Nhysical data independence:
7hanges to the physical level 2how the data is stored, whether in arrays or lin&ed lists
etc.3 must not reAuire a change to an application based on the structure.
'ule J: *ogical data independence:
7hanges to the logical level 2tables, columns, rows, and so on3 must not reAuire a change
to an application based on the structure. *ogical data independence is more difficult to
achieve than physical data independence.
'ule 1<: Integrity independence:
Integrity constraints must be specified separately from application programs and stored in
the catalog. It must be possible to change such constraints as and when appropriate
without unnecessarily affecting existing applications.
'ule 11: Distribution independence:
The distribution of portions of the database to various locations should be invisible to
users of the database. ,xisting applications should continue to operate successfully :
2a3 when a distributed version of the D%9. is first introduced5 and
2b3 when existing distributed data are redistributed around the system.
$4
'ule 1:: The nonsubversion rule:
If the system provides a low/level 2record/at/a/time3 interface, then that interface cannot
be used to subvert the system, for example, bypassing a relational security or integrity
constraint.
'ules of Data 9ormali#ation
19D ,liminate +epeating Droups / 9a&e a separate table for each set of related
attributes, and give each table a primary &ey.
:9D ,liminate +edundant Data / If an attribute depends on only part of a multi/valued
&ey, remove it to a separate table.
!9D ,liminate 7olumns (ot Dependent Fn Key / If attributes do not contribute to a
description of the &ey, remove them to a separate table.
B%9D %oyce/7odd (ormal -orm / If there are non/trivial dependencies between
candidate &ey attributes, separate them out into distinct tables.
?9D Isolate Independent 9ultiple +elationships / (o table may contain two or more
!:n or n:m relationships that are not directly related.
9D Isolate .emantically +elated 9ultiple +elationships / There may be practical
constrains on information that justify separating logically related many/to/many
relationships.
+9D Fptimal (ormal -orm / a model limited to only simple 2elemental3 facts, as
expressed in Fbject +ole 9odel notation.
$#
D;9D Domain/Key (ormal -orm / a model free from all modification anomalies.
1. Eliminate epeatin! "roups
In the original member list, each member name is followed by any databases that the
member has experience with. .ome might &now many, and others might not &now any.
To answer the Auestion, ^6ho &nows D%"_^ we need to perform an aw&ward scan of the
list loo&ing for references to D%". This is inefficient and an extremely untidy way to
store information.
9oving the &nown databases into a seperate table helps a lot. .eparating the repeating
groups of databases from the member information results in first normal form. The
9emberID in the database table matches the primary &ey in the member table, providing
a foreign &ey for relating the two tables with a join operation. (ow we can answer the
Auestion by loo&ing in the database table for ^D%"^ and getting the list of members.
2. Eliminate edundant Data
In the Database Table, the primary &ey is made up of the 9emberID and the DatabaseID.
This ma&es sense for other attributes li&e ^6here *earned^ and ^.&ill *evel^ attributes,
since they will be different for every memberUdatabase combination. %ut the database
name depends only on the DatabaseID. The same database name will appear redundantly
every time its associated ID appears in the Database Table.
.uppose you want to reclassify a database / give it a different DatabaseID. The change
has to be made for every member that lists that database[ If you miss some, youWll have
several members with the same database under different IDs. This is an update anomaly.
$;
Fr suppose the last member listing a particular database leaves the group. Lis records
will be removed from the system, and the database will not be stored anywhere[ This is a
delete anomaly. To avoid these problems, we need second normal form.
To achieve this, separate the attributes depending on both parts of the &ey from those
depending only on the DatabaseID. This results in two tables: ^Database^ which gives the
name for each DatabaseID, and ^9emberDatabase^ which lists the databases for each
member.
(ow we can reclassify a database in a single operation: loo& up the DatabaseID in the
^Database^ table and change its name. The result will instantly be available throughout
the application.
3. Eliminate #olumns $ot Dependent %n &ey
The 9ember table satisfies first normal form / it contains no repeating groups. It satisfies
second normal form / since it doesnWt have a multivalued &ey. %ut the &ey is 9emberID,
and the company name and location describe only a company, not a member. To achieve
third normal form, they must be moved into a separate table. .ince they describe a
company, 7ompany7ode becomes the &ey of the new ^7ompany^ table.
The motivation for this is the same for second normal form: we want to avoid update and
delete anomalies. -or example, suppose no members from the I%9 were currently stored
in the database. 6ith the previous design, there would be no record of its existence, even
though "' past members were from I%9[
$C
'#$(. 'oyce-#odd $ormal (orm
%oyce/7odd (ormal -orm states mathematically that:
A relation + is said to be in %7(- if whenever E /Q A holds in +, and A is not in E, then
E is a candidate &ey for +.
%7(- covers very specific situations where 4(- misses inter/dependencies between
non/&ey 2but candidate &ey3 attributes. Typically, any relation that is in 4(- is also in
%7(-. Lowever, a 4(- relation wonWt be in %7(- if 2a3 there are multiple candidate
&eys, 2b3 the &eys are composed of multiple attributes, and 2c3 there are common
attributes between the &eys.
%asically, a humorous way to remember %7(- is that all functional dependencies are:
^The &ey, the whole &ey, and nothing but the &ey, so help me 7odd.^
4. )solate )ndependent *ultiple elationships
This applies primarily to &ey/only associative tables, and appears as a ternary
relationship, but has incorrectly merged " distinct, independent relationships.
The way this situation starts is by a business reAuest list the one shown below. This could
be any " 9:9 relationships from a single entity. -or instance, a member could &now
many software tools, and a software tool may be used by many members. Also, a member
could have recommended many boo&s, and a boo& could be recommended by many
members.
$G
&nitial business "equest
.o, to resolve the two 9:9 relationships, we &now that we should resolve them
separately, and that would give us #th normal form. %ut, if we were to combine them into
a single table, it might loo& right 2it is in 4rd normal form3 at first. This is shown below,
and violates #th normal form.
&nco""ect solution
To get a picture of what is wrong, loo& at some sample data, shown below. The first few
records loo& right, where %ill &nows ,+6in and recommends the ,+6in %ible for
everyone to read. %ut something is wrong with 9ary and .teve. 9ary didnWt recommend
a boo&, and .teve DoesnWt &now any software tools. Fur solution has forced us to do
strange things li&e create dummy records in both %oo& and .oftware to allow the record
in the association, since it is &ey only table.
'a%(le data f"o% inco""ect solution
$$
The correct solution, to cause the model to be in #th normal form, is to ensure that all
9:9 relationships are resolved independently if they are indeed independent, as shown
below.
)o""ect 4t# no"%al fo"%
9+T/U This is not to say that A** ternary associations are invalid. The above situation
made it obvious that %oo&s and .oftware were independently lin&ed to 9embers. If,
however, there were distinct lin&s between all three, such that we would be stating that
^%ill recommends the ,+6in %ible as a reference for ,+6in^, then separating the
relationship into two separate associations would be incorrect. In that case, we would lose
the distinct information about the 4/way relationship.
5. )solate +emantically elated *ultiple elationships
FK, now lets modify the original business diagram and add a lin& between the boo&s and
the software tools, indicating which boo&s deal with which software tools, as shown
below.
&nitial business "equest
This ma&es sense after the discussion on +ule #, and again we may be tempted to resolve
the multiple 9:9 relationships into a single association, which would now violate ;th
normal form. The ternary association loo&s identical to the one shown in the #th normal
form example, and is also going to have trouble displaying the information correctly. This
time we would have even more trouble because we canWt show the relationships between
boo&s and software unless we have a member to lin& to, or we have to add our favorite
dummy member record to allow the record in the association table.
$=
&nco""ect solution
The solution, as before, is to ensure that all 9:9 relationships that are independent are
resolved independently, resulting in the model shown below. (ow information about
members and boo&s, members and software, and boo&s and software are all stored
independently, even though they are all very much semantically related. It is very
tempting in many situations to combine the multiple 9:9 relationships because they are
so similar. 6ithin complex business discussions, the lines can become blurred and the
correct solution not so obvious.
)o""ect 5t# no"%al fo"%
,. %ptimal $ormal (orm
At this point, we have done all we can with ,ntity/+elationship Diagrams 2,+D3. 9ost
people will stop here because this is usually pretty good. Lowever, another modeling
style called Fbject +ole 9odeling 2F+93 can display relationships that cannot be
expressed in ,+D. Therefore there are more normal forms beyond ;th. 6ith Fptimal
(ormal -orm 2F9-3
It is defined as a model limited to only simple 2elemental3 facts, as expressed in F+9.
-. Domain-&ey $ormal (orm
This level of normaliation is simply a model ta&en to the point where there are no
opportunities for modification anomalies.
^if every constraint on the relation is a logical conseAuence of the definition of &eys
and domains^
='
7onstraint ^a rule governing static values of attributes^
Key ^uniAue identifier of a tuple^
Domain ^description of an attributeHs allowed values^
!. A relation in DKU(- has no modification anomalies, and conversely.
". DKU(- is the ultimate normal form5 there is no higher normal form related to
modification anomalies
4. Defn: A relation is in DKU(- if every constraint on the relation is a logical
conseAuence of the definition of &eys and domains.
#. 7onstraint is any rule governing static values of attributes that is precise enough
to be ascertained whether or not it is true
;. ,.g. edit rules, intra/relation and inter/relation constraints, functional and multi/
valued dependencies.
C. (ot including constraints on changes in data values or time/dependent constraints.
G. Key / the uniAue identifier of a tuple.
$. Domain: physical and a logical description of an attributes allowed values.
=. Nhysical description is the format of an attribute.
!'. *ogical description is a further restriction of the values the domain is allowed
!!. *ogical conseAuence: find a constraint on &eys andUor domains which, if it is
enforced, means that the desired constraint is also enforced.
!". %ottom line on DKU(-: If every table has a single theme, then all functional
dependencies will be logical conseAuences of &eys. All data value constraints can
them be expressed as domain constraints.
!4. Nractical conseAuence: .ince &eys are enforced by the D%9. and domains are
enforced by edit chec&s on data input, all modification anomalies can be avoided
by just these two simple measures.
=!
="

Das könnte Ihnen auch gefallen