Anda di halaman 1dari 36

CHAPTER-1

DATABASE:

A collection of information, tables and other objects organized and presented


to serve a specific purpose, such as searching, sorting and recombining data. Database are
stored in files.

TABLES:

Describes how table are used to store rows of data and defined the relationship
between multiple tables.

* In 1989 the American national standards institute (ANSI) published the first set of
standards for
* A database query language called ansi- .sql

Types Of Commands:

1. DDL COMMANDS (DATA DEFINATION LANGUAGE)


2. DML COMMANDS (DATA MANULIPLATE LANGUAGE)
3. DCL COMMANDS (DATA CONTROL LANGUAGE)

1. DDL Commands:

DDL statements are used to create, delete, or change the object of a


database.

DDL STATEMENTS

* Create Database, Create Table, Create Index, Create Procedure, Create View
* Alter Table, Alter Index, Alter Trigger, Alter Procedure, Alter View.
* Drop Database, Drop Table, Drop Trigger, Drop View, Drop Procedure.

To Create a Database

It creates a new database and the files used to store the database this
statements allocates space to two files .the first file .mdf, will hold the data for the
database .the second file .ldf will hold a record of any changes made to the database.

Syntax:
Create database databasename
Example:
Create database anbu

To use the database

Syntax:
Use databasename

Example:
Use anbu

To Create The Table


It creates a new table in the current database.

Syntax:
Create table tablename (field1 datatype, field2 datatype, field3 datatype,… field n
datatype)

Example:
Create table emp (eno int, ename varchar (20), salary int)

Adding Rows To The Table

Syntax:
Insert into tablename values (value1, value2, value3,.............value n)

Example:
Insert into emp values (1,'a', 2000)
Insert into emp values (2,'b', 3000)
Insert into emp values (3,'c', 4000)
Insert into emp values (4,'d', 5000)
Insert into emp (eno, ename) values (5,'e')

To View The Information From Table


Syntax:
Select fieldname from tablename

Example:
Select * from emp

NOTE: (*) specifies all the fields in the table


Select eno, ename from emp
CHAPTER-2

Alter Table

Syntax:
Alter table tablename add/drop fieldname datatype

Example:
Alter table emp add age int
Alter table emp drop age

Drop Table

Syntax:
Drop table tablename

Example:
Drop table emp

Truncate Table

Syntax:
Truncate table tablename

Example:
Truncate table emp

Deleting Data From The Table

Syntax:
Delete from tablename where condition

Example:
Delete from emp where eno=9
Delete from emp
CHAPTER-3

Select Clauses

> WHERE
> DISTINCT
> ORDER BY
> ASC/DESC
> INTO
> TOP
> GROUP BY
> HAVING
> COMPUTE

> Where Clause

Operato Description
r
Equal
=
Not Equal
<>
> Greater Than
Less Than
<
Greater Than Or Equal
>=
<= Less Than Or Equal
Not Greater Than
!>
Not Less Than
<!

Example:
Select * from emp where salary=4000
Select * from emp where salary<=4000
Select * from emp where salary>=4000
Select * from emp where salary<>4000
Select * from emp where salary!>4000
Select * from emp where salary! <4000

Using Logical Operators

AND Any condition satisfied

OR All condition satisfied

BETWEEN Expression falls within a range


Example:
Select * from emp where salary=2000 or salary=1000
Select * from emp where salary>=2000 and salary<=5000
Select * from emp where salary between 2000 and 5000

Using Is Null And Is Not Null

Example:
Select * from emp where salary is null
Select * from emp where salary is not null

Using Like
% Matches any string of zero or more characters
_(UNDERSCORE) Matches any single characters
[] Matches a single character listed within the brackets
[-] Matches a single character within the given range
[^] Matches a single character not listed after the caret

Example:
Select * from emp where empname like 'a%'
Select * from emp where empname like 'bal_'
Select * from emp where empname like ' a [nrg] %'
Select * from emp where empname like 'a [b-h] %'
Select * from emp where empname like 'a [^b-h] %'

UPDATING DATA IN A TABLE

Example:
Update emp set salary=salary+1000
Update emp set salary=5000 where eno=9

DISTINCT CLAUSE

Example:
Insert into emp values (9,'i', 2000)
Select * from emp
Select distinct salary from emp

ORDER BY CLAUSE
Example:
Select * from emp order by salary asc
Select * from emp order by salary desc

INTO CLAUSE

Example:
Select eno, ename into stu from emp
Select * from stu

TOP CLAUSE

Example:
Select top 5* from emp
Select top 3 percent * from emp

CHAPTER-4
T-SQL Functions

1. Numeric Function
2. String Function
3. Date And Time Function
4. System Function
5. Calculating Function
6. Conversion Function
7. Other Function

Numeric Function

Example:
Select abs (-12)
Select floor (456.89)
Select ceiling (456.89)
Select rand (1)
Select round (12.345678, 3)
Select sign (-43)
Select sign (43)
Select sign (0)
Select sqrt (16)
Select radians (90)
Select degrees (25)
Select pi ()
Select tan (45)
Select cos (45)
Select sin (45)

String Functions

Example:
Select 'siva' +'ram'
Select ascii ('a')
Select char (65)
Select charindex ('a', 'anbu')
Select charindex ('ar', 'anbuarasu')
Select difference ('anbu','anbu')
Select lower ('anbu')
Select upper ('anbu')
Select replicate (' hai', 10)
Select reverse ('hai')
Select space (10) + 'hai' +space (10) + 'to'+ space (10) + 'everyone'
Select substring ('hello world', 1, 5)
Select stuff ('sevakasi', 1, 4,'ten')
Select soundex ('gita')
Select soundex ('geetha')
Select ' hai'
Select ltrim (' hai')
Select 'hello '+'world'
Select rtrim ('hello ') +'world'

Date Functions:
Datepart Values:

DATEPART ABBREIRATION VALUES


Year yy, yyy 1739-9999
Month MM 1-12
Day DD 1-366
week WK 0-51
day at year DY 1-366
week day DW 1-7
Hour HH 0-23
Minute MI 0-59
Second SS 0-59
Millisecond MS 0-999
Getdate ()
-Returns the current date and time

Example:
Select getdate ()

Dateadd ()
-Adds The Number to the Datepart of Date

Syntax:
Dateadd (datepart,number,date)

Example:
Select dateadd (yy, 2, getdate())
Select dateadd (mm, 2, getdate())
Select dateadd (dd, 2, getdate())

Datediff ()
- Returns the number of datepart between the 2 date

Syntax:
Datediff (datepart, date1, date2)

Example:
Select datediff (mm, '2004-1-1', '2005-1-1')
Select datediff (yy, '2004-1-1', '2005-1-1')
Select datediff (dd, '2004-1-1', '2005-1-1')

Datepart ()

Syntax:
Datepart (datepart,date)

Example:
Select datepart (yy, getdate())
Select datepart (dd, getdate())
Select datepart (mm, getdate())

Month ()
-returns the month as integer

Syntax:
Month (date)
Example:
Select month (getdate ())

Year ():
-returns the year as integer

Syntax:
Year (date)

Example:
Select year (getdate())

System functions:

Db_name ()
-returns the current database name

Example:
Select db_name ()

Db_id ()
-returns the database id

Example:
Select db_id ()

Datalength ()
-returns the actual length of an expression

Example:
Select datalength ('anbu')

Host_name ()
-returns the current host computer name

Example:
Select host_name ()

Object_name ()
-returns the database object name
Example:
Select object_name (1)

Object_id ()
-returns the database object id

Example:
Select object_id ('sysobject')

User_name ()
-returns the user name

Example:
Select user_name ()

User_id ()
-returns the user id

Example:
Select user_id ()

Suser_name ()
-returns the server user name

Example:
Select suser_name ()

Suser_id ()
-returns the server user id

Example:
Select suser_id ()

Calculating result function


-It is used to calculate summary values in a particular column and returns a single
value. For each set of rows to which the function applies.

Avg average of values in a numeric expression


Max highest value in the expression
Min lowest value in the expression
Sum total of values in a numeric expression
Count number of values in an expression either all or
distinct
Count(* number of selected rows
)

Example:
Create table stu1 (sno int, sname varchar (20),total int)
Insert into stu1 values (1,'a', 200)
Insert into stu1 values (2,'b', 300)
Insert into stu1 values (3,'c', 400)
Insert into stu1 (sno, sname) values (8,'h')
Insert into stu1 (sno, sname) values (9,'i')
Insert into stu1 (sno, sname) values (10,'j')
Select * from stu1

Select sum (total) from stu1


Select avg (total) from stu1
Select avg (total), count (total) from stu1
Select avg (total), count (*) from stu1
Select max (total) from stu1
Select min (total) from stu1

Convertion functions
-It is used to convert an expression from one datatype to another datatype

Syntax:
Convert (datatype, expression)

Example:
Select sname +' mark is '+convert (char, total) from stu1

Other functions

Isnull ()
Returns the specified value in place of null

Isnumeric ()
Returns a value of 1 if expression is in numeric else it will return 0

Isdate ()
Returns a value of 1 if expression is in date format else it will return 0

Group by:
It calculates summary data for groups of rows in a column.

Example:
Select job, max (salary), min (salary) from emp group by job
Having:
It determines which groups are included in the final result.

Example:
Select depno,count (*) a ‘ sno of employes ' from emp group by depno having count(*)>3

Compute:
It produces a single summarized result for each specified group of rows

Example:
Select deptno, empid, ename, salary from emp order by deptno compute sum (salary)

chapter-5

Union operator:
The union operator allows us to combine the result of 2 or more queries into single
result set. A union results in an increase in rows

Create table stu2 (sno2 int, sname2 varchar (20), total2 int)
Insert into stu2 values (1,'abi', 200)
Insert into stu2 values (2,'banu', 300)
Insert into stu2 values (3,'clarin', 400)
Insert into stu2 values (4,'deva', 500)
Insert into stu2 values (5,'ezhil', 600)
Select * from stu2

Create table stu3 (sno3 int, sname3 varchar (20), total3 int)
Insert into stu3 values (1,'abi', 200)
Insert into stu3 values (2,'babu', 300)
Insert into stu3 values (3,'clarin', 400)
Insert into stu3 values (4,'deva', 500)
Insert into stu3 values (5,'kumar', 600)
Select * from stu3

Example:
Select sname2 from stu2
Union
Select sname3 from stu3

Union all:
It is equal to the union command expect that union all selects all values
Example:
Select sname2 from stu2
Union all
Select sname3 from stu3

Joins:
It is used to retrieve and manipulate data from more than one table in a single select
statement. They are four types of joins .they are
1. Restricted joins or cross joins
2. Natural joins
3. Outer joins
4. Self joins

Restricted joins or cross joins:


It produces a result set that includes every combination of all the rows between the
tables. If they are 4 rows in one table and 6 rows in another table the result include 24 rows
(2*6)

Example:
Create table emp1 (eno int, ename varchar (20), empid int)
Insert into emp1 values (1,'anu', 10)
Insert into emp1 values (2,'babu', 10)
Insert into emp1 values (3,'clarin', 20)
Insert into emp1 (eno, ename) values (4,'deva')
Select * from emp1

Create table emp2 (depno int, depname varchar (20))


Insert into emp2 values (10,'manager')
Insert into emp2 values (20,'sales')
Insert into emp2 values (30,'marketing')
Select * from emp2

Select eno,ename,depname from emp1,emp2

Natural joins:
A natural join is one in which the column values being compared are equal for two or
more tables. But join column display only once.

Example:
Select eno, ename, depname from emp1, emp2 where emp1.empid=emp2.depno
Select emp1.eno, emp1.ename, emp2. depname from emp1,emp2 where
emp1.empid=emp2.depno

Select e1.eno, e1.ename, e2.depname from emp1 e1, emp2 e2 where e1.empid=e2.depno

Outer joins:
An outer join return all the rows from one table and some rows from another table
They are two types of outer join
1. Left Outer joins
2. Right Outer joins

Left Outer joins:


================
Displays all rows from the first table (the table on the left of the expression)

Example:
Select eno, ename, depname from emp1, emp2 where emp1.empid*=emp2.depno

Right outer joins:


Displays all rows from the second table (the table on the right of the expression)

Example:
Select eno, ename, depname from emp1, emp2 where emp1.empid=*emp2.depno

Self joins:
Joining the table to itself. Joins can also be used within a single table

Example:
Create table emp3 (eno int, ename varchar (20), magno int)
Insert into emp3 values (1,'anu', null)
Insert into emp3 values (2,'babu', 1)
Insert into emp3 values (3,'clarin', 1)
Insert into emp3 values (4,'deva', 2)
Select * from emp3

Select e1.eno, e1.ename, e2.ename from emp3 e1, emp3 e2 where e1.eno=e2.magno

SubQueries:
A sub queries is a select statement nested inside a select, insert, update or delete
statement. A subquery is a nested query.

Rules for writing subqueries:

1. The select statement of subquery is always enclosed in parantheses.


2. A subquery can be nested inside the where or having clauses
3. We cannot use a subquery in order by

Example:
Select * from emp where salary >= (select salary from emp where ename='d')

Subquery that returns single value:


Using in:

Example:
Select * from emp where salary in (select salary from emp where ename='d')

Using not in:

Select * from emp where salary not in (select salary from emp where ename='d')

Using Any,All,Some:

Example
Select * from emp where salary> any (select salary from emp where ename='d')
Select * from emp where salary> all (select salary from emp where ename='d')
Select * from emp where salary> some (select salary from emp where ename='d')

Chapter-6

Constraints:
A constrain is a rule defined for a single table taht limits that possible values user
Can enter into the table.they are five types of constraints.
1. Primary key constraint
2. Unique constraint
3. Foreign key constraint
4. Check constraint
5. Default constraint

1. Primary key constraint


Only one primary key can be defined per table. null values are not allowed, not two
rows can have same values

Syntax:
Create table tablename (fieldname datatype constraint keyname primary key,fieldname
datatype.......)
Example:
Create table emp4 (eno int constraint pk_name primary key, ename varchar (20), salary int)
Insert into emp4 values (1,'anu', 3000)
Insert into emp4 values (1,'babu', 1000)

Defining primary key after the table has been created:

Example:
alter table emp4 add constraint pk_name primary key (eno)

2. Unique constraint:
It is similar to primary key except it allows null values over one or more column,
But there can be only one row with a null value.

Syntax:
Create table tablename (fieldname datatype constraint keyname unique, fieldname
datatype.......)

Example:
Create table emp5 (eno int constraint uq_name unique, ename varchar (20), salary int)
Insert into emp5 values (1,'anu', 3000)
Insert into emp5 values (1,'babu', 1000)
Insert into emp5 (ename, salary) values ('siva', 2000)
Insert into emp5 (ename, salary) values ('mani', 6000)
Select * from emp5

Defining unique key after the table has been created:

Example
alter table emp5 add constraint uq_name unique (eno)

3. Foreign key constraint


The foreign key constraint defines a column or combination of columns whose value
matches the primary key of a table. It is used in conjunction with the references clause.
It must reference either the primary or unique constraint of another table.

Syntax:
Create table tablename (fieldname datatype constraint keyname foreign key references table
name (fieldname), fieldname datatype.......)

Example:
Select * from emp4
Create table emp6 (eno int constraint fo_name foreign key references emp4 (eno), ename
varchar (20), salary int)
Insert into emp6 values (1,'mani', 400)
Insert into emp6 values (2,'anbu', 3000)

Defining foreign key after the table has been created:

Example:
alter table emp6 add constraint fo_name foreign key (eno) references emp4 (eno)

4. Check constraint
It is user defined search condition similar to where clause of select statement.

Syntax:
Create table tablename (fieldname datatype constraint keyname check (expression),
fieldname datatype.......)

Example:
Create table emp7 (eno int, ename varchar (20), salary int constraint ck_name check
(salary<=10000))
Insert into emp7 values (1,'anu', 3000)
Insert into emp7 values (2,'banu', 10000)
Insert into emp7 values (1,'arul', 11000)

5. Default constraint
we can define default constraint for a column to supply a value when a user does not
enter a value. A column can have only one default constraint.

Syntax:
Create table tablename (fieldname datatype constraint keyname default value, fieldname
datatype.......)

Example:
Create table emp8 (eno int, ename varchar (20), salary int constraint df_name default 2000)
Insert into emp8 values (1,'anu', 3000)
Insert into emp8 (eno,ename) values (2,'banu')
Select * from emp8

Defining default key after the table has been created:

Example:
alter table emp8 add constraint df_name default 0 for salary

Identity:
The column identity property generates incremental values for the column that identify
Each row inserted into the table. we can use this feature to generates sequential number

Rules for creating identity:

1. A table can have only one column with the identity property
2. A column with identity property cannot be updated.
3. A column with identity property does not allow null to be inserted.
4. A column with identity property must have an integer or decimal datatypes.

Creating an identity column:

Syntax:
Identity (seed, increment)

Seed: is the value that is used for the very first row loaded into the table

Example:
Create table stu4 (studid int identity (101, 1), name varchar (10))

Insert into stu4 values ('john')


Insert into stu4 values ('Siva')
Insert into stu4 values ('banu')
Insert into stu4 values ('abi')
Select * from stu4

We can use system function ident_seed and ident_incr to determine the seed and
incremental values for an identity column.

Syntax:
ident_seed ('tablename')
ident_incr ('tablename')

Example:
Select ident_seed ('stu4')
Select ident_incr ('stu4')

Defaults:
A Default specifies a value to be inserted into a column. A default can be applied to
multiple columns in multiple tables. After a default has been created it has to bind to a
column or user defined datatype.

Syntax:
Create default defaultname as constant _ expression

Example:
Create table stu5 (stid int, name varchar (20), mark int)
Insert into stu5 values (1,'john', 400)

Create default defmrk as 200

Binding defaults:

Syntax:
exec sp_bindefault default_name, objectname

Example:
Exec sp_bindefault defmrk,'stu5.mark'
Insert into stu5 (stid,name) values (2,'siva')
Select * from stu5

Unbinding defaults:

Syntax:
exec sp_unbindefault objectname

Example:
Exec sp_unbindefault 'stu5.mark'

Dropping defaults:

Syntax:
Drop default defaultname

Example:
Drop default defmrk

Rules:
Rules are used to restrict the range and format to possible values that can enter in a
column.
Syntax:
create rule rulename as condition

Example:
Create rule rulmark as @mark<=500

Binding rules:

Syntax:
Exec sp_bindrule rulename,'objname'

Example:
exec sp_bindrule rulmark,'stu5.mark'
Select * from stu5
Insert into stu5 values (3,'kumar', 400)

Unbinding rules:

Syntax:
Exec sp_unbindrule 'objname'

Example:
exec sp_unbindrule 'stu5.mark'

Drop rule:

Syntax:
Drop rule rulename

Example:
Drop rule rulmark

Chapter-7
Views:
A view is a virtual table whose content are defined by a query. Like a real table a view
consist of set of named columns and rows of data.

Creating views:

Syntax:
Create view view_name
As
Select statement (with check option)

Example:
Create view eview
As select sno, sname from stu1

Manipulating views:

Example:
Insert into eview values (11,'k')
Select * from stu1
Select * from eview

Dropping views:

Syntax:
Drop view view_name

Example:
Drop view eview

Indexes:
An Index is a structure that provides for locating one or more rows directly.
Without an index, sql server has to perform a table scan, which involves searching through
the entire table. Index is a structure associated with a table that speeds retrieval of the rows
in the table.
Types of index
1. Clustered index
2. NoClustered index

1. Clustered index:
It will sort and store the data rows in the table based on their key values.

2. Noclustered index:
The data rows are not stored in order based on the noclustered key.

Creating index:

Syntax:
Create [clustered/nonclustered] index index_name on tablename (column name)
Example:
Create clustered index ind_no on stu1 (sno)
Create nonclustered index ind_no on stu1 (sno)

Dropping indexes:

Syntax:
Drop index table.index

Example:
Drop index stu1.ind_no

Chapter-1
Sql Server Programming.
Transact Sql Statement For Script Processing:
These statements are used within sql scripts to add functionality similar to that
provided by Procedural programming languages.

T-Sql Statements For Controlling The Flow Of Execution.

If...else control the flow of execution based on condition


Begin...end defines a statement block
While repeats statement while specific condition is true
Break exits the innermost while loop
Continue returns to the beginning of a while loop
Go to unconditionally changes the flow of execution
Return exits unconditionally

T-Sql Statements For Script Processing

Use changes to specified database


Print returns a message to the client
Declare declares a local variable
Set sets the value of a local or session variable
Exec executes a dynamic sql statements or stored procedure
.
Declare statement:
Used to create local variable

Syntax:
Declare @variable name datatype, @variable name datatype, ........

Example:
Declare @x int, @y int, @z int

Set statement:
To set or assign a value to a variable

Syntax:
Set @variablename =expression

Example:
Set @x=10
Set @y=20

Example1:
Declare @x int, @y int, @z int
Set @x=10
Set @y=20
Set @z=@x + @y
Print @x
Print @y
Print 'the result of two numbers is '+convert (varchar, @z)

Example2:
Declare @design varchar (20), @empname varchar (15)
Select @empname =ename, @design=job from emp where empno=101
Print 'employee name is '+ @empname
Print 'employee job'+ @design

Variables:
It is used to store data
Types:
1. Local variables
2. Global variables

1. Local variables:
They are often used in batches stored procedure, statements blocks. They are declared in
the body of batch or procedure using the declare statement.

2. Global variables:
They are predefined and maintained by the system. We can refer to them in script
without declaring them. Global variables start with 2 at symbols (@@).

@@version:
Date and number of the current version of sql server

Example:
Select @@version

@@servername:
Name of the server

Example:
Select @@servername

@@language
Name of the current language in use

Example:
Select @@language

@@langid
Local language id of the language in use

Example:
Select @@langid

@@rowcount
Number of rows affected by the last query

Example:
Select @@rowcount

@@trancount
Number of active transactions for the current user

Example:
Select @@trancount

@@error
Error number for the last t-sql statement executed

Example:
Select @@error

@@cursor_rows
Number of qualifying rows in the last opened cursor
Example:
Select @@cursor_rows

@@identity
Returns the last inserted identity value

Example:
Select @@identity

@@fetch_status
Status of the last cursor fetches statement

Example:
Select @@fetch_status

@@connections
No of logins or attempted logins since sql server started

Example:
Select @@connections

Temporary tables:
Temporary tables are used to store table data within a complex script. In addition
they provide a way for us to test queries against temporary data rather than permanent data.

Temporary table types:


1. Local temporary table
2. Global temporary table

1. Local temporary table:


The name of the local temporary table begins with a # sign. They are visible only to
the database session in which it is created

Example:
Select * into #stu6 from emp1
Select * from #stu6

2. Global Temporary Table:


The name of the global temporary table begins with a ## sign. They are visible to all
database session.

Example:
Create table ##stu7 (sno int, sname varchar (20), salary int)
Insert into ##stu7 values (1,'a', 2000)
Select * from ##stu7

Chapter-2

Conditional processing:
To execute a statement or block of statements based on a condition

1. If.....else

Syntax:
If
{statement/begin.....end}
Else
{statement/begin.....end}

Example:
Declare @duedate datetime
Select @duedate=returndate from stu where stuid=101
If getdate ()>@duedate
Print 'due date over must pay fine'

Example:
Declare @desig varchar (20)
Select @desig=job from emp where empno=101
If @desig='manager'
Update emp set salary=salary+2000 where empno=101
Else if @desig='clerk'
Update emp set salary=salary+1000 where empno=101
Else if @desig='analyst'
Update emp set salary=salary+500 where empno=101

Continue statement:

Example:
Declare @x int
Set @x=0
While @x<=15
Begin
Select @x=@x+1
If @x%2=0
Continue
Print @x
End

Chapter-3
Stored procedure:
A stored procedure is a database object that contains one or more sql statements.
Stored procedure are precompiled that means that the execution plan for the sql
code is compiled the first time the procedure is executed and is then saved in its compiled
form. It execute faster than an equivalent sql script

Syntax:
Create procedure procedurename
{@parameter datatype.........}
As sql statement

Example:
create procedure add_prod
As
Select sno, sname from stu1

Executing stored procedure:

Example:
Exec add_prod

Example:
Create procedure ins1
@pid int,
@pname varchar (10),
@price int
As
Insert into stu1 (sno,sname,total) values(@pid,@pname,@price)

Exec ins1 12,'m', 200

Select * from stu1

Creating a stored procedure that returns the product of 2 numbers


Example:
Create procedure findpro
@x int,
@y int,
@z int output
As select @z=@x*@y

Calling or executing stored proedure

Example:
Declare @result int
Execute findpro 25,10,@result output
Print 'the product is '+convert (varchar, @result)

Chapter-4
Triggers:
A trigger is a special type of stored procedure that executes automatically when an
insert, update, or delete statement is executed on a table.

Benefits
1. Triggers provide a powerful way to control how action queries modify the data in our
database
2. Help secure the integrity of data by preventing unauthorized or inconsistent changes to
be made

Creating triggers:

Syntax:
Create trigger triggername
On tablename
For
Delete, insert, update
As
Sql statement

Example:
Create table stu6 (sno int, sname varchar (20), salary int)

Insert into stu6 values (1,'a', 2000)


Insert into stu6 values (2,'b', 3000)
Insert into stu6 values (3,'c', 4000)
Insert into stu6 values (4,'d', 5000)
Select * from stu6

Example for insertion:


Create trigger forins
on stu6
For insert
As declare @a int
Select @a=salary from inserted
If (@a>15000)
Begin
Print' you should give a salary with less than 15000'
Rollback tran
End

Insert into stu6 values (6,'f', 20000)

Example for deletion:


Create trigger fordel
on stu6
For delete
As declare @a int
Select @a=sno from deleted
If (@a=5)
Begin
Print'cannot delete the record no 5'
Rollback tran
End

Select * from stu6

Delete from stu6 where sno=5

Example for updating:


Create trigger forupd
on stu6
For update
As declare @a int, @b int
Select @a=salary from deleted
Select @b=salary from inserted
If (abs (@a-@b)>500)
Begin
Print 'cannot increment or decrement the record'
Rollback tran
End

Select * from stu6


Update stu6 set salary=6000 where sno=4

Droping the trigger:

Syntax:
drop trigger triggername

Example:
drop trigger forins

Chapter -5
Cursors:
Most of the operations we performed in sql server are set-oriented-the operation
works with an entire set at a time.
A cursor lets us retrieve data from a result set one row at a time-row oriented operation.
We use a cursor to identity the row we want to retrieve from the result set.

The sql statements for cursor processing:

Declare defines a cursor


Open open and populates the cursor by executing the select statement defined by the
cursor.
Fetch retrieves a row from the cursor
Close close the cursor
Deallocate deletes the cursor definition and releases all system resources associated with
cursor

Declaring a cursor:

Syntax:
Declare cursorname cursor
For
Select statement

Example:
Declare cur_prod cursor static
For
Select sno, sname from stu1

Opening a cursor:
The open statement opens a cursor. After a cursor has been opened, use the global
variable. @@cursor_rows to determine the number of qualifying rows in the last opened
cursor.

Syntax:
Open cursor_name

Example:
Open cur_prod

Fetching information from a cursor:

Syntax:
Fetch next |prior |first |last |absolute n |relative n | from cursorname

Example:
Fetch next from cur_prod --->retrieves the next record
Fetch prior from cur_prod --->retrieves the previous row
Fetch first from cur_prod --->retrieves the first record in the table
Fetch last from cur_prod --->retrieves the last record in the table
Fetch absolute 2 from cur_prod --->retrieves absolutely the 2nd rows
Fetch relative 3 from cur_prod --->retrieves relative of 3rd record

Closing a cursor:
The close statement releases any memory being used for buffering.

Syntax:
Close cursorname

Example:
Close cur_prod

Removing a cursor:

Syntax:
Deallocate cursorname

Example:
Deallocate cur_prod
Chapter-6
Transaction processing:
Whenever a request to modify the database is received, a copy of both old and new
states of database affected portion in transaction log. These changes are recorded in a
transaction log before they are made to the database itself.

Begin transaction:
Marks the starting point of a transaction.

Commit transaction:
Marks the end of a transaction and makes the changes within the transaction a
permanent part of the database.

Rollback transaction:
Rolls back a transaction to the starting point or to the specified point

Save transaction:
Sets a new save point within a transaction. the save point defines a location to
which a transaction can return if part of transaction is conditionally cancelled.

Example:
Create table stu7 (sno int, sname varchar (20), salary int)
Insert into stu7 values (1,'a', 200)
Insert into stu7 values (1,'a', 200)
Insert into stu7 values (1,'a', 200)
Insert into stu7 values (2,'b', 300)
Insert into stu7 values (3,'c', 400)
Insert into stu7 values (4,'d', 500)
Insert into stu7 values (5,'e', 600)
Select * from stu7

Delete stu7 where sno=1


If @@rowcount >1
Begin
Rollback tran
Print 'more than one emp with this empid'
Print 'deletion cancel'
End
Else
Begin
Commit tran
Print 'deletion successfully'
End

Example.2:
Begin tran
Delete stu7 where sno=1
Save tran e1
Delete stu7 where sno=2
Save tran e2
Select * from stu7
Rollback tran e2
Select * from stu7
Rollback tran e1
Select * from stu7

Chapter-7

Microsoft sql server provides two methods for obtaining metadata.


They are
1. System stored procedures
2. Information schema views

1. System Stored Procedures:

1. To report information about a specified database or all database

Syntax:
Sp_helpdb databasename

Example:
Sp_helpdb anbu

2. To report information about a database object

Syntax:
Sp_help objectname

Example:
Sp_help stu1

3. To return the type or types of trigger defined on the specified table

Syntax:
Sp_helptrigger tablename

Example:
Sp_helptrigger stu6

4. To print the text of a rule,a default,stored procedure,trigger,view

Syntax:
Sp_helptext objectname

Example:
Sp_helptext forins

Note:forins is a trigger name

5. Reports information about sql server users.

Syntax:
Sp_helpuser username

Example:
Exec sp_helpuser

6. To show all constraint for the specified table

Syntax:
Sp_helpconstraint tablename

Example:
Sp_helpconstraint emp4
Sp_helpconstraint emp5
Sp_helpconstraint emp6
Sp_helpconstraint emp7

7. To report information about the indexes on a table

Syntax:
Sp_helpindex tablename

Example:
Sp_helpindex stu1

8. To list all tables in a database


Syntax:
Sp_tables

Example:
Exec sp_tables

9. To change the name of a database object (table, column, view, trigger, stored procedure,
database...etc)
In the current database
Syntax:
Sp_rename object name, new name

Example:
Exec sp_rename 'stu','stu1'

10. To return a list of stored procedure in the current database

Syntax:
Sp_stored_procedures

Example:
Exec sp_stored_procedures

11. To create an user-defined datatype

Syntax:
Sp_addtype typename, datatype, null |not null

Example:
Exec sp_addtype birthday, int, 'null'

12. To drop an user-defined datatype

Syntax:
Sp_droptype typename

Example:
Exec sp_droptype 'birthday'

2. Information Schema Views:

1. To view the list of tables in a database.

Example:
Select * from information_schema. tables

2. To view the list of constraints defined in a database

Example:
Select * from information_schema.table_constraints

3. To report list of views defined by a user in the current database.

Example:
Select * from information_schema. views

System tables:
The information used by Microsoft sql server and its components are stored in special
tables knows as system tables. System tables should not be altered directly by any user.

1. sysdatabase
2. sysobjects
3. sysconstraints
4. syscolumns
5. sysusers
6. sysindexes

Example:
Select * from sysdatabases
Select * from sysobjects
Select * from sysconstraints
Select * from syscolumns
Select * from sysusers
Select * from sysindexes
=================================================================