Query
Query
************************************************************************************************
// Set Primary key with ALTER TABLE COMMAND
**********************************************************************************************
// Create A Table with a Primary key
*********************************************************************************************
// Set Referencial Integrity [ Joining two tables ]
*********************************************************************************************
// Create a table with primary key and foreign key
***********************************************************************************************
// Droping a Constraint
*************************************************************************************************
// Droping a Column in a Table
***********************************************************************************************
// Create a Table with default value
ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );
*****************************************************************************************
// Disabling Check constraint
******************************************************************************************
// Create a new table and copy only some particular fields of another Table
******************************************************************************************
//Create A Table and copy the data from another Table
******************************************************************************************
select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’
*********************************************************************************************
Grouping:
______________________________________________________________________________________
select type, sum(type) from titles; // Error
// Rule:
When ever you have aggregate function in the select list
along with some other fileds which are not enclosed with aggregate functions.
you should use group by functions.
_________________________________________________________________________________________
select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id d
sp_help titles
******************************************************************************************
// Select keywords
SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]
******************************************************************************************
SELECT *
FROM TITLES
ORDER BY TYPE DESC;
//////////////////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
group by type
order by title_id;
When ever use an order by class along with group by class the order by class should have
only those filels which are present in the group by class.
/////////////////////////////////////////////////////////////////////////////////////////////
select type,title_id,sum(price)
from titles
group by type
order by title_id; // Error
select type,title_id,sum(price)
from titles
group by type,title_id
order by title_id;
select sum(price)
from titles ; order by titles
3
select sum(price)
from titles
Query - Page #4
***********************************************************************
select type, count(*) from titles group by type having count(*)=3;
***********************************************************************
December 21 2001:
-----------------
Compute By class:
select type,price
from titles
order by type
compute sum(price) by type;
Whenever we use group by class or compute by class, the sql server builds Work Table....
In compute by class not able to generate Work Table automatically..but Group by class itself
able to generate Work Table...So the Compute by class relay order by class...
select type,price
from titles
order by pub_id
compute sum(price) by type; // Error
Reason:
The work table is built based on pub_id...In that work Table,we can’t find the sum of
price by Type...’
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type;
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by pub_id; // Error
Reason:
Work Table
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type,pub_id;
select type,pub_id,title_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id,title_id;
select type,pub_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id;
****************************************************
Afternoon:21-dec-2001
2...select type,pub_id
from titles
group by type,pub_id;
select type,pub_id
from titles
group by type,pub_id;
// In the above query.. The Distinct applies both type and pub_id columns..We can not make to apply
for a particular column. It will apply all the columns in the select list
For Ex
Business p1 200
Business p1 400
Business p1 300
Computer p2 500
Computer p2 700
The Result is
Business p1 200
Computer p2 500
/////////////////////////////////////////////////
select type,sum(price),avg(price)
from titles
group by price; // Error
Reason:
The field name in group by clause which is not used in aggregate function in select list
//////////////////////////////////////////////////////////
Having: 5
Having clause should have group by class...but when using group by class it is optional
to use Having clause.
Query - Page #6
1..select type,sum(price)
from titles
group by type
having type=’business’; // Grouped and followed by Filtered.......
2..select type,sum(price)
from titles
where type=’business’
group by type; // More Optimized: Fileterd and followed by Grouped...
All types of Records like Business,Computer and Novel and then take Business Records are Filtered
///////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select type,sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
/////////////////////////////////////////////////////////////////////////////////////////////////
December-26-2001
Joins:
if the select statement contains more table in from clause without where clause, it is called
cross joining which is never used...
6
select authors.au_id,authors.au_lname,authors.phone,
publishers.pub_id,publishers.pub_name,publishers.city
from authors,publishers
where authors.city = publishers.city;
select authors.*,pub_id,pub_name
from authors,publishers
where authors.city = publishers.city; // authors.* displays all fields in the Authors Table
Natural join:
The redundat field names are eliminated in the Result set
join
Equi Join :
The Redundat field names are present in the result set.
Table Alias:
select p.*,au_id,au_lname
from authors a, publishers p
where a.city = p.city and a.au_lname like ’c%’
select p.*,au_id,au_lname
from authors a, publishers p
where au_lname like ’c%’ and a.city = p.city
Question:
Find the publisher name for the book written by the author with fname ’Lorsley’
Answer:
select p.pub_name
from publishers p,authors a,titles t,titleauthor ta
where a.au_lname = ’Locksley’ and
a.au_id = ta.au_id and
ta.title_id = t.title_id and
t.pub_id = p.pub_id;
December 27 2001:
.................
Explanation:
Title: Authors
7
au_id au_lname
----------- ----------------------------
a1 lockley
Query - Page #8
a2 peter
Table: Publisher
pub_id pub_name
------ -----------
p1 samy
p2 golgotia
p3 samba
Table: Titles
title_id pub_id
-------- --------
t1 p1
t2 p2
t3 p3
Table: TitleAuthor
au_id title_id
----------- --------
a1 t1
a1 t2
a2 t1
a2 t3
Virtual Tables:
[Authors] [TitleAuthor]
aid aname au_id title_id
a1 lockey a1 t1
a1 lockey a1 t2
FAQ:
Ans: The Query optimizer find out which join will be evaluated first and run the query
in the optimized way....
Cross Checking: 8
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
December 28 2001:
.................................................................................................
Self Join:
The Table joins with itself...
Rule:
’When use self join in the where condition, you shoud use the in-equility condition
of the primary keys’
................................................................................................
Question:
Find the name of the authors who lives in the same city...
Explanation:
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
A1
A6
A2
A3
select a.au_id,a.city
from authors a, authors b
where a.city = b.city; // It displays duplicate Records
select state,count(*)
from authors 9
group by state
having count(*)>1 // We should not use group by function in the self joining situations
Query - Page #10
Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Question: Find the author id who has written more than one book???
Question: Find the title_id which has been written by more than one author?
Question: Find the author Names who has written more than one book???
Question: Find the titles which has been written by more than one author?
/////////////////////////////////////////////////////////////////////////////////////////////////
Jan 02 2002:
Outer join:
emp
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Anderw SYS
e5 Lafer null
dep
emp
eno
ename
d_id
dept
ddid
dname
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
e5 lafer
////////////////////////////////////////////////////////////////////////////////////////////
Query - Page #12
///////////////////////////////////////////////////////////////////////////////////////////////
Sub Query:
A query with in query is called sub query...
Note: All joins can be formulated with sub query but all sub query can not be
formulated with joins
Question : Find the name and title of the most expensive book???
declare @p float;
select @p = max(price) from titles;
select @p;
select * from titles where price = @p;
Jan-04-2002:
Exists:
Rule: Exsits has the rule that no filed name in the where clause.
...............................................................................................
Simple Query: All the select statements are evaluated in the bottom up.
Correlated SubQuery:
1. The Correlated subquery will always have the join inside..[but just because
the join inside the subquery it does not make correlated subquery.]
Example:
select cid from orders where customers.id=orders.id, This query will return olny true or false.
The inner query is executed as many times the outer query depends....it means that the inner
query depends the value of outer query...
--------------------------------------------------------------------------------------------------------
Query - Page #13
7-01-2002:
Any self join can be carried out through correlated sub query.
select a.au_fname
from authors a
where exists ( select b.au_id
from authors b
where a.state = b.state and
a.au_id <> b.au_id ); // This is correlated sub query 1.It has join.
2.The left or right side field name is oute
The correlated sub query executed for every outer table row...but simple sub query executed only once...
It takes one record from the outer condition for that row all the rows of the inner codition will be exec
If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct
the correlated sub query.
---------------------------------------------------------------------------------------------------------
Union:
select * from authors union select * from sen_temp_table; // It will not give the duplicates of the re
if u want to include the duplicates use Union all keyword...
select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ
select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mis
Note: The order by statements can not be used in the individual query inside
the union but group by and having is allowed.
But order by allowed in the outside of the union .
Example:
select title_id,title from titles union all select title_id,au_id from titleauthor o
Note: The field name in the first select statement is allowed in the order by clause.
we can not use group by clause in the order by place....
---------------------------------------------------------------------------------------------------------
Self-Interest:
Ans:
drop vi
create view v_sample as
select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p
where o.proid=p.pid group by o.cuid
Ans: 13
select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p
where o.proid=p.pid group by o.cuid;
Query - Page #14
---------------------------------------------------------------------------------------------------------
11-01-2002:
Syntax:
Grant select|update|insert|delete on Table_name to User
Grant All Table_name to User
Revoke select|update|insert|delete on Table_name from User
Revoke All Table_name from User
View:
The View is the Projection of the base tables...
Syntax:
Create View view_name
as
select statement
Step 1:
create view sen_view_v1
as
select * from titles where title_id=’BU1111’
Step 2:
select * from sen_view_v1; // The select statement inside the view will be executed....
delete sen_view_v1;
*************************************************************************************************
16-January-2002:
Ex:
create view v1 as
select.....
Create view v2 as
select pub_id,sum(price) from titles group by pub_id; // The above statement would not work.
Here the sum(price) is tried to derive a new column in the view
create view v2 as
select pub_id,sum(price) as "Total" from titles group by pub_id
(or)
create view v2(publishers_id,price) as
select pub_id,sum(price) as "Total" from titles group by pub_id
//////////////////////////////////////////////////////////////////////////////////////////////
Rule:
1. We can not use order by,compute by,compute14in the selection list while creating views.
2. We can not use ’Select into’ on views.
3. We can use order by indirectly.
//////////////////////////////////////////////////////////////////////////////////////////////
Query - Page #15
create view v1 as
select emp_no,emp_name,dept_id,phone from emp; // It would not work...
create view v1 as
select * form emp; // It will work
Rule 1:
The view has to contain all not null columns,[it will become updateable view] then olny
it is possible insert,update,delete, If the view does not contain all not null columns,
it is only readable veiw.We can not do insert,delete,update...
Rule 2:
If the select list in the view contains aggregate functions,the view is readable view...
create view v1 as
select emp_no,emp_name,emp.dept_id,phone,salary,dept_name from emp,dept
where emp.dept_id=dept.dept_id;
Rule 3:
In above statement, the insert is possible only if all the columns are in the same table
in the insert statememt. The insert will not work the columns are in different table...
////////////////////////////////////////////////////////////////////////////////////////////////
select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS
find whether it is table or view...if it is view, it executes the select statement with where
condition. And the statement looks like below....
Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpreted
as below....
Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....
insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view has
been created by with check option condition. It allow only the where clause condition is match, it
means that we can insert only ’HRD’ type......
/////////////////////////////////////////////////////////////////////////////////////////////////
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
17-January-2002:
Transact-SQL:
Transact-SQL is procedure oriented language
Stored Procedure:
Batch of sql statemets kept compiled in the server and ready for the execution.
In stored procedure,the return statement can return only int value,but we can return more
than one value by using output parameter concept.
Whatever variable used in sql server, these variable should begin with @ symbol. By default,
all parameters are input parameters.All system defined procedure is preceeded with sp...
The created procedure have an entry in sysobjects table.....The statements are used in procedure
will be stored in syscomments table.
Exec pro // while creating procudure, it checks only the syntax, while executing, the compilation
process is done..
select object_id (’demo’); // we can get the table id what the sql server maintains...
//////////////////////////////////////////////////////////////////////////////////////////////
what is Query plan????
The query plan is nothing but the path of the execution in the sql statements...
Exec pro;
The step 1 and step 2 will be executed at the first execution of the procedure..if u execute
the procedure another time, it will no go for compilation process,it just checks the procedure
cache and execute suitable obj file....If the system is gone for shut down, the contents of the
procedure cache will be deleted....Whatever changes made in table contents, it will re-complile.
if the table is dropped,the procedure for the table will not be deleted...
16
//////////////////////////////////////////////////////////////////////////////////////////////
18-January-2002:
Query - Page #17
if(@price <=100)
return 1;
if(@price>100 and @price<=200)
return 2;
if(@price >200)
return 3;
-------------------------------------
if @ret = 2
begin
select "Return 2";
end
if @ret = 3
begin
select "Return 3";
end
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Example:
Example
end
select @ret
/////////////////////////////////////////////////////////////////////////////////////////////////
19-01-2002:
Output Parameters:
Question: Write the procedure to find the city and state of the given publishers????
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names ( use while loop )
------------------------------------------------------------------------------------------------
Goto Statement Example:
21-January-2002:
E-R Diagram:
Entity:
The entity is an object about information can be recorded..
For example, the employee and dept entity has some relationship between them...
{Chen notation}
Employee has one to one relationship with Dept ( one employee has to work in only one dept)
Dept has one to many relationship with Employee ( one dept has many employees)
so we depict one to many relationship with these two entites....( one to one[left to right] and
one to many[right to left] realationship comes either side,Take a one to many relationship...)
For ex:
1.(emp)one instance of employee has how many instances of dept...(0,1){(min,max)}
(dept)one instance of dept has how many instances of employee...(0,M)
emp has a existence dependent with dept ( dept has to created before emp...)
Existence Dependent: It means that with out having a entry in dept table,the emp id can not
have an dept id ( Foreign key rules apply here..)
One professor can guide many students...[one to many relationship in left to right] in some
cases the one professor not giving guidence to any students....
One Student can get advise from one professor [one to one relationship in right to left]
one professor can have zero or one room [ one to one left to rigth ]
one room is allotted to zero or one professor [ one to one right to left ]
one theatre can show many films [ one to Many left to rigth ]
one film is shown in many theatres [ one to Many right to left ]
The oracle and sql server can not support for many to many relationship....For these cases
we have to split the relationship into two one to many relationship...
one author can write many books [ one to Many left to rigth ]
one title is written by many authors [ one to Many right to left ]
-------------------------------------------------------------------------------------------------
Note: The calculated field(derived attribute) should not be stored in the database..For example
the age can be calculated with date-of-birth.....
-------------------------------------------------------------------------------------------------
25-jan-2002:
Normalization:
Segregating tables as to avoid redundancy...
DeNormalization:
introducing redundancy into tables to make more optimization or more performance the
Any database desin normally will not go beyond the third normal form....
Atomic values:
A field should record about the single attribute...
For example: To store address,we have to put street,city,state,country as a separate field names.
Then only possible to search the employees by city,state or country.....
(*) The field names shoud accept null values, if the no specefic info for that recor
and take to consideration the table should not have more null value fields.
Example:
---------------------------------------------------------------------------------------------------------
All the non key attributes should depend upon whole primary key or all the non key attributes
may depend on other non key attributes...
In the above table, the department id is partially belonging to the primary key,which means that the emp
itself only need to identify the department id and the project id is no longer needed...
*In order conform second normal form,we have take out the non key attribute which does not depend entril
the primary key and put it separate table along with the field on which the non key attribute is depen
eid did
---------
e1 IS
e2 IS
e3 NET
24 NET 20
nohrs is partially depend on primary key,which means the nohrs dependent on only project id...
Query - Page #21
pid nohrs
-----------
p1 20
p2 30 ( It is in third normal form,we can not split it again)
The dehead is not related to eid or pid...it is related to did.....so put dhead following table
---------------------------------------------------------------------------------------------------------
Third Normal Form:
All the non key attributes should be dependent only on the primary key
In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only th
did which is not a primary key of the table....
did dhead
--------------
IS boris
NET peter
---------------------------------------------------------------------------------------------------------
*************************************************************************************************
29-jan-2002:
Triggers:
Trigger is a stored procedure, it will be invoked automatically upon user action
(Insert,Update,Delete).
Cascade deletions:
The child table refers some field in the master table...We can not delete
any enty in the master table,which is refered by in the child table...The SQL server maintains
restrictions automatically...The cascade deletions is opposite of these restrictions....
Syntax:
The trigger can be depend on only one table...and the trigger can not defined on the views...
only three types of triggers ( Insert Trigger,Update Trigger,Delete Trigger) These are all after
trigger,The SQL could not support Before Triggers.....
Book Magazine
----------------------------
Bid Magid 21
Bname Mname
Author price
Query - Page #22
Transaction
--------------
Tid
Card_id
book_id
issue_date
return_date
--------------------------------------------------------------------------------------------------
Implementing primary key constraint:-
emp inserted
----------------------------------------------------
e1 boris d1 d1 HRD
e2 becker d2 d2 SYS
e3 sapeg d3
-------------------------------------------------------------------------------------------------
Implementing foreign key constraint:-
-------------------------------------------------------------------------------------------------
Note:
While creating trigger,the object should be exist on which the trigger imposed...but it
does not check the body of the statements.... 22
-------------------------------------------------------------------------------------------------
Implementing Cascade Deletion:-
Query - Page #23
The value from Trigger table is moved into Trigger Test Table (Deleted Table)
-------------------------------------------------------------------------------------------------
Implementing Restriction on deletion:-
------------------------------------------------------------------------------------------------
Question:
Create a trigger to move the deleted records to that respective back_up tables?????
Hits provided:
declare @i int
select @i=Object_id(’publishers’)
------------------------------------------------------------------------------------------------
31-JAN-2002:
-------------------------------------------------------------------------------------------
Note: The rollback command will only work on triggers it will not work on procedures....
--------------------------------------------------------------------------------------------
23
Note: Through the delete and update command will affect many rows.., the trigger will be
executed for each row...
---------------------------------------------------------------------------------------------
create trigger tri
Query - Page #24
on invoice
for update
if update(oid) // if the user tries to update field oid it will return true
begin or it will retun false
rollback
return
end
if not exists (select * from products,inserted
where inserted.productid=products.proudctid
begin
print ’Fk violation on products’
rollback
return
end
--------------------------------------------------------------------------------------------
Note: For update triggers, the inserted and deleted virutal table will be created....
deleted followed by inserted...................
--------------------------------------------------------------------------------------------
TSQL Cursors:
The main application of cursors is ’report’ generation..........
1....Declare
2....Open
3....Fetch
4....Close
5....Deallocate
A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’..
1...Declare:
Syntax:
Declare cursorname cursor
for
select statement
Note: It check the existence of the object but it would not compile and execute
-------------------------------------------------------------------------------------------------
2...Open:
Open cur; // Opening a cursor
Note: The select statement is executed and the resultset is stored inside the memory
-------------------------------------------------------------------------------------------------
3....Fetch:
Fetch next from cur;
Fetch prior from cur;
Fetch first from cur;
Fetch last from cur;
Note: It goes and bring the records one by one from the resultset which is stored in the memory
The logical pointer is pointed bof at first time....
-------------------------------------------------------------------------------------------------
4.....Close:
Close cur;
exec sen_cur_pro;
Note: @@fetch_status is system defined global variable which is automatically set to 0 which
indicates for successful fetch...
------------------------------------------------------------------------------------------------
1-02-2002:
Application of Cursors:
exec sen_cpro
Note: The Compute by clause should not be used in the select stattement along with cursor....
The Compute by clause should not be used in the select stattement along with subquery...
We can use order by and group by clause in the select statement along with cursor......
------------------------------------------------------------------------------------------------
Question : Write the procedure to display all book which is published by each publisher in neat format???
close tcur
deallocate tcur
end
print ’------------------------------------------------’
fetch next from cur into @pid,@pname
end
close cur
deallocate cur
exec sen_publisher_books
---------------------------------------------------------------------------------------------------------
2-Feb-2002:
Indexing:
It is a sorting process to reduce the searching process time....
Syntax:
The field on which indexed is sorted in ascending order and build binary tree....
It take the first value and any middle arbitary value
------------------------------------------------------------------------------------------------
Note: Through the index is created, the optimizer will decide wheter to use index is feasible or
it is feasible for going for table scan......
--------------------------------------------------------------------------------------------------
Note: Primary key creates Clustered automaically but to make it nonClustered index is more
feasible than Clustered index
--------------------------------------------------------------------------------------------
Clustered:
-----------------------------------------------------------------------------------------------
Note: The clustered index points the page...but the nonclustered index points the exact match of
record...
26
Query - Page #1
************************************************************************************************
// Set Primary key with ALTER TABLE COMMAND
**********************************************************************************************
// Create A Table with a Primary key
*********************************************************************************************
// Set Referencial Integrity [ Joining two tables ]
*********************************************************************************************
// Create a table with primary key and foreign key
***********************************************************************************************
// Droping a Constraint
*************************************************************************************************
// Droping a Column in a Table
***********************************************************************************************
// Create a Table with default value
ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );
*****************************************************************************************
// Disabling Check constraint
******************************************************************************************
// Create a new table and copy only some particular fields of another Table
******************************************************************************************
//Create A Table and copy the data from another Table
******************************************************************************************
select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’
*********************************************************************************************
Grouping:
______________________________________________________________________________________
select type, sum(type) from titles; // Error
// Rule:
When ever you have aggregate function in the select list
along with some other fileds which are not enclosed with aggregate functions.
you should use group by functions.
_________________________________________________________________________________________
select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id d
sp_help titles
******************************************************************************************
// Select keywords
SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]
******************************************************************************************
SELECT *
FROM TITLES
ORDER BY TYPE DESC;
//////////////////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
group by type
order by title_id;
When ever use an order by class along with group by class the order by class should have
only those filels which are present in the group by class.
/////////////////////////////////////////////////////////////////////////////////////////////
select type,title_id,sum(price)
from titles
group by type
order by title_id; // Error
select type,title_id,sum(price)
from titles
group by type,title_id
order by title_id;
select sum(price)
from titles ; order by titles
29
select sum(price)
from titles
Query - Page #4
***********************************************************************
select type, count(*) from titles group by type having count(*)=3;
***********************************************************************
December 21 2001:
-----------------
Compute By class:
select type,price
from titles
order by type
compute sum(price) by type;
Whenever we use group by class or compute by class, the sql server builds Work Table....
In compute by class not able to generate Work Table automatically..but Group by class itself
able to generate Work Table...So the Compute by class relay order by class...
select type,price
from titles
order by pub_id
compute sum(price) by type; // Error
Reason:
The work table is built based on pub_id...In that work Table,we can’t find the sum of
price by Type...’
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type;
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by pub_id; // Error
Reason:
Work Table
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type,pub_id;
select type,pub_id,title_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id,title_id;
select type,pub_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id;
****************************************************
Afternoon:21-dec-2001
2...select type,pub_id
from titles
group by type,pub_id;
select type,pub_id
from titles
group by type,pub_id;
// In the above query.. The Distinct applies both type and pub_id columns..We can not make to apply
for a particular column. It will apply all the columns in the select list
For Ex
Business p1 200
Business p1 400
Business p1 300
Computer p2 500
Computer p2 700
The Result is
Business p1 200
Computer p2 500
/////////////////////////////////////////////////
select type,sum(price),avg(price)
from titles
group by price; // Error
Reason:
The field name in group by clause which is not used in aggregate function in select list
//////////////////////////////////////////////////////////
Having: 31
Having clause should have group by class...but when using group by class it is optional
to use Having clause.
Query - Page #6
1..select type,sum(price)
from titles
group by type
having type=’business’; // Grouped and followed by Filtered.......
2..select type,sum(price)
from titles
where type=’business’
group by type; // More Optimized: Fileterd and followed by Grouped...
All types of Records like Business,Computer and Novel and then take Business Records are Filtered
///////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select type,sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
/////////////////////////////////////////////////////////////////////////////////////////////////
December-26-2001
Joins:
if the select statement contains more table in from clause without where clause, it is called
cross joining which is never used...
32
select authors.au_id,authors.au_lname,authors.phone,
publishers.pub_id,publishers.pub_name,publishers.city
from authors,publishers
where authors.city = publishers.city;
select authors.*,pub_id,pub_name
from authors,publishers
where authors.city = publishers.city; // authors.* displays all fields in the Authors Table
Natural join:
The redundat field names are eliminated in the Result set
join
Equi Join :
The Redundat field names are present in the result set.
Table Alias:
select p.*,au_id,au_lname
from authors a, publishers p
where a.city = p.city and a.au_lname like ’c%’
select p.*,au_id,au_lname
from authors a, publishers p
where au_lname like ’c%’ and a.city = p.city
Question:
Find the publisher name for the book written by the author with fname ’Lorsley’
Answer:
select p.pub_name
from publishers p,authors a,titles t,titleauthor ta
where a.au_lname = ’Locksley’ and
a.au_id = ta.au_id and
ta.title_id = t.title_id and
t.pub_id = p.pub_id;
December 27 2001:
.................
Explanation:
Title: Authors
33
au_id au_lname
----------- ----------------------------
a1 lockley
Query - Page #8
a2 peter
Table: Publisher
pub_id pub_name
------ -----------
p1 samy
p2 golgotia
p3 samba
Table: Titles
title_id pub_id
-------- --------
t1 p1
t2 p2
t3 p3
Table: TitleAuthor
au_id title_id
----------- --------
a1 t1
a1 t2
a2 t1
a2 t3
Virtual Tables:
[Authors] [TitleAuthor]
aid aname au_id title_id
a1 lockey a1 t1
a1 lockey a1 t2
FAQ:
Ans: The Query optimizer find out which join will be evaluated first and run the query
in the optimized way....
Cross Checking: 34
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
December 28 2001:
.................................................................................................
Self Join:
The Table joins with itself...
Rule:
’When use self join in the where condition, you shoud use the in-equility condition
of the primary keys’
................................................................................................
Question:
Find the name of the authors who lives in the same city...
Explanation:
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
A1
A6
A2
A3
select a.au_id,a.city
from authors a, authors b
where a.city = b.city; // It displays duplicate Records
select state,count(*)
from authors 35
group by state
having count(*)>1 // We should not use group by function in the self joining situations
Query - Page #10
Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Question: Find the author id who has written more than one book???
Question: Find the title_id which has been written by more than one author?
Question: Find the author Names who has written more than one book???
Question: Find the titles which has been written by more than one author?
/////////////////////////////////////////////////////////////////////////////////////////////////
Jan 02 2002:
Outer join:
emp
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Anderw SYS
e5 Lafer null
dep
emp
eno
ename
d_id
dept
ddid
dname
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
e5 lafer
////////////////////////////////////////////////////////////////////////////////////////////
Query - Page #12
///////////////////////////////////////////////////////////////////////////////////////////////
Sub Query:
A query with in query is called sub query...
Note: All joins can be formulated with sub query but all sub query can not be
formulated with joins
Question : Find the name and title of the most expensive book???
declare @p float;
select @p = max(price) from titles;
select @p;
select * from titles where price = @p;
Jan-04-2002:
Exists:
Rule: Exsits has the rule that no filed name in the where clause.
...............................................................................................
Simple Query: All the select statements are evaluated in the bottom up.
Correlated SubQuery:
1. The Correlated subquery will always have the join inside..[but just because
the join inside the subquery it does not make correlated subquery.]
Example:
select cid from orders where customers.id=orders.id, This query will return olny true or false.
The inner query is executed as many times the outer query depends....it means that the inner
query depends the value of outer query...
--------------------------------------------------------------------------------------------------------
Query - Page #13
7-01-2002:
Any self join can be carried out through correlated sub query.
select a.au_fname
from authors a
where exists ( select b.au_id
from authors b
where a.state = b.state and
a.au_id <> b.au_id ); // This is correlated sub query 1.It has join.
2.The left or right side field name is oute
The correlated sub query executed for every outer table row...but simple sub query executed only once...
It takes one record from the outer condition for that row all the rows of the inner codition will be exec
If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct
the correlated sub query.
---------------------------------------------------------------------------------------------------------
Union:
select * from authors union select * from sen_temp_table; // It will not give the duplicates of the re
if u want to include the duplicates use Union all keyword...
select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ
select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mis
Note: The order by statements can not be used in the individual query inside
the union but group by and having is allowed.
But order by allowed in the outside of the union .
Example:
select title_id,title from titles union all select title_id,au_id from titleauthor o
Note: The field name in the first select statement is allowed in the order by clause.
we can not use group by clause in the order by place....
---------------------------------------------------------------------------------------------------------
Self-Interest:
Ans:
drop vi
create view v_sample as
select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p
where o.proid=p.pid group by o.cuid
Ans: 39
select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p
where o.proid=p.pid group by o.cuid;
Query - Page #14
---------------------------------------------------------------------------------------------------------
11-01-2002:
Syntax:
Grant select|update|insert|delete on Table_name to User
Grant All Table_name to User
Revoke select|update|insert|delete on Table_name from User
Revoke All Table_name from User
View:
The View is the Projection of the base tables...
Syntax:
Create View view_name
as
select statement
Step 1:
create view sen_view_v1
as
select * from titles where title_id=’BU1111’
Step 2:
select * from sen_view_v1; // The select statement inside the view will be executed....
delete sen_view_v1;
*************************************************************************************************
16-January-2002:
Ex:
create view v1 as
select.....
Create view v2 as
select pub_id,sum(price) from titles group by pub_id; // The above statement would not work.
Here the sum(price) is tried to derive a new column in the view
create view v2 as
select pub_id,sum(price) as "Total" from titles group by pub_id
(or)
create view v2(publishers_id,price) as
select pub_id,sum(price) as "Total" from titles group by pub_id
//////////////////////////////////////////////////////////////////////////////////////////////
Rule:
1. We can not use order by,compute by,compute40in the selection list while creating views.
2. We can not use ’Select into’ on views.
3. We can use order by indirectly.
//////////////////////////////////////////////////////////////////////////////////////////////
Query - Page #15
create view v1 as
select emp_no,emp_name,dept_id,phone from emp; // It would not work...
create view v1 as
select * form emp; // It will work
Rule 1:
The view has to contain all not null columns,[it will become updateable view] then olny
it is possible insert,update,delete, If the view does not contain all not null columns,
it is only readable veiw.We can not do insert,delete,update...
Rule 2:
If the select list in the view contains aggregate functions,the view is readable view...
create view v1 as
select emp_no,emp_name,emp.dept_id,phone,salary,dept_name from emp,dept
where emp.dept_id=dept.dept_id;
Rule 3:
In above statement, the insert is possible only if all the columns are in the same table
in the insert statememt. The insert will not work the columns are in different table...
////////////////////////////////////////////////////////////////////////////////////////////////
select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS
find whether it is table or view...if it is view, it executes the select statement with where
condition. And the statement looks like below....
Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpreted
as below....
Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....
insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view has
been created by with check option condition. It allow only the where clause condition is match, it
means that we can insert only ’HRD’ type......
/////////////////////////////////////////////////////////////////////////////////////////////////
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
17-January-2002:
Transact-SQL:
Transact-SQL is procedure oriented language
Stored Procedure:
Batch of sql statemets kept compiled in the server and ready for the execution.
In stored procedure,the return statement can return only int value,but we can return more
than one value by using output parameter concept.
Whatever variable used in sql server, these variable should begin with @ symbol. By default,
all parameters are input parameters.All system defined procedure is preceeded with sp...
The created procedure have an entry in sysobjects table.....The statements are used in procedure
will be stored in syscomments table.
Exec pro // while creating procudure, it checks only the syntax, while executing, the compilation
process is done..
select object_id (’demo’); // we can get the table id what the sql server maintains...
//////////////////////////////////////////////////////////////////////////////////////////////
what is Query plan????
The query plan is nothing but the path of the execution in the sql statements...
Exec pro;
The step 1 and step 2 will be executed at the first execution of the procedure..if u execute
the procedure another time, it will no go for compilation process,it just checks the procedure
cache and execute suitable obj file....If the system is gone for shut down, the contents of the
procedure cache will be deleted....Whatever changes made in table contents, it will re-complile.
if the table is dropped,the procedure for the table will not be deleted...
42
//////////////////////////////////////////////////////////////////////////////////////////////
18-January-2002:
Query - Page #17
if(@price <=100)
return 1;
if(@price>100 and @price<=200)
return 2;
if(@price >200)
return 3;
-------------------------------------
if @ret = 2
begin
select "Return 2";
end
if @ret = 3
begin
select "Return 3";
end
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Example:
Example
end
select @ret
/////////////////////////////////////////////////////////////////////////////////////////////////
19-01-2002:
Output Parameters:
Question: Write the procedure to find the city and state of the given publishers????
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names ( use while loop )
------------------------------------------------------------------------------------------------
Goto Statement Example:
21-January-2002:
E-R Diagram:
Entity:
The entity is an object about information can be recorded..
For example, the employee and dept entity has some relationship between them...
{Chen notation}
Employee has one to one relationship with Dept ( one employee has to work in only one dept)
Dept has one to many relationship with Employee ( one dept has many employees)
so we depict one to many relationship with these two entites....( one to one[left to right] and
one to many[right to left] realationship comes either side,Take a one to many relationship...)
For ex:
1.(emp)one instance of employee has how many instances of dept...(0,1){(min,max)}
(dept)one instance of dept has how many instances of employee...(0,M)
emp has a existence dependent with dept ( dept has to created before emp...)
Existence Dependent: It means that with out having a entry in dept table,the emp id can not
have an dept id ( Foreign key rules apply here..)
One professor can guide many students...[one to many relationship in left to right] in some
cases the one professor not giving guidence to any students....
One Student can get advise from one professor [one to one relationship in right to left]
one professor can have zero or one room [ one to one left to rigth ]
one room is allotted to zero or one professor [ one to one right to left ]
one theatre can show many films [ one to Many left to rigth ]
one film is shown in many theatres [ one to Many right to left ]
The oracle and sql server can not support for many to many relationship....For these cases
we have to split the relationship into two one to many relationship...
one author can write many books [ one to Many left to rigth ]
one title is written by many authors [ one to Many right to left ]
-------------------------------------------------------------------------------------------------
Note: The calculated field(derived attribute) should not be stored in the database..For example
the age can be calculated with date-of-birth.....
-------------------------------------------------------------------------------------------------
25-jan-2002:
Normalization:
Segregating tables as to avoid redundancy...
DeNormalization:
introducing redundancy into tables to make more optimization or more performance the
Any database desin normally will not go beyond the third normal form....
Atomic values:
A field should record about the single attribute...
For example: To store address,we have to put street,city,state,country as a separate field names.
Then only possible to search the employees by city,state or country.....
(*) The field names shoud accept null values, if the no specefic info for that recor
and take to consideration the table should not have more null value fields.
Example:
---------------------------------------------------------------------------------------------------------
All the non key attributes should depend upon whole primary key or all the non key attributes
may depend on other non key attributes...
In the above table, the department id is partially belonging to the primary key,which means that the emp
itself only need to identify the department id and the project id is no longer needed...
*In order conform second normal form,we have take out the non key attribute which does not depend entril
the primary key and put it separate table along with the field on which the non key attribute is depen
eid did
---------
e1 IS
e2 IS
e3 NET
24 NET 46
nohrs is partially depend on primary key,which means the nohrs dependent on only project id...
Query - Page #21
pid nohrs
-----------
p1 20
p2 30 ( It is in third normal form,we can not split it again)
The dehead is not related to eid or pid...it is related to did.....so put dhead following table
---------------------------------------------------------------------------------------------------------
Third Normal Form:
All the non key attributes should be dependent only on the primary key
In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only th
did which is not a primary key of the table....
did dhead
--------------
IS boris
NET peter
---------------------------------------------------------------------------------------------------------
*************************************************************************************************
29-jan-2002:
Triggers:
Trigger is a stored procedure, it will be invoked automatically upon user action
(Insert,Update,Delete).
Cascade deletions:
The child table refers some field in the master table...We can not delete
any enty in the master table,which is refered by in the child table...The SQL server maintains
restrictions automatically...The cascade deletions is opposite of these restrictions....
Syntax:
The trigger can be depend on only one table...and the trigger can not defined on the views...
only three types of triggers ( Insert Trigger,Update Trigger,Delete Trigger) These are all after
trigger,The SQL could not support Before Triggers.....
Book Magazine
----------------------------
Bid Magid 47
Bname Mname
Author price
Query - Page #22
Transaction
--------------
Tid
Card_id
book_id
issue_date
return_date
--------------------------------------------------------------------------------------------------
Implementing primary key constraint:-
emp inserted
----------------------------------------------------
e1 boris d1 d1 HRD
e2 becker d2 d2 SYS
e3 sapeg d3
-------------------------------------------------------------------------------------------------
Implementing foreign key constraint:-
-------------------------------------------------------------------------------------------------
Note:
While creating trigger,the object should be exist on which the trigger imposed...but it
does not check the body of the statements.... 48
-------------------------------------------------------------------------------------------------
Implementing Cascade Deletion:-
Query - Page #23
The value from Trigger table is moved into Trigger Test Table (Deleted Table)
-------------------------------------------------------------------------------------------------
Implementing Restriction on deletion:-
------------------------------------------------------------------------------------------------
Question:
Create a trigger to move the deleted records to that respective back_up tables?????
Hits provided:
declare @i int
select @i=Object_id(’publishers’)
------------------------------------------------------------------------------------------------
31-JAN-2002:
-------------------------------------------------------------------------------------------
Note: The rollback command will only work on triggers it will not work on procedures....
--------------------------------------------------------------------------------------------
49
Note: Through the delete and update command will affect many rows.., the trigger will be
executed for each row...
---------------------------------------------------------------------------------------------
create trigger tri
Query - Page #24
on invoice
for update
if update(oid) // if the user tries to update field oid it will return true
begin or it will retun false
rollback
return
end
if not exists (select * from products,inserted
where inserted.productid=products.proudctid
begin
print ’Fk violation on products’
rollback
return
end
--------------------------------------------------------------------------------------------
Note: For update triggers, the inserted and deleted virutal table will be created....
deleted followed by inserted...................
--------------------------------------------------------------------------------------------
TSQL Cursors:
The main application of cursors is ’report’ generation..........
1....Declare
2....Open
3....Fetch
4....Close
5....Deallocate
A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’..
1...Declare:
Syntax:
Declare cursorname cursor
for
select statement
Note: It check the existence of the object but it would not compile and execute
-------------------------------------------------------------------------------------------------
2...Open:
Open cur; // Opening a cursor
Note: The select statement is executed and the resultset is stored inside the memory
-------------------------------------------------------------------------------------------------
3....Fetch:
Fetch next from cur;
Fetch prior from cur;
Fetch first from cur;
Fetch last from cur;
Note: It goes and bring the records one by one from the resultset which is stored in the memory
The logical pointer is pointed bof at first time....
-------------------------------------------------------------------------------------------------
4.....Close:
Close cur;
exec sen_cur_pro;
Note: @@fetch_status is system defined global variable which is automatically set to 0 which
indicates for successful fetch...
------------------------------------------------------------------------------------------------
1-02-2002:
Application of Cursors:
exec sen_cpro
Note: The Compute by clause should not be used in the select stattement along with cursor....
The Compute by clause should not be used in the select stattement along with subquery...
We can use order by and group by clause in the select statement along with cursor......
------------------------------------------------------------------------------------------------
Question : Write the procedure to display all book which is published by each publisher in neat format???
close tcur
deallocate tcur
end
print ’------------------------------------------------’
fetch next from cur into @pid,@pname
end
close cur
deallocate cur
exec sen_publisher_books
---------------------------------------------------------------------------------------------------------
2-Feb-2002:
Indexing:
It is a sorting process to reduce the searching process time....
Syntax:
The field on which indexed is sorted in ascending order and build binary tree....
It take the first value and any middle arbitary value
------------------------------------------------------------------------------------------------
Note: Through the index is created, the optimizer will decide wheter to use index is feasible or
it is feasible for going for table scan......
--------------------------------------------------------------------------------------------------
Note: Primary key creates Clustered automaically but to make it nonClustered index is more
feasible than Clustered index
--------------------------------------------------------------------------------------------
Clustered:
-----------------------------------------------------------------------------------------------
Note: The clustered index points the page...but the nonclustered index points the exact match of
record...
52
Query - Page #1
************************************************************************************************
// Set Primary key with ALTER TABLE COMMAND
**********************************************************************************************
// Create A Table with a Primary key
*********************************************************************************************
// Set Referencial Integrity [ Joining two tables ]
*********************************************************************************************
// Create a table with primary key and foreign key
***********************************************************************************************
// Droping a Constraint
*************************************************************************************************
// Droping a Column in a Table
***********************************************************************************************
// Create a Table with default value
53
CREATE TABLE _TEMP
(
empno int,
Query - Page #2
ename varchar(20),
city varchar(20) default ’cbe’
);
ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );
*****************************************************************************************
// Disabling Check constraint
******************************************************************************************
// Create a new table and copy only some particular fields of another Table
******************************************************************************************
//Create A Table and copy the data from another Table
******************************************************************************************
select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’
*********************************************************************************************
Grouping:
______________________________________________________________________________________
select type, sum(type) from titles; // Error
// Rule:
When ever you have aggregate function in the select list
along with some other fileds which are not enclosed with aggregate functions.
you should use group by functions.
_________________________________________________________________________________________
select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id d
sp_help titles
******************************************************************************************
// Select keywords
SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]
******************************************************************************************
SELECT *
FROM TITLES
ORDER BY TYPE DESC;
//////////////////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
group by type
order by title_id;
When ever use an order by class along with group by class the order by class should have
only those filels which are present in the group by class.
/////////////////////////////////////////////////////////////////////////////////////////////
select type,title_id,sum(price)
from titles
group by type
order by title_id; // Error
select type,title_id,sum(price)
from titles
group by type,title_id 55
order by title_id;
select sum(price)
from titles ; order by titles
select sum(price)
from titles
***********************************************************************
select type, count(*) from titles group by type having count(*)=3;
***********************************************************************
December 21 2001:
-----------------
Compute By class:
select type,price
from titles
order by type
compute sum(price) by type;
Whenever we use group by class or compute by class, the sql server builds Work Table....
In compute by class not able to generate Work Table automatically..but Group by class itself
able to generate Work Table...So the Compute by class relay order by class...
select type,price
from titles
order by pub_id
compute sum(price) by type; // Error
Reason:
The work table is built based on pub_id...In that work Table,we can’t find the sum of
price by Type...’
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type;
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by pub_id; // Error
Reason:
Work Table
Computer p2 200
Novel p1 200
Novel p1 240
Novel p2 450
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type,pub_id;
select type,pub_id,title_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id,title_id;
select type,pub_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id;
****************************************************
Afternoon:21-dec-2001
2...select type,pub_id
from titles
group by type,pub_id;
select type,pub_id
from titles
group by type,pub_id;
// In the above query.. The Distinct applies both type and pub_id columns..We can not make to apply
for a particular column. It will apply all the columns in the select list
For Ex
Business p1 200
Business p1 400
Business p1 300
Computer p2 500
Computer p2 700
The Result is
Business p1 200
Computer p2 500
/////////////////////////////////////////////////
select type,sum(price),avg(price)
from titles
group by price; // Error 57
Reason:
The field name in group by clause which is not used in aggregate function in select list
Query - Page #6
//////////////////////////////////////////////////////////
Having:
Having clause should have group by class...but when using group by class it is optional
to use Having clause.
1..select type,sum(price)
from titles
group by type
having type=’business’; // Grouped and followed by Filtered.......
2..select type,sum(price)
from titles
where type=’business’
group by type; // More Optimized: Fileterd and followed by Grouped...
All types of Records like Business,Computer and Novel and then take Business Records are Filtered
///////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select type,sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
/////////////////////////////////////////////////////////////////////////////////////////////////
December-26-2001
Joins: 58
if the select statement contains more table in from clause without where clause, it is called
cross joining which is never used...
select authors.au_id,authors.au_lname,authors.phone,
publishers.pub_id,publishers.pub_name,publishers.city
from authors,publishers
where authors.city = publishers.city;
select authors.*,pub_id,pub_name
from authors,publishers
where authors.city = publishers.city; // authors.* displays all fields in the Authors Table
Natural join:
The redundat field names are eliminated in the Result set
join
Equi Join :
The Redundat field names are present in the result set.
Table Alias:
select p.*,au_id,au_lname
from authors a, publishers p
where a.city = p.city and a.au_lname like ’c%’
select p.*,au_id,au_lname
from authors a, publishers p
where au_lname like ’c%’ and a.city = p.city
Question:
Find the publisher name for the book written by the author with fname ’Lorsley’
Answer:
select p.pub_name
from publishers p,authors a,titles t,titleauthor ta
where a.au_lname = ’Locksley’ and
a.au_id = ta.au_id and
ta.title_id = t.title_id and
t.pub_id = p.pub_id;
December 27 2001: 59
.................
Query - Page #8
Explanation:
Title: Authors
au_id au_lname
----------- ----------------------------
a1 lockley
a2 peter
Table: Publisher
pub_id pub_name
------ -----------
p1 samy
p2 golgotia
p3 samba
Table: Titles
title_id pub_id
-------- --------
t1 p1
t2 p2
t3 p3
Table: TitleAuthor
au_id title_id
----------- --------
a1 t1
a1 t2
a2 t1
a2 t3
Virtual Tables:
[Authors] [TitleAuthor]
aid aname au_id title_id
a1 lockey a1 t1
a1 lockey a1 t2
FAQ:
Ans: The Query optimizer find out which join will be evaluated first and run the query
in the optimized way.... 60
Cross Checking:
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
December 28 2001:
.................................................................................................
Self Join:
The Table joins with itself...
Rule:
’When use self join in the where condition, you shoud use the in-equility condition
of the primary keys’
................................................................................................
Question:
Find the name of the authors who lives in the same city...
Explanation:
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
A1
A6
A2
A3
61
select a.au_id,a.city
from authors a, authors b
where a.city = b.city; // It displays duplicate Records
Query - Page #10
select state,count(*)
from authors
group by state
having count(*)>1 // We should not use group by function in the self joining situations
Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Question: Find the author id who has written more than one book???
Question: Find the title_id which has been written by more than one author?
Question: Find the author Names who has written more than one book???
Query - Page #11
Question: Find the titles which has been written by more than one author?
/////////////////////////////////////////////////////////////////////////////////////////////////
Jan 02 2002:
Outer join:
emp
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Anderw SYS
e5 Lafer null
dep
emp
eno
ename
d_id
dept
ddid
dname
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
e5 lafer 63
////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
Sub Query:
A query with in query is called sub query...
Note: All joins can be formulated with sub query but all sub query can not be
formulated with joins
Question : Find the name and title of the most expensive book???
declare @p float;
select @p = max(price) from titles;
select @p;
select * from titles where price = @p;
Jan-04-2002:
Exists:
Rule: Exsits has the rule that no filed name in the where clause.
...............................................................................................
Simple Query: All the select statements are evaluated in the bottom up.
Correlated SubQuery:
1. The Correlated subquery will always have the join inside..[but just because
the join inside the subquery it does not make correlated subquery.]
Example:
select cid from orders where customers.id=orders.id, This query will return olny true or false.
The inner query is executed as many times the outer query depends....it means that the inner
query depends the value of outer query...
--------------------------------------------------------------------------------------------------------
7-01-2002:
Any self join can be carried out through correlated sub query.
select a.au_fname
from authors a
where exists ( select b.au_id
from authors b
where a.state = b.state and
a.au_id <> b.au_id ); // This is correlated sub query 1.It has join.
2.The left or right side field name is oute
The correlated sub query executed for every outer table row...but simple sub query executed only once...
It takes one record from the outer condition for that row all the rows of the inner codition will be exec
If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct
the correlated sub query.
---------------------------------------------------------------------------------------------------------
Union:
select * from authors union select * from sen_temp_table; // It will not give the duplicates of the re
if u want to include the duplicates use Union all keyword...
select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ
select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mis
Note: The order by statements can not be used in the individual query inside
the union but group by and having is allowed.
But order by allowed in the outside of the union .
Example:
select title_id,title from titles union all select title_id,au_id from titleauthor o
Note: The field name in the first select statement is allowed in the order by clause.
we can not use group by clause in the order by place....
---------------------------------------------------------------------------------------------------------
Self-Interest:
Ans:
drop vi
create view v_sample as
select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p
where o.proid=p.pid group by o.cuid 65
Ans:
select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p
where o.proid=p.pid group by o.cuid;
---------------------------------------------------------------------------------------------------------
11-01-2002:
Syntax:
Grant select|update|insert|delete on Table_name to User
Grant All Table_name to User
Revoke select|update|insert|delete on Table_name from User
Revoke All Table_name from User
View:
The View is the Projection of the base tables...
Syntax:
Create View view_name
as
select statement
Step 1:
create view sen_view_v1
as
select * from titles where title_id=’BU1111’
Step 2:
select * from sen_view_v1; // The select statement inside the view will be executed....
delete sen_view_v1;
*************************************************************************************************
16-January-2002:
Ex:
create view v1 as
select.....
Create view v2 as
select pub_id,sum(price) from titles group by pub_id; // The above statement would not work.
Here the sum(price) is tried to derive a new column in the view
create view v2 as
select 66 by pub_id
pub_id,sum(price) as "Total" from titles group
(or)
create view v2(publishers_id,price) as
select pub_id,sum(price) as "Total" from titles group by pub_id
Query - Page #15
//////////////////////////////////////////////////////////////////////////////////////////////
Rule:
1. We can not use order by,compute by,compute in the selection list while creating views.
2. We can not use ’Select into’ on views.
3. We can use order by indirectly.
//////////////////////////////////////////////////////////////////////////////////////////////
create view v1 as
select emp_no,emp_name,dept_id,phone from emp; // It would not work...
create view v1 as
select * form emp; // It will work
Rule 1:
The view has to contain all not null columns,[it will become updateable view] then olny
it is possible insert,update,delete, If the view does not contain all not null columns,
it is only readable veiw.We can not do insert,delete,update...
Rule 2:
If the select list in the view contains aggregate functions,the view is readable view...
create view v1 as
select emp_no,emp_name,emp.dept_id,phone,salary,dept_name from emp,dept
where emp.dept_id=dept.dept_id;
Rule 3:
In above statement, the insert is possible only if all the columns are in the same table
in the insert statememt. The insert will not work the columns are in different table...
////////////////////////////////////////////////////////////////////////////////////////////////
select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS
find whether it is table or view...if it is view, it executes the select statement with where
condition. And the statement looks like below....
Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpreted
as below....
Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....
insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view has
been created by with check option condition. It allow only the where clause condition is match, it
means that we can insert only ’HRD’ type......
/////////////////////////////////////////////////////////////////////////////////////////////////
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
17-January-2002:
Transact-SQL:
Transact-SQL is procedure oriented language
Stored Procedure:
Batch of sql statemets kept compiled in the server and ready for the execution.
In stored procedure,the return statement can return only int value,but we can return more
than one value by using output parameter concept.
Whatever variable used in sql server, these variable should begin with @ symbol. By default,
all parameters are input parameters.All system defined procedure is preceeded with sp...
The created procedure have an entry in sysobjects table.....The statements are used in procedure
will be stored in syscomments table.
Exec pro // while creating procudure, it checks only the syntax, while executing, the compilation
process is done..
select object_id (’demo’); // we can get the table id what the sql server maintains...
//////////////////////////////////////////////////////////////////////////////////////////////
what is Query plan????
The query plan is nothing but the path of the execution in the sql statements...
Exec pro;
The step 1 and step 2 will be executed at the first execution of the procedure..if u execute
the procedure another time, it will no go for compilation process,it just checks the procedure
Query - Page #17
cache and execute suitable obj file....If the system is gone for shut down, the contents of the
procedure cache will be deleted....Whatever changes made in table contents, it will re-complile.
if the table is dropped,the procedure for the table will not be deleted...
//////////////////////////////////////////////////////////////////////////////////////////////
18-January-2002:
if(@price <=100)
return 1;
if(@price>100 and @price<=200)
return 2;
if(@price >200)
return 3;
-------------------------------------
if @ret = 2
begin
select "Return 2";
end
if @ret = 3
begin
select "Return 3";
end
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Example:
Example
Query - Page #18
19-01-2002:
Output Parameters:
Question: Write the procedure to find the city and state of the given publishers????
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names ( use while loop )
------------------------------------------------------------------------------------------------
Goto Statement Example:
21-January-2002:
E-R Diagram:
Entity: 70
The entity is an object about information can be recorded..
Query - Page #19
For example, the employee and dept entity has some relationship between them...
1. One to One
2. One to Many
3. Many to Many
{Chen notation}
Employee has one to one relationship with Dept ( one employee has to work in only one dept)
Dept has one to many relationship with Employee ( one dept has many employees)
so we depict one to many relationship with these two entites....( one to one[left to right] and
one to many[right to left] realationship comes either side,Take a one to many relationship...)
For ex:
1.(emp)one instance of employee has how many instances of dept...(0,1){(min,max)}
(dept)one instance of dept has how many instances of employee...(0,M)
emp has a existence dependent with dept ( dept has to created before emp...)
Existence Dependent: It means that with out having a entry in dept table,the emp id can not
have an dept id ( Foreign key rules apply here..)
One professor can guide many students...[one to many relationship in left to right] in some
cases the one professor not giving guidence to any students....
One Student can get advise from one professor [one to one relationship in right to left]
one professor can have zero or one room [ one to one left to rigth ]
one room is allotted to zero or one professor [ one to one right to left ]
The oracle and sql server can not support for many to many relationship....For these cases
we have to split the relationship into two one to many relationship...
one author can write many books [ one to Many left to rigth ]
one title is written by many authors [ one to Many right to left ]
-------------------------------------------------------------------------------------------------
Note: The calculated field(derived attribute) should not be stored in the database..For example
the age can be calculated with date-of-birth.....
-------------------------------------------------------------------------------------------------
25-jan-2002:
Normalization:
Segregating tables as to avoid redundancy...
DeNormalization:
introducing redundancy into tables to make more optimization or more performance the
Any database desin normally will not go beyond the third normal form....
Atomic values:
A field should record about the single attribute...
For example: To store address,we have to put street,city,state,country as a separate field names.
Then only possible to search the employees by city,state or country.....
(*) The field names shoud accept null values, if the no specefic info for that recor
and take to consideration the table should not have more null value fields.
Example:
---------------------------------------------------------------------------------------------------------
All the non key attributes should depend upon whole primary key or all the non key attributes
may depend on other non key attributes...
In the above table, the department id is partially belonging to the primary key,which means that the emp
itself only need to identify the department id and the project id is no longer needed...
*In order conform second normal form,we have take out the non key attribute which does not depend entril
the primary key and put it separate table along with the field on which the non key attribute is depen
eid did
---------
Query - Page #21
e1 IS
e2 IS
e3 NET
24 NET
nohrs is partially depend on primary key,which means the nohrs dependent on only project id...
pid nohrs
-----------
p1 20
p2 30 ( It is in third normal form,we can not split it again)
The dehead is not related to eid or pid...it is related to did.....so put dhead following table
---------------------------------------------------------------------------------------------------------
Third Normal Form:
All the non key attributes should be dependent only on the primary key
In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only th
did which is not a primary key of the table....
did dhead
--------------
IS boris
NET peter
---------------------------------------------------------------------------------------------------------
*************************************************************************************************
29-jan-2002:
Triggers:
Trigger is a stored procedure, it will be invoked automatically upon user action
(Insert,Update,Delete).
Cascade deletions:
The child table refers some field in the master table...We can not delete
any enty in the master table,which is refered by in the child table...The SQL server maintains
restrictions automatically...The cascade deletions is opposite of these restrictions....
Syntax:
The trigger can be depend on only one table...and the trigger can not defined on the views...
73 Trigger,Delete Trigger) These are all after
only three types of triggers ( Insert Trigger,Update
trigger,The SQL could not support Before Triggers.....
Book Magazine
----------------------------
Bid Magid
Bname Mname
Author price
Transaction
--------------
Tid
Card_id
book_id
issue_date
return_date
--------------------------------------------------------------------------------------------------
Implementing primary key constraint:-
emp inserted
----------------------------------------------------
e1 boris d1 d1 HRD
e2 becker d2 d2 SYS
e3 sapeg d3
-------------------------------------------------------------------------------------------------
Implementing foreign key constraint:-
-------------------------------------------------------------------------------------------------
Note:
While creating trigger,the object should be exist on which the trigger imposed...but it
does not check the body of the statements....
-------------------------------------------------------------------------------------------------
Implementing Cascade Deletion:-
The value from Trigger table is moved into Trigger Test Table (Deleted Table)
-------------------------------------------------------------------------------------------------
Implementing Restriction on deletion:-
------------------------------------------------------------------------------------------------
Question:
Create a trigger to move the deleted records to that respective back_up tables?????
Hits provided:
declare @i int
select @i=Object_id(’publishers’)
------------------------------------------------------------------------------------------------
31-JAN-2002:
-------------------------------------------------------------------------------------------
Note: The rollback command will only work on triggers it will not work on procedures....
--------------------------------------------------------------------------------------------
Note: Through the delete and update command will affect many rows.., the trigger will be
executed for each row...
---------------------------------------------------------------------------------------------
create trigger tri
on invoice
for update
if update(oid) // if the user tries to update field oid it will return true
begin or it will retun false
rollback
return
end
if not exists (select * from products,inserted
where inserted.productid=products.proudctid
begin
print ’Fk violation on products’
rollback
return
end
--------------------------------------------------------------------------------------------
Note: For update triggers, the inserted and deleted virutal table will be created....
deleted followed by inserted...................
--------------------------------------------------------------------------------------------
TSQL Cursors:
The main application of cursors is ’report’ generation..........
1....Declare
2....Open
3....Fetch
4....Close
5....Deallocate
A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’..
1...Declare:
Syntax:
Declare cursorname cursor
for
select statement
Note: It check the existence of the object but it would not compile and execute
-------------------------------------------------------------------------------------------------
2...Open:
Open cur; // Opening a cursor
Note: The select statement is executed and the resultset is stored inside the memory
-------------------------------------------------------------------------------------------------
3....Fetch:
Fetch next from cur;
Fetch prior from cur;
Fetch first from cur;
Fetch last from cur;
Note: It goes and bring the records one by one from the resultset which is stored in the memory
The logical pointer is pointed bof at first time....
-------------------------------------------------------------------------------------------------
4.....Close:
Close cur;
exec sen_cur_pro;
Note: @@fetch_status is system defined global variable which is automatically set to 0 which
indicates for successful fetch...
------------------------------------------------------------------------------------------------
1-02-2002:
Application of Cursors:
exec sen_cpro
Note: The Compute by clause should not be used in the select stattement along with cursor....
The Compute by clause should not be used in the select stattement along with subquery...
We can use order by and group by clause in the select statement along with cursor......
------------------------------------------------------------------------------------------------
Question : Write the procedure to display all book which is published by each publisher in neat format???
open tcur
fetch next from tcur into @tid,@title,@price
while(@@fetch_status=0)
begin
print @tid + " " + @title + " " + convert(varchar,@price)
fetch next from tcur into @tid,@title,@price
end
close tcur
deallocate tcur
end
print ’------------------------------------------------’
fetch next from cur into @pid,@pname
end
close cur
deallocate cur
exec sen_publisher_books
---------------------------------------------------------------------------------------------------------
2-Feb-2002:
Indexing:
It is a sorting process to reduce the searching process time....
Syntax:
The field on which indexed is sorted in ascending order and build binary tree....
It take the first value and any middle arbitary value
------------------------------------------------------------------------------------------------
Note: Through the index is created, the optimizer will decide wheter to use index is feasible or
it is feasible for going for table scan......
--------------------------------------------------------------------------------------------------
Note: Primary key creates Clustered automaically but to make it nonClustered index is more
feasible than Clustered index
--------------------------------------------------------------------------------------------
Clustered:
-----------------------------------------------------------------------------------------------
Note: The clustered index points the page...but the nonclustered index points the exact match of
record...
78
Query - Page #1
************************************************************************************************
// Set Primary key with ALTER TABLE COMMAND
**********************************************************************************************
// Create A Table with a Primary key
*********************************************************************************************
// Set Referencial Integrity [ Joining two tables ]
*********************************************************************************************
// Create a table with primary key and foreign key
***********************************************************************************************
// Droping a Constraint
*************************************************************************************************
// Droping a Column in a Table
***********************************************************************************************
// Create a Table with default value
79
CREATE TABLE _TEMP
(
empno int,
Query - Page #2
ename varchar(20),
city varchar(20) default ’cbe’
);
ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );
*****************************************************************************************
// Disabling Check constraint
******************************************************************************************
// Create a new table and copy only some particular fields of another Table
******************************************************************************************
//Create A Table and copy the data from another Table
******************************************************************************************
select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’
*********************************************************************************************
Grouping:
______________________________________________________________________________________
select type, sum(type) from titles; // Error
// Rule:
When ever you have aggregate function in the select list
along with some other fileds which are not enclosed with aggregate functions.
you should use group by functions.
_________________________________________________________________________________________
select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id d
sp_help titles
******************************************************************************************
// Select keywords
SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]
******************************************************************************************
SELECT *
FROM TITLES
ORDER BY TYPE DESC;
//////////////////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
group by type
order by title_id;
When ever use an order by class along with group by class the order by class should have
only those filels which are present in the group by class.
/////////////////////////////////////////////////////////////////////////////////////////////
select type,title_id,sum(price)
from titles
group by type
order by title_id; // Error
select type,title_id,sum(price)
from titles
group by type,title_id 81
order by title_id;
select sum(price)
from titles ; order by titles
select sum(price)
from titles
***********************************************************************
select type, count(*) from titles group by type having count(*)=3;
***********************************************************************
December 21 2001:
-----------------
Compute By class:
select type,price
from titles
order by type
compute sum(price) by type;
Whenever we use group by class or compute by class, the sql server builds Work Table....
In compute by class not able to generate Work Table automatically..but Group by class itself
able to generate Work Table...So the Compute by class relay order by class...
select type,price
from titles
order by pub_id
compute sum(price) by type; // Error
Reason:
The work table is built based on pub_id...In that work Table,we can’t find the sum of
price by Type...’
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type;
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by pub_id; // Error
Reason:
Work Table
Computer p2 200
Novel p1 200
Novel p1 240
Novel p2 450
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type,pub_id;
select type,pub_id,title_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id,title_id;
select type,pub_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id;
****************************************************
Afternoon:21-dec-2001
2...select type,pub_id
from titles
group by type,pub_id;
select type,pub_id
from titles
group by type,pub_id;
// In the above query.. The Distinct applies both type and pub_id columns..We can not make to apply
for a particular column. It will apply all the columns in the select list
For Ex
Business p1 200
Business p1 400
Business p1 300
Computer p2 500
Computer p2 700
The Result is
Business p1 200
Computer p2 500
/////////////////////////////////////////////////
select type,sum(price),avg(price)
from titles
group by price; // Error 83
Reason:
The field name in group by clause which is not used in aggregate function in select list
Query - Page #6
//////////////////////////////////////////////////////////
Having:
Having clause should have group by class...but when using group by class it is optional
to use Having clause.
1..select type,sum(price)
from titles
group by type
having type=’business’; // Grouped and followed by Filtered.......
2..select type,sum(price)
from titles
where type=’business’
group by type; // More Optimized: Fileterd and followed by Grouped...
All types of Records like Business,Computer and Novel and then take Business Records are Filtered
///////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select type,sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
/////////////////////////////////////////////////////////////////////////////////////////////////
December-26-2001
Joins: 84
if the select statement contains more table in from clause without where clause, it is called
cross joining which is never used...
select authors.au_id,authors.au_lname,authors.phone,
publishers.pub_id,publishers.pub_name,publishers.city
from authors,publishers
where authors.city = publishers.city;
select authors.*,pub_id,pub_name
from authors,publishers
where authors.city = publishers.city; // authors.* displays all fields in the Authors Table
Natural join:
The redundat field names are eliminated in the Result set
join
Equi Join :
The Redundat field names are present in the result set.
Table Alias:
select p.*,au_id,au_lname
from authors a, publishers p
where a.city = p.city and a.au_lname like ’c%’
select p.*,au_id,au_lname
from authors a, publishers p
where au_lname like ’c%’ and a.city = p.city
Question:
Find the publisher name for the book written by the author with fname ’Lorsley’
Answer:
select p.pub_name
from publishers p,authors a,titles t,titleauthor ta
where a.au_lname = ’Locksley’ and
a.au_id = ta.au_id and
ta.title_id = t.title_id and
t.pub_id = p.pub_id;
December 27 2001: 85
.................
Query - Page #8
Explanation:
Title: Authors
au_id au_lname
----------- ----------------------------
a1 lockley
a2 peter
Table: Publisher
pub_id pub_name
------ -----------
p1 samy
p2 golgotia
p3 samba
Table: Titles
title_id pub_id
-------- --------
t1 p1
t2 p2
t3 p3
Table: TitleAuthor
au_id title_id
----------- --------
a1 t1
a1 t2
a2 t1
a2 t3
Virtual Tables:
[Authors] [TitleAuthor]
aid aname au_id title_id
a1 lockey a1 t1
a1 lockey a1 t2
FAQ:
Ans: The Query optimizer find out which join will be evaluated first and run the query
in the optimized way.... 86
Cross Checking:
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
December 28 2001:
.................................................................................................
Self Join:
The Table joins with itself...
Rule:
’When use self join in the where condition, you shoud use the in-equility condition
of the primary keys’
................................................................................................
Question:
Find the name of the authors who lives in the same city...
Explanation:
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
A1
A6
A2
A3
87
select a.au_id,a.city
from authors a, authors b
where a.city = b.city; // It displays duplicate Records
Query - Page #10
select state,count(*)
from authors
group by state
having count(*)>1 // We should not use group by function in the self joining situations
Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Question: Find the author id who has written more than one book???
Question: Find the title_id which has been written by more than one author?
Question: Find the author Names who has written more than one book???
Query - Page #11
Question: Find the titles which has been written by more than one author?
/////////////////////////////////////////////////////////////////////////////////////////////////
Jan 02 2002:
Outer join:
emp
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Anderw SYS
e5 Lafer null
dep
emp
eno
ename
d_id
dept
ddid
dname
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
e5 lafer 89
////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
Sub Query:
A query with in query is called sub query...
Note: All joins can be formulated with sub query but all sub query can not be
formulated with joins
Question : Find the name and title of the most expensive book???
declare @p float;
select @p = max(price) from titles;
select @p;
select * from titles where price = @p;
Jan-04-2002:
Exists:
Rule: Exsits has the rule that no filed name in the where clause.
...............................................................................................
Simple Query: All the select statements are evaluated in the bottom up.
Correlated SubQuery:
1. The Correlated subquery will always have the join inside..[but just because
the join inside the subquery it does not make correlated subquery.]
Example:
select cid from orders where customers.id=orders.id, This query will return olny true or false.
The inner query is executed as many times the outer query depends....it means that the inner
query depends the value of outer query...
--------------------------------------------------------------------------------------------------------
7-01-2002:
Any self join can be carried out through correlated sub query.
select a.au_fname
from authors a
where exists ( select b.au_id
from authors b
where a.state = b.state and
a.au_id <> b.au_id ); // This is correlated sub query 1.It has join.
2.The left or right side field name is oute
The correlated sub query executed for every outer table row...but simple sub query executed only once...
It takes one record from the outer condition for that row all the rows of the inner codition will be exec
If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct
the correlated sub query.
---------------------------------------------------------------------------------------------------------
Union:
select * from authors union select * from sen_temp_table; // It will not give the duplicates of the re
if u want to include the duplicates use Union all keyword...
select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ
select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mis
Note: The order by statements can not be used in the individual query inside
the union but group by and having is allowed.
But order by allowed in the outside of the union .
Example:
select title_id,title from titles union all select title_id,au_id from titleauthor o
Note: The field name in the first select statement is allowed in the order by clause.
we can not use group by clause in the order by place....
---------------------------------------------------------------------------------------------------------
Self-Interest:
Ans:
drop vi
create view v_sample as
select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p
where o.proid=p.pid group by o.cuid 91
Ans:
select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p
where o.proid=p.pid group by o.cuid;
---------------------------------------------------------------------------------------------------------
11-01-2002:
Syntax:
Grant select|update|insert|delete on Table_name to User
Grant All Table_name to User
Revoke select|update|insert|delete on Table_name from User
Revoke All Table_name from User
View:
The View is the Projection of the base tables...
Syntax:
Create View view_name
as
select statement
Step 1:
create view sen_view_v1
as
select * from titles where title_id=’BU1111’
Step 2:
select * from sen_view_v1; // The select statement inside the view will be executed....
delete sen_view_v1;
*************************************************************************************************
16-January-2002:
Ex:
create view v1 as
select.....
Create view v2 as
select pub_id,sum(price) from titles group by pub_id; // The above statement would not work.
Here the sum(price) is tried to derive a new column in the view
create view v2 as
select 92 by pub_id
pub_id,sum(price) as "Total" from titles group
(or)
create view v2(publishers_id,price) as
select pub_id,sum(price) as "Total" from titles group by pub_id
Query - Page #15
//////////////////////////////////////////////////////////////////////////////////////////////
Rule:
1. We can not use order by,compute by,compute in the selection list while creating views.
2. We can not use ’Select into’ on views.
3. We can use order by indirectly.
//////////////////////////////////////////////////////////////////////////////////////////////
create view v1 as
select emp_no,emp_name,dept_id,phone from emp; // It would not work...
create view v1 as
select * form emp; // It will work
Rule 1:
The view has to contain all not null columns,[it will become updateable view] then olny
it is possible insert,update,delete, If the view does not contain all not null columns,
it is only readable veiw.We can not do insert,delete,update...
Rule 2:
If the select list in the view contains aggregate functions,the view is readable view...
create view v1 as
select emp_no,emp_name,emp.dept_id,phone,salary,dept_name from emp,dept
where emp.dept_id=dept.dept_id;
Rule 3:
In above statement, the insert is possible only if all the columns are in the same table
in the insert statememt. The insert will not work the columns are in different table...
////////////////////////////////////////////////////////////////////////////////////////////////
select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS
find whether it is table or view...if it is view, it executes the select statement with where
condition. And the statement looks like below....
Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpreted
as below....
Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....
insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view has
been created by with check option condition. It allow only the where clause condition is match, it
means that we can insert only ’HRD’ type......
/////////////////////////////////////////////////////////////////////////////////////////////////
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
17-January-2002:
Transact-SQL:
Transact-SQL is procedure oriented language
Stored Procedure:
Batch of sql statemets kept compiled in the server and ready for the execution.
In stored procedure,the return statement can return only int value,but we can return more
than one value by using output parameter concept.
Whatever variable used in sql server, these variable should begin with @ symbol. By default,
all parameters are input parameters.All system defined procedure is preceeded with sp...
The created procedure have an entry in sysobjects table.....The statements are used in procedure
will be stored in syscomments table.
Exec pro // while creating procudure, it checks only the syntax, while executing, the compilation
process is done..
select object_id (’demo’); // we can get the table id what the sql server maintains...
//////////////////////////////////////////////////////////////////////////////////////////////
what is Query plan????
The query plan is nothing but the path of the execution in the sql statements...
Exec pro;
The step 1 and step 2 will be executed at the first execution of the procedure..if u execute
the procedure another time, it will no go for compilation process,it just checks the procedure
Query - Page #17
cache and execute suitable obj file....If the system is gone for shut down, the contents of the
procedure cache will be deleted....Whatever changes made in table contents, it will re-complile.
if the table is dropped,the procedure for the table will not be deleted...
//////////////////////////////////////////////////////////////////////////////////////////////
18-January-2002:
if(@price <=100)
return 1;
if(@price>100 and @price<=200)
return 2;
if(@price >200)
return 3;
-------------------------------------
if @ret = 2
begin
select "Return 2";
end
if @ret = 3
begin
select "Return 3";
end
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Example:
Example
Query - Page #18
19-01-2002:
Output Parameters:
Question: Write the procedure to find the city and state of the given publishers????
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names ( use while loop )
------------------------------------------------------------------------------------------------
Goto Statement Example:
21-January-2002:
E-R Diagram:
Entity: 96
The entity is an object about information can be recorded..
Query - Page #19
For example, the employee and dept entity has some relationship between them...
1. One to One
2. One to Many
3. Many to Many
{Chen notation}
Employee has one to one relationship with Dept ( one employee has to work in only one dept)
Dept has one to many relationship with Employee ( one dept has many employees)
so we depict one to many relationship with these two entites....( one to one[left to right] and
one to many[right to left] realationship comes either side,Take a one to many relationship...)
For ex:
1.(emp)one instance of employee has how many instances of dept...(0,1){(min,max)}
(dept)one instance of dept has how many instances of employee...(0,M)
emp has a existence dependent with dept ( dept has to created before emp...)
Existence Dependent: It means that with out having a entry in dept table,the emp id can not
have an dept id ( Foreign key rules apply here..)
One professor can guide many students...[one to many relationship in left to right] in some
cases the one professor not giving guidence to any students....
One Student can get advise from one professor [one to one relationship in right to left]
one professor can have zero or one room [ one to one left to rigth ]
one room is allotted to zero or one professor [ one to one right to left ]
The oracle and sql server can not support for many to many relationship....For these cases
we have to split the relationship into two one to many relationship...
one author can write many books [ one to Many left to rigth ]
one title is written by many authors [ one to Many right to left ]
-------------------------------------------------------------------------------------------------
Note: The calculated field(derived attribute) should not be stored in the database..For example
the age can be calculated with date-of-birth.....
-------------------------------------------------------------------------------------------------
25-jan-2002:
Normalization:
Segregating tables as to avoid redundancy...
DeNormalization:
introducing redundancy into tables to make more optimization or more performance the
Any database desin normally will not go beyond the third normal form....
Atomic values:
A field should record about the single attribute...
For example: To store address,we have to put street,city,state,country as a separate field names.
Then only possible to search the employees by city,state or country.....
(*) The field names shoud accept null values, if the no specefic info for that recor
and take to consideration the table should not have more null value fields.
Example:
---------------------------------------------------------------------------------------------------------
All the non key attributes should depend upon whole primary key or all the non key attributes
may depend on other non key attributes...
In the above table, the department id is partially belonging to the primary key,which means that the emp
itself only need to identify the department id and the project id is no longer needed...
*In order conform second normal form,we have take out the non key attribute which does not depend entril
the primary key and put it separate table along with the field on which the non key attribute is depen
eid did
---------
Query - Page #21
e1 IS
e2 IS
e3 NET
24 NET
nohrs is partially depend on primary key,which means the nohrs dependent on only project id...
pid nohrs
-----------
p1 20
p2 30 ( It is in third normal form,we can not split it again)
The dehead is not related to eid or pid...it is related to did.....so put dhead following table
---------------------------------------------------------------------------------------------------------
Third Normal Form:
All the non key attributes should be dependent only on the primary key
In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only th
did which is not a primary key of the table....
did dhead
--------------
IS boris
NET peter
---------------------------------------------------------------------------------------------------------
*************************************************************************************************
29-jan-2002:
Triggers:
Trigger is a stored procedure, it will be invoked automatically upon user action
(Insert,Update,Delete).
Cascade deletions:
The child table refers some field in the master table...We can not delete
any enty in the master table,which is refered by in the child table...The SQL server maintains
restrictions automatically...The cascade deletions is opposite of these restrictions....
Syntax:
The trigger can be depend on only one table...and the trigger can not defined on the views...
99 Trigger,Delete Trigger) These are all after
only three types of triggers ( Insert Trigger,Update
trigger,The SQL could not support Before Triggers.....
Book Magazine
----------------------------
Bid Magid
Bname Mname
Author price
Transaction
--------------
Tid
Card_id
book_id
issue_date
return_date
--------------------------------------------------------------------------------------------------
Implementing primary key constraint:-
emp inserted
----------------------------------------------------
e1 boris d1 d1 HRD
e2 becker d2 d2 SYS
e3 sapeg d3
-------------------------------------------------------------------------------------------------
Implementing foreign key constraint:-
-------------------------------------------------------------------------------------------------
Note:
While creating trigger,the object should be exist on which the trigger imposed...but it
does not check the body of the statements....
-------------------------------------------------------------------------------------------------
Implementing Cascade Deletion:-
The value from Trigger table is moved into Trigger Test Table (Deleted Table)
-------------------------------------------------------------------------------------------------
Implementing Restriction on deletion:-
------------------------------------------------------------------------------------------------
Question:
Create a trigger to move the deleted records to that respective back_up tables?????
Hits provided:
declare @i int
select @i=Object_id(’publishers’)
------------------------------------------------------------------------------------------------
31-JAN-2002:
-------------------------------------------------------------------------------------------
Note: The rollback command will only work on triggers it will not work on procedures....
--------------------------------------------------------------------------------------------
Note: Through the delete and update command will affect many rows.., the trigger will be
executed for each row...
---------------------------------------------------------------------------------------------
create trigger tri
on invoice
for update
if update(oid) // if the user tries to update field oid it will return true
begin or it will retun false
rollback
return
end
if not exists (select * from products,inserted
where inserted.productid=products.proudctid
begin
print ’Fk violation on products’
rollback
return
end
--------------------------------------------------------------------------------------------
Note: For update triggers, the inserted and deleted virutal table will be created....
deleted followed by inserted...................
--------------------------------------------------------------------------------------------
TSQL Cursors:
The main application of cursors is ’report’ generation..........
1....Declare
2....Open
3....Fetch
4....Close
5....Deallocate
A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’..
1...Declare:
Syntax:
Declare cursorname cursor
for
select statement
Note: It check the existence of the object but it would not compile and execute
-------------------------------------------------------------------------------------------------
2...Open:
Open cur; // Opening a cursor
Note: The select statement is executed and the resultset is stored inside the memory
-------------------------------------------------------------------------------------------------
3....Fetch:
Fetch next from cur;
Fetch prior from cur;
Fetch first from cur;
Fetch last from cur;
Note: It goes and bring the records one by one from the resultset which is stored in the memory
The logical pointer is pointed bof at first time....
-------------------------------------------------------------------------------------------------
4.....Close:
Close cur;
exec sen_cur_pro;
Note: @@fetch_status is system defined global variable which is automatically set to 0 which
indicates for successful fetch...
------------------------------------------------------------------------------------------------
1-02-2002:
Application of Cursors:
exec sen_cpro
Note: The Compute by clause should not be used in the select stattement along with cursor....
The Compute by clause should not be used in the select stattement along with subquery...
We can use order by and group by clause in the select statement along with cursor......
------------------------------------------------------------------------------------------------
Question : Write the procedure to display all book which is published by each publisher in neat format???
open tcur
fetch next from tcur into @tid,@title,@price
while(@@fetch_status=0)
begin
print @tid + " " + @title + " " + convert(varchar,@price)
fetch next from tcur into @tid,@title,@price
end
close tcur
deallocate tcur
end
print ’------------------------------------------------’
fetch next from cur into @pid,@pname
end
close cur
deallocate cur
exec sen_publisher_books
---------------------------------------------------------------------------------------------------------
2-Feb-2002:
Indexing:
It is a sorting process to reduce the searching process time....
Syntax:
The field on which indexed is sorted in ascending order and build binary tree....
It take the first value and any middle arbitary value
------------------------------------------------------------------------------------------------
Note: Through the index is created, the optimizer will decide wheter to use index is feasible or
it is feasible for going for table scan......
--------------------------------------------------------------------------------------------------
Note: Primary key creates Clustered automaically but to make it nonClustered index is more
feasible than Clustered index
--------------------------------------------------------------------------------------------
Clustered:
-----------------------------------------------------------------------------------------------
Note: The clustered index points the page...but the nonclustered index points the exact match of
record...
104
Query - Page #1
************************************************************************************************
// Set Primary key with ALTER TABLE COMMAND
**********************************************************************************************
// Create A Table with a Primary key
*********************************************************************************************
// Set Referencial Integrity [ Joining two tables ]
*********************************************************************************************
// Create a table with primary key and foreign key
***********************************************************************************************
// Droping a Constraint
*************************************************************************************************
// Droping a Column in a Table
***********************************************************************************************
// Create a Table with default value
105
CREATE TABLE _TEMP
(
empno int,
Query - Page #2
ename varchar(20),
city varchar(20) default ’cbe’
);
ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );
*****************************************************************************************
// Disabling Check constraint
******************************************************************************************
// Create a new table and copy only some particular fields of another Table
******************************************************************************************
//Create A Table and copy the data from another Table
******************************************************************************************
select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’
*********************************************************************************************
Grouping:
______________________________________________________________________________________
select type, sum(type) from titles; // Error
// Rule:
When ever you have aggregate function in the select list
along with some other fileds which are not enclosed with aggregate functions.
you should use group by functions.
_________________________________________________________________________________________
select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id d
sp_help titles
******************************************************************************************
// Select keywords
SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]
******************************************************************************************
SELECT *
FROM TITLES
ORDER BY TYPE DESC;
//////////////////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
group by type
order by title_id;
When ever use an order by class along with group by class the order by class should have
only those filels which are present in the group by class.
/////////////////////////////////////////////////////////////////////////////////////////////
select type,title_id,sum(price)
from titles
group by type
order by title_id; // Error
select type,title_id,sum(price)
from titles
group by type,title_id 107
order by title_id;
select sum(price)
from titles ; order by titles
select sum(price)
from titles
***********************************************************************
select type, count(*) from titles group by type having count(*)=3;
***********************************************************************
December 21 2001:
-----------------
Compute By class:
select type,price
from titles
order by type
compute sum(price) by type;
Whenever we use group by class or compute by class, the sql server builds Work Table....
In compute by class not able to generate Work Table automatically..but Group by class itself
able to generate Work Table...So the Compute by class relay order by class...
select type,price
from titles
order by pub_id
compute sum(price) by type; // Error
Reason:
The work table is built based on pub_id...In that work Table,we can’t find the sum of
price by Type...’
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type;
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by pub_id; // Error
Reason:
Work Table
Computer p2 200
Novel p1 200
Novel p1 240
Novel p2 450
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type,pub_id;
select type,pub_id,title_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id,title_id;
select type,pub_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id;
****************************************************
Afternoon:21-dec-2001
2...select type,pub_id
from titles
group by type,pub_id;
select type,pub_id
from titles
group by type,pub_id;
// In the above query.. The Distinct applies both type and pub_id columns..We can not make to apply
for a particular column. It will apply all the columns in the select list
For Ex
Business p1 200
Business p1 400
Business p1 300
Computer p2 500
Computer p2 700
The Result is
Business p1 200
Computer p2 500
/////////////////////////////////////////////////
select type,sum(price),avg(price)
from titles
group by price; // Error 109
Reason:
The field name in group by clause which is not used in aggregate function in select list
Query - Page #6
//////////////////////////////////////////////////////////
Having:
Having clause should have group by class...but when using group by class it is optional
to use Having clause.
1..select type,sum(price)
from titles
group by type
having type=’business’; // Grouped and followed by Filtered.......
2..select type,sum(price)
from titles
where type=’business’
group by type; // More Optimized: Fileterd and followed by Grouped...
All types of Records like Business,Computer and Novel and then take Business Records are Filtered
///////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select type,sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
/////////////////////////////////////////////////////////////////////////////////////////////////
December-26-2001
Joins: 110
if the select statement contains more table in from clause without where clause, it is called
cross joining which is never used...
select authors.au_id,authors.au_lname,authors.phone,
publishers.pub_id,publishers.pub_name,publishers.city
from authors,publishers
where authors.city = publishers.city;
select authors.*,pub_id,pub_name
from authors,publishers
where authors.city = publishers.city; // authors.* displays all fields in the Authors Table
Natural join:
The redundat field names are eliminated in the Result set
join
Equi Join :
The Redundat field names are present in the result set.
Table Alias:
select p.*,au_id,au_lname
from authors a, publishers p
where a.city = p.city and a.au_lname like ’c%’
select p.*,au_id,au_lname
from authors a, publishers p
where au_lname like ’c%’ and a.city = p.city
Question:
Find the publisher name for the book written by the author with fname ’Lorsley’
Answer:
select p.pub_name
from publishers p,authors a,titles t,titleauthor ta
where a.au_lname = ’Locksley’ and
a.au_id = ta.au_id and
ta.title_id = t.title_id and
t.pub_id = p.pub_id;
Explanation:
Title: Authors
au_id au_lname
----------- ----------------------------
a1 lockley
a2 peter
Table: Publisher
pub_id pub_name
------ -----------
p1 samy
p2 golgotia
p3 samba
Table: Titles
title_id pub_id
-------- --------
t1 p1
t2 p2
t3 p3
Table: TitleAuthor
au_id title_id
----------- --------
a1 t1
a1 t2
a2 t1
a2 t3
Virtual Tables:
[Authors] [TitleAuthor]
aid aname au_id title_id
a1 lockey a1 t1
a1 lockey a1 t2
FAQ:
Ans: The Query optimizer find out which join will be evaluated first and run the query
in the optimized way.... 112
Cross Checking:
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
December 28 2001:
.................................................................................................
Self Join:
The Table joins with itself...
Rule:
’When use self join in the where condition, you shoud use the in-equility condition
of the primary keys’
................................................................................................
Question:
Find the name of the authors who lives in the same city...
Explanation:
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
A1
A6
A2
A3
113
select a.au_id,a.city
from authors a, authors b
where a.city = b.city; // It displays duplicate Records
Query - Page #10
select state,count(*)
from authors
group by state
having count(*)>1 // We should not use group by function in the self joining situations
Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Question: Find the author id who has written more than one book???
Question: Find the title_id which has been written by more than one author?
Question: Find the author Names who has written more than one book???
Query - Page #11
Question: Find the titles which has been written by more than one author?
/////////////////////////////////////////////////////////////////////////////////////////////////
Jan 02 2002:
Outer join:
emp
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Anderw SYS
e5 Lafer null
dep
emp
eno
ename
d_id
dept
ddid
dname
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
e5 lafer 115
////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
Sub Query:
A query with in query is called sub query...
Note: All joins can be formulated with sub query but all sub query can not be
formulated with joins
Question : Find the name and title of the most expensive book???
declare @p float;
select @p = max(price) from titles;
select @p;
select * from titles where price = @p;
Jan-04-2002:
Exists:
Rule: Exsits has the rule that no filed name in the where clause.
...............................................................................................
Simple Query: All the select statements are evaluated in the bottom up.
Correlated SubQuery:
1. The Correlated subquery will always have the join inside..[but just because
the join inside the subquery it does not make correlated subquery.]
Example:
select cid from orders where customers.id=orders.id, This query will return olny true or false.
The inner query is executed as many times the outer query depends....it means that the inner
query depends the value of outer query...
--------------------------------------------------------------------------------------------------------
7-01-2002:
Any self join can be carried out through correlated sub query.
select a.au_fname
from authors a
where exists ( select b.au_id
from authors b
where a.state = b.state and
a.au_id <> b.au_id ); // This is correlated sub query 1.It has join.
2.The left or right side field name is oute
The correlated sub query executed for every outer table row...but simple sub query executed only once...
It takes one record from the outer condition for that row all the rows of the inner codition will be exec
If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct
the correlated sub query.
---------------------------------------------------------------------------------------------------------
Union:
select * from authors union select * from sen_temp_table; // It will not give the duplicates of the re
if u want to include the duplicates use Union all keyword...
select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ
select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mis
Note: The order by statements can not be used in the individual query inside
the union but group by and having is allowed.
But order by allowed in the outside of the union .
Example:
select title_id,title from titles union all select title_id,au_id from titleauthor o
Note: The field name in the first select statement is allowed in the order by clause.
we can not use group by clause in the order by place....
---------------------------------------------------------------------------------------------------------
Self-Interest:
Ans:
drop vi
create view v_sample as
select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p
where o.proid=p.pid group by o.cuid 117
Ans:
select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p
where o.proid=p.pid group by o.cuid;
---------------------------------------------------------------------------------------------------------
11-01-2002:
Syntax:
Grant select|update|insert|delete on Table_name to User
Grant All Table_name to User
Revoke select|update|insert|delete on Table_name from User
Revoke All Table_name from User
View:
The View is the Projection of the base tables...
Syntax:
Create View view_name
as
select statement
Step 1:
create view sen_view_v1
as
select * from titles where title_id=’BU1111’
Step 2:
select * from sen_view_v1; // The select statement inside the view will be executed....
delete sen_view_v1;
*************************************************************************************************
16-January-2002:
Ex:
create view v1 as
select.....
Create view v2 as
select pub_id,sum(price) from titles group by pub_id; // The above statement would not work.
Here the sum(price) is tried to derive a new column in the view
create view v2 as
select 118 by pub_id
pub_id,sum(price) as "Total" from titles group
(or)
create view v2(publishers_id,price) as
select pub_id,sum(price) as "Total" from titles group by pub_id
Query - Page #15
//////////////////////////////////////////////////////////////////////////////////////////////
Rule:
1. We can not use order by,compute by,compute in the selection list while creating views.
2. We can not use ’Select into’ on views.
3. We can use order by indirectly.
//////////////////////////////////////////////////////////////////////////////////////////////
create view v1 as
select emp_no,emp_name,dept_id,phone from emp; // It would not work...
create view v1 as
select * form emp; // It will work
Rule 1:
The view has to contain all not null columns,[it will become updateable view] then olny
it is possible insert,update,delete, If the view does not contain all not null columns,
it is only readable veiw.We can not do insert,delete,update...
Rule 2:
If the select list in the view contains aggregate functions,the view is readable view...
create view v1 as
select emp_no,emp_name,emp.dept_id,phone,salary,dept_name from emp,dept
where emp.dept_id=dept.dept_id;
Rule 3:
In above statement, the insert is possible only if all the columns are in the same table
in the insert statememt. The insert will not work the columns are in different table...
////////////////////////////////////////////////////////////////////////////////////////////////
select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS
find whether it is table or view...if it is view, it executes the select statement with where
condition. And the statement looks like below....
Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpreted
as below....
Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....
insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view has
been created by with check option condition. It allow only the where clause condition is match, it
means that we can insert only ’HRD’ type......
/////////////////////////////////////////////////////////////////////////////////////////////////
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
17-January-2002:
Transact-SQL:
Transact-SQL is procedure oriented language
Stored Procedure:
Batch of sql statemets kept compiled in the server and ready for the execution.
In stored procedure,the return statement can return only int value,but we can return more
than one value by using output parameter concept.
Whatever variable used in sql server, these variable should begin with @ symbol. By default,
all parameters are input parameters.All system defined procedure is preceeded with sp...
The created procedure have an entry in sysobjects table.....The statements are used in procedure
will be stored in syscomments table.
Exec pro // while creating procudure, it checks only the syntax, while executing, the compilation
process is done..
select object_id (’demo’); // we can get the table id what the sql server maintains...
//////////////////////////////////////////////////////////////////////////////////////////////
what is Query plan????
The query plan is nothing but the path of the execution in the sql statements...
Exec pro;
The step 1 and step 2 will be executed at the first execution of the procedure..if u execute
the procedure another time, it will no go for compilation process,it just checks the procedure
Query - Page #17
cache and execute suitable obj file....If the system is gone for shut down, the contents of the
procedure cache will be deleted....Whatever changes made in table contents, it will re-complile.
if the table is dropped,the procedure for the table will not be deleted...
//////////////////////////////////////////////////////////////////////////////////////////////
18-January-2002:
if(@price <=100)
return 1;
if(@price>100 and @price<=200)
return 2;
if(@price >200)
return 3;
-------------------------------------
if @ret = 2
begin
select "Return 2";
end
if @ret = 3
begin
select "Return 3";
end
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Example:
Example
Query - Page #18
19-01-2002:
Output Parameters:
Question: Write the procedure to find the city and state of the given publishers????
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names ( use while loop )
------------------------------------------------------------------------------------------------
Goto Statement Example:
21-January-2002:
E-R Diagram:
Entity: 122
The entity is an object about information can be recorded..
Query - Page #19
For example, the employee and dept entity has some relationship between them...
1. One to One
2. One to Many
3. Many to Many
{Chen notation}
Employee has one to one relationship with Dept ( one employee has to work in only one dept)
Dept has one to many relationship with Employee ( one dept has many employees)
so we depict one to many relationship with these two entites....( one to one[left to right] and
one to many[right to left] realationship comes either side,Take a one to many relationship...)
For ex:
1.(emp)one instance of employee has how many instances of dept...(0,1){(min,max)}
(dept)one instance of dept has how many instances of employee...(0,M)
emp has a existence dependent with dept ( dept has to created before emp...)
Existence Dependent: It means that with out having a entry in dept table,the emp id can not
have an dept id ( Foreign key rules apply here..)
One professor can guide many students...[one to many relationship in left to right] in some
cases the one professor not giving guidence to any students....
One Student can get advise from one professor [one to one relationship in right to left]
one professor can have zero or one room [ one to one left to rigth ]
one room is allotted to zero or one professor [ one to one right to left ]
The oracle and sql server can not support for many to many relationship....For these cases
we have to split the relationship into two one to many relationship...
one author can write many books [ one to Many left to rigth ]
one title is written by many authors [ one to Many right to left ]
-------------------------------------------------------------------------------------------------
Note: The calculated field(derived attribute) should not be stored in the database..For example
the age can be calculated with date-of-birth.....
-------------------------------------------------------------------------------------------------
25-jan-2002:
Normalization:
Segregating tables as to avoid redundancy...
DeNormalization:
introducing redundancy into tables to make more optimization or more performance the
Any database desin normally will not go beyond the third normal form....
Atomic values:
A field should record about the single attribute...
For example: To store address,we have to put street,city,state,country as a separate field names.
Then only possible to search the employees by city,state or country.....
(*) The field names shoud accept null values, if the no specefic info for that recor
and take to consideration the table should not have more null value fields.
Example:
---------------------------------------------------------------------------------------------------------
All the non key attributes should depend upon whole primary key or all the non key attributes
may depend on other non key attributes...
In the above table, the department id is partially belonging to the primary key,which means that the emp
itself only need to identify the department id and the project id is no longer needed...
*In order conform second normal form,we have take out the non key attribute which does not depend entril
the primary key and put it separate table along with the field on which the non key attribute is depen
eid did
---------
Query - Page #21
e1 IS
e2 IS
e3 NET
24 NET
nohrs is partially depend on primary key,which means the nohrs dependent on only project id...
pid nohrs
-----------
p1 20
p2 30 ( It is in third normal form,we can not split it again)
The dehead is not related to eid or pid...it is related to did.....so put dhead following table
---------------------------------------------------------------------------------------------------------
Third Normal Form:
All the non key attributes should be dependent only on the primary key
In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only th
did which is not a primary key of the table....
did dhead
--------------
IS boris
NET peter
---------------------------------------------------------------------------------------------------------
*************************************************************************************************
29-jan-2002:
Triggers:
Trigger is a stored procedure, it will be invoked automatically upon user action
(Insert,Update,Delete).
Cascade deletions:
The child table refers some field in the master table...We can not delete
any enty in the master table,which is refered by in the child table...The SQL server maintains
restrictions automatically...The cascade deletions is opposite of these restrictions....
Syntax:
The trigger can be depend on only one table...and the trigger can not defined on the views...
125 Trigger,Delete Trigger) These are all after
only three types of triggers ( Insert Trigger,Update
trigger,The SQL could not support Before Triggers.....
Book Magazine
----------------------------
Bid Magid
Bname Mname
Author price
Transaction
--------------
Tid
Card_id
book_id
issue_date
return_date
--------------------------------------------------------------------------------------------------
Implementing primary key constraint:-
emp inserted
----------------------------------------------------
e1 boris d1 d1 HRD
e2 becker d2 d2 SYS
e3 sapeg d3
-------------------------------------------------------------------------------------------------
Implementing foreign key constraint:-
-------------------------------------------------------------------------------------------------
Note:
While creating trigger,the object should be exist on which the trigger imposed...but it
does not check the body of the statements....
-------------------------------------------------------------------------------------------------
Implementing Cascade Deletion:-
The value from Trigger table is moved into Trigger Test Table (Deleted Table)
-------------------------------------------------------------------------------------------------
Implementing Restriction on deletion:-
------------------------------------------------------------------------------------------------
Question:
Create a trigger to move the deleted records to that respective back_up tables?????
Hits provided:
declare @i int
select @i=Object_id(’publishers’)
------------------------------------------------------------------------------------------------
31-JAN-2002:
-------------------------------------------------------------------------------------------
Note: The rollback command will only work on triggers it will not work on procedures....
--------------------------------------------------------------------------------------------
Note: Through the delete and update command will affect many rows.., the trigger will be
executed for each row...
---------------------------------------------------------------------------------------------
create trigger tri
on invoice
for update
if update(oid) // if the user tries to update field oid it will return true
begin or it will retun false
rollback
return
end
if not exists (select * from products,inserted
where inserted.productid=products.proudctid
begin
print ’Fk violation on products’
rollback
return
end
--------------------------------------------------------------------------------------------
Note: For update triggers, the inserted and deleted virutal table will be created....
deleted followed by inserted...................
--------------------------------------------------------------------------------------------
TSQL Cursors:
The main application of cursors is ’report’ generation..........
1....Declare
2....Open
3....Fetch
4....Close
5....Deallocate
A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’..
1...Declare:
Syntax:
Declare cursorname cursor
for
select statement
Note: It check the existence of the object but it would not compile and execute
-------------------------------------------------------------------------------------------------
2...Open:
Open cur; // Opening a cursor
Note: The select statement is executed and the resultset is stored inside the memory
-------------------------------------------------------------------------------------------------
3....Fetch:
Fetch next from cur;
Fetch prior from cur;
Fetch first from cur;
Fetch last from cur;
Note: It goes and bring the records one by one from the resultset which is stored in the memory
The logical pointer is pointed bof at first time....
-------------------------------------------------------------------------------------------------
4.....Close:
Close cur;
exec sen_cur_pro;
Note: @@fetch_status is system defined global variable which is automatically set to 0 which
indicates for successful fetch...
------------------------------------------------------------------------------------------------
1-02-2002:
Application of Cursors:
exec sen_cpro
Note: The Compute by clause should not be used in the select stattement along with cursor....
The Compute by clause should not be used in the select stattement along with subquery...
We can use order by and group by clause in the select statement along with cursor......
------------------------------------------------------------------------------------------------
Question : Write the procedure to display all book which is published by each publisher in neat format???
open tcur
fetch next from tcur into @tid,@title,@price
while(@@fetch_status=0)
begin
print @tid + " " + @title + " " + convert(varchar,@price)
fetch next from tcur into @tid,@title,@price
end
close tcur
deallocate tcur
end
print ’------------------------------------------------’
fetch next from cur into @pid,@pname
end
close cur
deallocate cur
exec sen_publisher_books
---------------------------------------------------------------------------------------------------------
2-Feb-2002:
Indexing:
It is a sorting process to reduce the searching process time....
Syntax:
The field on which indexed is sorted in ascending order and build binary tree....
It take the first value and any middle arbitary value
------------------------------------------------------------------------------------------------
Note: Through the index is created, the optimizer will decide wheter to use index is feasible or
it is feasible for going for table scan......
--------------------------------------------------------------------------------------------------
Note: Primary key creates Clustered automaically but to make it nonClustered index is more
feasible than Clustered index
--------------------------------------------------------------------------------------------
Clustered:
-----------------------------------------------------------------------------------------------
Note: The clustered index points the page...but the nonclustered index points the exact match of
record...
130
Query - Page #1
************************************************************************************************
// Set Primary key with ALTER TABLE COMMAND
**********************************************************************************************
// Create A Table with a Primary key
*********************************************************************************************
// Set Referencial Integrity [ Joining two tables ]
*********************************************************************************************
// Create a table with primary key and foreign key
***********************************************************************************************
// Droping a Constraint
*************************************************************************************************
// Droping a Column in a Table
***********************************************************************************************
// Create a Table with default value
131
CREATE TABLE _TEMP
(
empno int,
Query - Page #2
ename varchar(20),
city varchar(20) default ’cbe’
);
ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );
*****************************************************************************************
// Disabling Check constraint
******************************************************************************************
// Create a new table and copy only some particular fields of another Table
******************************************************************************************
//Create A Table and copy the data from another Table
******************************************************************************************
select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’
*********************************************************************************************
Grouping:
______________________________________________________________________________________
select type, sum(type) from titles; // Error
// Rule:
When ever you have aggregate function in the select list
along with some other fileds which are not enclosed with aggregate functions.
you should use group by functions.
_________________________________________________________________________________________
select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id d
sp_help titles
******************************************************************************************
// Select keywords
SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]
******************************************************************************************
SELECT *
FROM TITLES
ORDER BY TYPE DESC;
//////////////////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
group by type
order by title_id;
When ever use an order by class along with group by class the order by class should have
only those filels which are present in the group by class.
/////////////////////////////////////////////////////////////////////////////////////////////
select type,title_id,sum(price)
from titles
group by type
order by title_id; // Error
select type,title_id,sum(price)
from titles
group by type,title_id 133
order by title_id;
select sum(price)
from titles ; order by titles
select sum(price)
from titles
***********************************************************************
select type, count(*) from titles group by type having count(*)=3;
***********************************************************************
December 21 2001:
-----------------
Compute By class:
select type,price
from titles
order by type
compute sum(price) by type;
Whenever we use group by class or compute by class, the sql server builds Work Table....
In compute by class not able to generate Work Table automatically..but Group by class itself
able to generate Work Table...So the Compute by class relay order by class...
select type,price
from titles
order by pub_id
compute sum(price) by type; // Error
Reason:
The work table is built based on pub_id...In that work Table,we can’t find the sum of
price by Type...’
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type;
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by pub_id; // Error
Reason:
Work Table
Computer p2 200
Novel p1 200
Novel p1 240
Novel p2 450
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type,pub_id;
select type,pub_id,title_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id,title_id;
select type,pub_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id;
****************************************************
Afternoon:21-dec-2001
2...select type,pub_id
from titles
group by type,pub_id;
select type,pub_id
from titles
group by type,pub_id;
// In the above query.. The Distinct applies both type and pub_id columns..We can not make to apply
for a particular column. It will apply all the columns in the select list
For Ex
Business p1 200
Business p1 400
Business p1 300
Computer p2 500
Computer p2 700
The Result is
Business p1 200
Computer p2 500
/////////////////////////////////////////////////
select type,sum(price),avg(price)
from titles
group by price; // Error 135
Reason:
The field name in group by clause which is not used in aggregate function in select list
Query - Page #6
//////////////////////////////////////////////////////////
Having:
Having clause should have group by class...but when using group by class it is optional
to use Having clause.
1..select type,sum(price)
from titles
group by type
having type=’business’; // Grouped and followed by Filtered.......
2..select type,sum(price)
from titles
where type=’business’
group by type; // More Optimized: Fileterd and followed by Grouped...
All types of Records like Business,Computer and Novel and then take Business Records are Filtered
///////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select type,sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
/////////////////////////////////////////////////////////////////////////////////////////////////
December-26-2001
Joins: 136
if the select statement contains more table in from clause without where clause, it is called
cross joining which is never used...
select authors.au_id,authors.au_lname,authors.phone,
publishers.pub_id,publishers.pub_name,publishers.city
from authors,publishers
where authors.city = publishers.city;
select authors.*,pub_id,pub_name
from authors,publishers
where authors.city = publishers.city; // authors.* displays all fields in the Authors Table
Natural join:
The redundat field names are eliminated in the Result set
join
Equi Join :
The Redundat field names are present in the result set.
Table Alias:
select p.*,au_id,au_lname
from authors a, publishers p
where a.city = p.city and a.au_lname like ’c%’
select p.*,au_id,au_lname
from authors a, publishers p
where au_lname like ’c%’ and a.city = p.city
Question:
Find the publisher name for the book written by the author with fname ’Lorsley’
Answer:
select p.pub_name
from publishers p,authors a,titles t,titleauthor ta
where a.au_lname = ’Locksley’ and
a.au_id = ta.au_id and
ta.title_id = t.title_id and
t.pub_id = p.pub_id;
Explanation:
Title: Authors
au_id au_lname
----------- ----------------------------
a1 lockley
a2 peter
Table: Publisher
pub_id pub_name
------ -----------
p1 samy
p2 golgotia
p3 samba
Table: Titles
title_id pub_id
-------- --------
t1 p1
t2 p2
t3 p3
Table: TitleAuthor
au_id title_id
----------- --------
a1 t1
a1 t2
a2 t1
a2 t3
Virtual Tables:
[Authors] [TitleAuthor]
aid aname au_id title_id
a1 lockey a1 t1
a1 lockey a1 t2
FAQ:
Ans: The Query optimizer find out which join will be evaluated first and run the query
in the optimized way.... 138
Cross Checking:
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
December 28 2001:
.................................................................................................
Self Join:
The Table joins with itself...
Rule:
’When use self join in the where condition, you shoud use the in-equility condition
of the primary keys’
................................................................................................
Question:
Find the name of the authors who lives in the same city...
Explanation:
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
A1
A6
A2
A3
139
select a.au_id,a.city
from authors a, authors b
where a.city = b.city; // It displays duplicate Records
Query - Page #10
select state,count(*)
from authors
group by state
having count(*)>1 // We should not use group by function in the self joining situations
Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Question: Find the author id who has written more than one book???
Question: Find the title_id which has been written by more than one author?
Question: Find the author Names who has written more than one book???
Query - Page #11
Question: Find the titles which has been written by more than one author?
/////////////////////////////////////////////////////////////////////////////////////////////////
Jan 02 2002:
Outer join:
emp
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Anderw SYS
e5 Lafer null
dep
emp
eno
ename
d_id
dept
ddid
dname
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
e5 lafer 141
////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
Sub Query:
A query with in query is called sub query...
Note: All joins can be formulated with sub query but all sub query can not be
formulated with joins
Question : Find the name and title of the most expensive book???
declare @p float;
select @p = max(price) from titles;
select @p;
select * from titles where price = @p;
Jan-04-2002:
Exists:
Rule: Exsits has the rule that no filed name in the where clause.
...............................................................................................
Simple Query: All the select statements are evaluated in the bottom up.
Correlated SubQuery:
1. The Correlated subquery will always have the join inside..[but just because
the join inside the subquery it does not make correlated subquery.]
Example:
select cid from orders where customers.id=orders.id, This query will return olny true or false.
The inner query is executed as many times the outer query depends....it means that the inner
query depends the value of outer query...
--------------------------------------------------------------------------------------------------------
7-01-2002:
Any self join can be carried out through correlated sub query.
select a.au_fname
from authors a
where exists ( select b.au_id
from authors b
where a.state = b.state and
a.au_id <> b.au_id ); // This is correlated sub query 1.It has join.
2.The left or right side field name is oute
The correlated sub query executed for every outer table row...but simple sub query executed only once...
It takes one record from the outer condition for that row all the rows of the inner codition will be exec
If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct
the correlated sub query.
---------------------------------------------------------------------------------------------------------
Union:
select * from authors union select * from sen_temp_table; // It will not give the duplicates of the re
if u want to include the duplicates use Union all keyword...
select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ
select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mis
Note: The order by statements can not be used in the individual query inside
the union but group by and having is allowed.
But order by allowed in the outside of the union .
Example:
select title_id,title from titles union all select title_id,au_id from titleauthor o
Note: The field name in the first select statement is allowed in the order by clause.
we can not use group by clause in the order by place....
---------------------------------------------------------------------------------------------------------
Self-Interest:
Ans:
drop vi
create view v_sample as
select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p
where o.proid=p.pid group by o.cuid 143
Ans:
select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p
where o.proid=p.pid group by o.cuid;
---------------------------------------------------------------------------------------------------------
11-01-2002:
Syntax:
Grant select|update|insert|delete on Table_name to User
Grant All Table_name to User
Revoke select|update|insert|delete on Table_name from User
Revoke All Table_name from User
View:
The View is the Projection of the base tables...
Syntax:
Create View view_name
as
select statement
Step 1:
create view sen_view_v1
as
select * from titles where title_id=’BU1111’
Step 2:
select * from sen_view_v1; // The select statement inside the view will be executed....
delete sen_view_v1;
*************************************************************************************************
16-January-2002:
Ex:
create view v1 as
select.....
Create view v2 as
select pub_id,sum(price) from titles group by pub_id; // The above statement would not work.
Here the sum(price) is tried to derive a new column in the view
create view v2 as
select 144 by pub_id
pub_id,sum(price) as "Total" from titles group
(or)
create view v2(publishers_id,price) as
select pub_id,sum(price) as "Total" from titles group by pub_id
Query - Page #15
//////////////////////////////////////////////////////////////////////////////////////////////
Rule:
1. We can not use order by,compute by,compute in the selection list while creating views.
2. We can not use ’Select into’ on views.
3. We can use order by indirectly.
//////////////////////////////////////////////////////////////////////////////////////////////
create view v1 as
select emp_no,emp_name,dept_id,phone from emp; // It would not work...
create view v1 as
select * form emp; // It will work
Rule 1:
The view has to contain all not null columns,[it will become updateable view] then olny
it is possible insert,update,delete, If the view does not contain all not null columns,
it is only readable veiw.We can not do insert,delete,update...
Rule 2:
If the select list in the view contains aggregate functions,the view is readable view...
create view v1 as
select emp_no,emp_name,emp.dept_id,phone,salary,dept_name from emp,dept
where emp.dept_id=dept.dept_id;
Rule 3:
In above statement, the insert is possible only if all the columns are in the same table
in the insert statememt. The insert will not work the columns are in different table...
////////////////////////////////////////////////////////////////////////////////////////////////
select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS
find whether it is table or view...if it is view, it executes the select statement with where
condition. And the statement looks like below....
Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpreted
as below....
Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....
insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view has
been created by with check option condition. It allow only the where clause condition is match, it
means that we can insert only ’HRD’ type......
/////////////////////////////////////////////////////////////////////////////////////////////////
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
17-January-2002:
Transact-SQL:
Transact-SQL is procedure oriented language
Stored Procedure:
Batch of sql statemets kept compiled in the server and ready for the execution.
In stored procedure,the return statement can return only int value,but we can return more
than one value by using output parameter concept.
Whatever variable used in sql server, these variable should begin with @ symbol. By default,
all parameters are input parameters.All system defined procedure is preceeded with sp...
The created procedure have an entry in sysobjects table.....The statements are used in procedure
will be stored in syscomments table.
Exec pro // while creating procudure, it checks only the syntax, while executing, the compilation
process is done..
select object_id (’demo’); // we can get the table id what the sql server maintains...
//////////////////////////////////////////////////////////////////////////////////////////////
what is Query plan????
The query plan is nothing but the path of the execution in the sql statements...
Exec pro;
The step 1 and step 2 will be executed at the first execution of the procedure..if u execute
the procedure another time, it will no go for compilation process,it just checks the procedure
Query - Page #17
cache and execute suitable obj file....If the system is gone for shut down, the contents of the
procedure cache will be deleted....Whatever changes made in table contents, it will re-complile.
if the table is dropped,the procedure for the table will not be deleted...
//////////////////////////////////////////////////////////////////////////////////////////////
18-January-2002:
if(@price <=100)
return 1;
if(@price>100 and @price<=200)
return 2;
if(@price >200)
return 3;
-------------------------------------
if @ret = 2
begin
select "Return 2";
end
if @ret = 3
begin
select "Return 3";
end
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Example:
Example
Query - Page #18
19-01-2002:
Output Parameters:
Question: Write the procedure to find the city and state of the given publishers????
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names ( use while loop )
------------------------------------------------------------------------------------------------
Goto Statement Example:
21-January-2002:
E-R Diagram:
Entity: 148
The entity is an object about information can be recorded..
Query - Page #19
For example, the employee and dept entity has some relationship between them...
1. One to One
2. One to Many
3. Many to Many
{Chen notation}
Employee has one to one relationship with Dept ( one employee has to work in only one dept)
Dept has one to many relationship with Employee ( one dept has many employees)
so we depict one to many relationship with these two entites....( one to one[left to right] and
one to many[right to left] realationship comes either side,Take a one to many relationship...)
For ex:
1.(emp)one instance of employee has how many instances of dept...(0,1){(min,max)}
(dept)one instance of dept has how many instances of employee...(0,M)
emp has a existence dependent with dept ( dept has to created before emp...)
Existence Dependent: It means that with out having a entry in dept table,the emp id can not
have an dept id ( Foreign key rules apply here..)
One professor can guide many students...[one to many relationship in left to right] in some
cases the one professor not giving guidence to any students....
One Student can get advise from one professor [one to one relationship in right to left]
one professor can have zero or one room [ one to one left to rigth ]
one room is allotted to zero or one professor [ one to one right to left ]
The oracle and sql server can not support for many to many relationship....For these cases
we have to split the relationship into two one to many relationship...
one author can write many books [ one to Many left to rigth ]
one title is written by many authors [ one to Many right to left ]
-------------------------------------------------------------------------------------------------
Note: The calculated field(derived attribute) should not be stored in the database..For example
the age can be calculated with date-of-birth.....
-------------------------------------------------------------------------------------------------
25-jan-2002:
Normalization:
Segregating tables as to avoid redundancy...
DeNormalization:
introducing redundancy into tables to make more optimization or more performance the
Any database desin normally will not go beyond the third normal form....
Atomic values:
A field should record about the single attribute...
For example: To store address,we have to put street,city,state,country as a separate field names.
Then only possible to search the employees by city,state or country.....
(*) The field names shoud accept null values, if the no specefic info for that recor
and take to consideration the table should not have more null value fields.
Example:
---------------------------------------------------------------------------------------------------------
All the non key attributes should depend upon whole primary key or all the non key attributes
may depend on other non key attributes...
In the above table, the department id is partially belonging to the primary key,which means that the emp
itself only need to identify the department id and the project id is no longer needed...
*In order conform second normal form,we have take out the non key attribute which does not depend entril
the primary key and put it separate table along with the field on which the non key attribute is depen
eid did
---------
Query - Page #21
e1 IS
e2 IS
e3 NET
24 NET
nohrs is partially depend on primary key,which means the nohrs dependent on only project id...
pid nohrs
-----------
p1 20
p2 30 ( It is in third normal form,we can not split it again)
The dehead is not related to eid or pid...it is related to did.....so put dhead following table
---------------------------------------------------------------------------------------------------------
Third Normal Form:
All the non key attributes should be dependent only on the primary key
In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only th
did which is not a primary key of the table....
did dhead
--------------
IS boris
NET peter
---------------------------------------------------------------------------------------------------------
*************************************************************************************************
29-jan-2002:
Triggers:
Trigger is a stored procedure, it will be invoked automatically upon user action
(Insert,Update,Delete).
Cascade deletions:
The child table refers some field in the master table...We can not delete
any enty in the master table,which is refered by in the child table...The SQL server maintains
restrictions automatically...The cascade deletions is opposite of these restrictions....
Syntax:
The trigger can be depend on only one table...and the trigger can not defined on the views...
151 Trigger,Delete Trigger) These are all after
only three types of triggers ( Insert Trigger,Update
trigger,The SQL could not support Before Triggers.....
Book Magazine
----------------------------
Bid Magid
Bname Mname
Author price
Transaction
--------------
Tid
Card_id
book_id
issue_date
return_date
--------------------------------------------------------------------------------------------------
Implementing primary key constraint:-
emp inserted
----------------------------------------------------
e1 boris d1 d1 HRD
e2 becker d2 d2 SYS
e3 sapeg d3
-------------------------------------------------------------------------------------------------
Implementing foreign key constraint:-
-------------------------------------------------------------------------------------------------
Note:
While creating trigger,the object should be exist on which the trigger imposed...but it
does not check the body of the statements....
-------------------------------------------------------------------------------------------------
Implementing Cascade Deletion:-
The value from Trigger table is moved into Trigger Test Table (Deleted Table)
-------------------------------------------------------------------------------------------------
Implementing Restriction on deletion:-
------------------------------------------------------------------------------------------------
Question:
Create a trigger to move the deleted records to that respective back_up tables?????
Hits provided:
declare @i int
select @i=Object_id(’publishers’)
------------------------------------------------------------------------------------------------
31-JAN-2002:
-------------------------------------------------------------------------------------------
Note: The rollback command will only work on triggers it will not work on procedures....
--------------------------------------------------------------------------------------------
Note: Through the delete and update command will affect many rows.., the trigger will be
executed for each row...
---------------------------------------------------------------------------------------------
create trigger tri
on invoice
for update
if update(oid) // if the user tries to update field oid it will return true
begin or it will retun false
rollback
return
end
if not exists (select * from products,inserted
where inserted.productid=products.proudctid
begin
print ’Fk violation on products’
rollback
return
end
--------------------------------------------------------------------------------------------
Note: For update triggers, the inserted and deleted virutal table will be created....
deleted followed by inserted...................
--------------------------------------------------------------------------------------------
TSQL Cursors:
The main application of cursors is ’report’ generation..........
1....Declare
2....Open
3....Fetch
4....Close
5....Deallocate
A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’..
1...Declare:
Syntax:
Declare cursorname cursor
for
select statement
Note: It check the existence of the object but it would not compile and execute
-------------------------------------------------------------------------------------------------
2...Open:
Open cur; // Opening a cursor
Note: The select statement is executed and the resultset is stored inside the memory
-------------------------------------------------------------------------------------------------
3....Fetch:
Fetch next from cur;
Fetch prior from cur;
Fetch first from cur;
Fetch last from cur;
Note: It goes and bring the records one by one from the resultset which is stored in the memory
The logical pointer is pointed bof at first time....
-------------------------------------------------------------------------------------------------
4.....Close:
Close cur;
exec sen_cur_pro;
Note: @@fetch_status is system defined global variable which is automatically set to 0 which
indicates for successful fetch...
------------------------------------------------------------------------------------------------
1-02-2002:
Application of Cursors:
exec sen_cpro
Note: The Compute by clause should not be used in the select stattement along with cursor....
The Compute by clause should not be used in the select stattement along with subquery...
We can use order by and group by clause in the select statement along with cursor......
------------------------------------------------------------------------------------------------
Question : Write the procedure to display all book which is published by each publisher in neat format???
open tcur
fetch next from tcur into @tid,@title,@price
while(@@fetch_status=0)
begin
print @tid + " " + @title + " " + convert(varchar,@price)
fetch next from tcur into @tid,@title,@price
end
close tcur
deallocate tcur
end
print ’------------------------------------------------’
fetch next from cur into @pid,@pname
end
close cur
deallocate cur
exec sen_publisher_books
---------------------------------------------------------------------------------------------------------
2-Feb-2002:
Indexing:
It is a sorting process to reduce the searching process time....
Syntax:
The field on which indexed is sorted in ascending order and build binary tree....
It take the first value and any middle arbitary value
------------------------------------------------------------------------------------------------
Note: Through the index is created, the optimizer will decide wheter to use index is feasible or
it is feasible for going for table scan......
--------------------------------------------------------------------------------------------------
Note: Primary key creates Clustered automaically but to make it nonClustered index is more
feasible than Clustered index
--------------------------------------------------------------------------------------------
Clustered:
-----------------------------------------------------------------------------------------------
Note: The clustered index points the page...but the nonclustered index points the exact match of
record...
156
Query - Page #1
------------------------------------------------------------------------------------------------
LIBRARY
------------------------------------------------------------------------------------------------
Project Specification:
Altair is a library renowned for its latest collection of books and
magazines.The number of members is increasing every month and it is becoming difficult to keep
track of so many members and transactions,which are currently maintained in registers. The chief
librarian approaches you to seek help for designing a computerized system. All members in the
library are given two member cards and one book is leased for each card. The membership fee for
each member is Rs 500. One time payment,refundable on relinquishing of the cards.Both books and
megazines are leased to the members.A book lent to a member can be with him for 15 days at most
and an extension of another 15 days is given to the member for that particular book if that book
is brought for renewal on the 15 th day after it is lent.The same member is not allowed to have
the book for another 15 days after it is returned.Magazines are lent only for 4 days and no
extension is allowed and there is no restriction for lending the magazine to the same member,as is
the case with books.
You need to store the book details for each book ( publisher name,title,author and the like ).
Each book is identified by a unique title number.Magazines are identified in the following format.
Each magazine has a short hand notation (Eg. otlk for the magazine outlook) To identify a particular
magazine the short hand notation is used along with the month and year of issue Eg. otlk-jan-1999
identifies Outlook magazine jan issue of 1999. You need to store the number of copies of each book
that is there in the library. One copy of each book is designated as reference and it is not lent
to any member.
-------------------------------------------------------------------------------------------------
Create Table sen_catlog
(
c_id varchar(10) constraint sc_pk primary key,
title varchar(20),
author varchar(20),
publisher varchar(20),
price float
);
157
insert into sen_catlog values(’CB001’,’C’,’Dennis Ritche’,’Tech Media’,140.25);
insert into sen_catlog values(’CB002’,’C++’,’Robert Rafore’,’BPB Publication’,356.90);
insert into sen_catlog values(’CB003’,’JAVA’,’Balaguru swamy’,’Tech Media’,230);
Query - Page #2
set nocount on
---------------------------------------------------------------------------------------------------------
1. For each book you will have to generate the members to whom copies of it have been lent....
end
end
exec sen_books_issue
---------------------------------------------------------------------------------------------------------
2.Generate a report which displays all the books. You will have to include all the relevant information i
exec sen_books_details;
---------------------------------------------------------------------------------------------------------
3.On any particular day you will have to generate a report which will produce the details of all
books that are to be delivered on that particular day...
if(@r is null)
set @message=’Not Returned’
else
set @message=’Returned’
print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid + " " + @message
end
end
159
exec sen_book_delevered @ddate=’2000-01-28’;
-----------------------------------------------------------------------------------------------
4.On any particular day you will have to display as report those books for which due date has
Query - Page #4
select @dday=DATEADD(day,-15,@date)
select @n=count(b_id)from sen_transaction where rdate is null and tdate<@dday
if(@n=0)
print ’No Over due books on that day’
else
begin
select b_id,card_id into #temp from sen_transaction where rdate is null and tdate<@dday
select @i = 1
while(@i<=@n)
begin
select top 1 @b=b_id,@c=card_id from #temp
select distinct @t_title=c.title,@t_bid=b.b_id from sen_catlog c,sen_books b,sen_transaction t
where t.b_id=@b and t.b_id=b.b_id and b.c_id = c.c_id
select distinct @t_name=m.mname,@t_card=c.card_id from sen_transaction t,sen_cards c,sen_member m
where t.card_id=@c and t.card_id=c.card_id and c.m_id=m.m_id
delete from #temp where card_id=@c and b_id=@b
select @i=@i+1
print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid
end
end
-------------------------------------------------------------------------------------------------
160
Query - Page #1
************************************************************************************************
// Set Primary key with ALTER TABLE COMMAND
**********************************************************************************************
// Create A Table with a Primary key
*********************************************************************************************
// Set Referencial Integrity [ Joining two tables ]
*********************************************************************************************
// Create a table with primary key and foreign key
***********************************************************************************************
// Droping a Constraint
*************************************************************************************************
// Droping a Column in a Table
***********************************************************************************************
// Create a Table with default value
ename varchar(20),
city varchar(20) default ’cbe’
);
ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );
*****************************************************************************************
// Disabling Check constraint
******************************************************************************************
// Create a new table and copy only some particular fields of another Table
******************************************************************************************
//Create A Table and copy the data from another Table
******************************************************************************************
select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’
*********************************************************************************************
Grouping:
______________________________________________________________________________________
select type, sum(type) from titles; // Error
// Rule:
When ever you have aggregate function in the select list
along with some other fileds which are not enclosed with aggregate functions.
you should use group by functions.
_________________________________________________________________________________________
select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id d
sp_help titles
******************************************************************************************
// Select keywords
SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]
******************************************************************************************
SELECT *
FROM TITLES
ORDER BY TYPE DESC;
//////////////////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
group by type
order by title_id;
When ever use an order by class along with group by class the order by class should have
only those filels which are present in the group by class.
/////////////////////////////////////////////////////////////////////////////////////////////
select type,title_id,sum(price)
from titles
group by type
order by title_id; // Error
select type,title_id,sum(price)
from titles
group by type,title_id
order by title_id;
select sum(price)
from titles ; order by titles
select sum(price)
from titles
***********************************************************************
select type, count(*) from titles group by type having count(*)=3;
***********************************************************************
December 21 2001:
-----------------
Compute By class:
select type,price
from titles
order by type
compute sum(price) by type;
Whenever we use group by class or compute by class, the sql server builds Work Table....
In compute by class not able to generate Work Table automatically..but Group by class itself
able to generate Work Table...So the Compute by class relay order by class...
select type,price
from titles
order by pub_id
compute sum(price) by type; // Error
Reason:
The work table is built based on pub_id...In that work Table,we can’t find the sum of
price by Type...’
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type;
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by pub_id; // Error
Reason:
Work Table
Computer p2 200
Novel p1 200
Novel p1 240
Novel p2 450
select type,pub_id,price
from titles
order by type,pub_id
compute sum(price) by type,pub_id;
select type,pub_id,title_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id,title_id;
select type,pub_id,price
from titles
order by type,pub_id,title_id
compute sum(price) by type,pub_id;
****************************************************
Afternoon:21-dec-2001
2...select type,pub_id
from titles
group by type,pub_id;
select type,pub_id
from titles
group by type,pub_id;
// In the above query.. The Distinct applies both type and pub_id columns..We can not make to apply
for a particular column. It will apply all the columns in the select list
For Ex
Business p1 200
Business p1 400
Business p1 300
Computer p2 500
Computer p2 700
The Result is
Business p1 200
Computer p2 500
/////////////////////////////////////////////////
select type,sum(price),avg(price)
from titles
group by price; // Error
Reason:
The field name in group by clause which is not used in aggregate function in select list
Query - Page #6
//////////////////////////////////////////////////////////
Having:
Having clause should have group by class...but when using group by class it is optional
to use Having clause.
1..select type,sum(price)
from titles
group by type
having type=’business’; // Grouped and followed by Filtered.......
2..select type,sum(price)
from titles
where type=’business’
group by type; // More Optimized: Fileterd and followed by Grouped...
All types of Records like Business,Computer and Novel and then take Business Records are Filtered
///////////////////////////////////////////////////////////////////////////////
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
select type,sum(price)
from titles
where sum(price) > 1000
group by type; // Error Rule 1 and 2
select type,sum(price)
from titles
where 1000<sum(price)
group by type; // Error Rule 2
/////////////////////////////////////////////////////////////////////////////////////////////////
December-26-2001
Joins:
if the select statement contains more table in from clause without where clause, it is called
cross joining which is never used...
select authors.au_id,authors.au_lname,authors.phone,
publishers.pub_id,publishers.pub_name,publishers.city
from authors,publishers
where authors.city = publishers.city;
select authors.*,pub_id,pub_name
from authors,publishers
where authors.city = publishers.city; // authors.* displays all fields in the Authors Table
Natural join:
The redundat field names are eliminated in the Result set
join
Equi Join :
The Redundat field names are present in the result set.
Table Alias:
select p.*,au_id,au_lname
from authors a, publishers p
where a.city = p.city and a.au_lname like ’c%’
select p.*,au_id,au_lname
from authors a, publishers p
where au_lname like ’c%’ and a.city = p.city
Question:
Find the publisher name for the book written by the author with fname ’Lorsley’
Answer:
select p.pub_name
from publishers p,authors a,titles t,titleauthor ta
where a.au_lname = ’Locksley’ and
a.au_id = ta.au_id and
ta.title_id = t.title_id and
t.pub_id = p.pub_id;
December 27 2001:
.................
Query - Page #8
Explanation:
Title: Authors
au_id au_lname
----------- ----------------------------
a1 lockley
a2 peter
Table: Publisher
pub_id pub_name
------ -----------
p1 samy
p2 golgotia
p3 samba
Table: Titles
title_id pub_id
-------- --------
t1 p1
t2 p2
t3 p3
Table: TitleAuthor
au_id title_id
----------- --------
a1 t1
a1 t2
a2 t1
a2 t3
Virtual Tables:
[Authors] [TitleAuthor]
aid aname au_id title_id
a1 lockey a1 t1
a1 lockey a1 t2
FAQ:
Ans: The Query optimizer find out which join will be evaluated first and run the query
in the optimized way....
Cross Checking:
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
December 28 2001:
.................................................................................................
Self Join:
The Table joins with itself...
Rule:
’When use self join in the where condition, you shoud use the in-equility condition
of the primary keys’
................................................................................................
Question:
Find the name of the authors who lives in the same city...
Explanation:
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
au_id city
A1 CA
A2 LA
A3 LA
A4 WA
A5 Ny
A6 CA
A1
A6
A2
A3
select a.au_id,a.city
from authors a, authors b
where a.city = b.city; // It displays duplicate Records
Query - Page #10
select state,count(*)
from authors
group by state
having count(*)>1 // We should not use group by function in the self joining situations
Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Question: Find the author id who has written more than one book???
Question: Find the title_id which has been written by more than one author?
Question: Find the author Names who has written more than one book???
Query - Page #11
Question: Find the titles which has been written by more than one author?
/////////////////////////////////////////////////////////////////////////////////////////////////
Jan 02 2002:
Outer join:
emp
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Anderw SYS
e5 Lafer null
dep
emp
eno
ename
d_id
dept
ddid
dname
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
REsult Set
e1 boris HRD
e2 becker HRD
e3 peter SYS
e4 Andrew SYS
e5 lafer
////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
Sub Query:
A query with in query is called sub query...
Note: All joins can be formulated with sub query but all sub query can not be
formulated with joins
Question : Find the name and title of the most expensive book???
declare @p float;
select @p = max(price) from titles;
select @p;
select * from titles where price = @p;
Jan-04-2002:
Exists:
Rule: Exsits has the rule that no filed name in the where clause.
...............................................................................................
Simple Query: All the select statements are evaluated in the bottom up.
Correlated SubQuery:
1. The Correlated subquery will always have the join inside..[but just because
the join inside the subquery it does not make correlated subquery.]
Example:
select cid from orders where customers.id=orders.id, This query will return olny true or false.
The inner query is executed as many times the outer query depends....it means that the inner
query depends the value of outer query...
--------------------------------------------------------------------------------------------------------
7-01-2002:
Any self join can be carried out through correlated sub query.
select a.au_fname
from authors a
where exists ( select b.au_id
from authors b
where a.state = b.state and
a.au_id <> b.au_id ); // This is correlated sub query 1.It has join.
2.The left or right side field name is oute
The correlated sub query executed for every outer table row...but simple sub query executed only once...
It takes one record from the outer condition for that row all the rows of the inner codition will be exec
If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct
the correlated sub query.
---------------------------------------------------------------------------------------------------------
Union:
select * from authors union select * from sen_temp_table; // It will not give the duplicates of the re
if u want to include the duplicates use Union all keyword...
select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ
select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mis
Note: The order by statements can not be used in the individual query inside
the union but group by and having is allowed.
But order by allowed in the outside of the union .
Example:
select title_id,title from titles union all select title_id,au_id from titleauthor o
Note: The field name in the first select statement is allowed in the order by clause.
we can not use group by clause in the order by place....
---------------------------------------------------------------------------------------------------------
Self-Interest:
Ans:
drop vi
create view v_sample as
select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p
where o.proid=p.pid group by o.cuid
Ans:
select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p
where o.proid=p.pid group by o.cuid;
---------------------------------------------------------------------------------------------------------
11-01-2002:
Syntax:
Grant select|update|insert|delete on Table_name to User
Grant All Table_name to User
Revoke select|update|insert|delete on Table_name from User
Revoke All Table_name from User
View:
The View is the Projection of the base tables...
Syntax:
Create View view_name
as
select statement
Step 1:
create view sen_view_v1
as
select * from titles where title_id=’BU1111’
Step 2:
select * from sen_view_v1; // The select statement inside the view will be executed....
delete sen_view_v1;
*************************************************************************************************
16-January-2002:
Ex:
create view v1 as
select.....
Create view v2 as
select pub_id,sum(price) from titles group by pub_id; // The above statement would not work.
Here the sum(price) is tried to derive a new column in the view
create view v2 as
select pub_id,sum(price) as "Total" from titles group by pub_id
(or)
create view v2(publishers_id,price) as
select pub_id,sum(price) as "Total" from titles group by pub_id
Query - Page #15
//////////////////////////////////////////////////////////////////////////////////////////////
Rule:
1. We can not use order by,compute by,compute in the selection list while creating views.
2. We can not use ’Select into’ on views.
3. We can use order by indirectly.
//////////////////////////////////////////////////////////////////////////////////////////////
create view v1 as
select emp_no,emp_name,dept_id,phone from emp; // It would not work...
create view v1 as
select * form emp; // It will work
Rule 1:
The view has to contain all not null columns,[it will become updateable view] then olny
it is possible insert,update,delete, If the view does not contain all not null columns,
it is only readable veiw.We can not do insert,delete,update...
Rule 2:
If the select list in the view contains aggregate functions,the view is readable view...
create view v1 as
select emp_no,emp_name,emp.dept_id,phone,salary,dept_name from emp,dept
where emp.dept_id=dept.dept_id;
Rule 3:
In above statement, the insert is possible only if all the columns are in the same table
in the insert statememt. The insert will not work the columns are in different table...
////////////////////////////////////////////////////////////////////////////////////////////////
select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS
find whether it is table or view...if it is view, it executes the select statement with where
condition. And the statement looks like below....
Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpreted
as below....
Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....
insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view has
been created by with check option condition. It allow only the where clause condition is match, it
means that we can insert only ’HRD’ type......
/////////////////////////////////////////////////////////////////////////////////////////////////
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
17-January-2002:
Transact-SQL:
Transact-SQL is procedure oriented language
Stored Procedure:
Batch of sql statemets kept compiled in the server and ready for the execution.
In stored procedure,the return statement can return only int value,but we can return more
than one value by using output parameter concept.
Whatever variable used in sql server, these variable should begin with @ symbol. By default,
all parameters are input parameters.All system defined procedure is preceeded with sp...
The created procedure have an entry in sysobjects table.....The statements are used in procedure
will be stored in syscomments table.
Exec pro // while creating procudure, it checks only the syntax, while executing, the compilation
process is done..
select object_id (’demo’); // we can get the table id what the sql server maintains...
//////////////////////////////////////////////////////////////////////////////////////////////
what is Query plan????
The query plan is nothing but the path of the execution in the sql statements...
Exec pro;
The step 1 and step 2 will be executed at the first execution of the procedure..if u execute
the procedure another time, it will no go for compilation process,it just checks the procedure
Query - Page #17
cache and execute suitable obj file....If the system is gone for shut down, the contents of the
procedure cache will be deleted....Whatever changes made in table contents, it will re-complile.
if the table is dropped,the procedure for the table will not be deleted...
//////////////////////////////////////////////////////////////////////////////////////////////
18-January-2002:
if(@price <=100)
return 1;
if(@price>100 and @price<=200)
return 2;
if(@price >200)
return 3;
-------------------------------------
if @ret = 2
begin
select "Return 2";
end
if @ret = 3
begin
select "Return 3";
end
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Example:
Example
Query - Page #18
19-01-2002:
Output Parameters:
Question: Write the procedure to find the city and state of the given publishers????
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names
Question: Write a procedure to check the given title_id has been written 2 authors,
if so print the 2 author names ( use while loop )
------------------------------------------------------------------------------------------------
Goto Statement Example:
21-January-2002:
E-R Diagram:
Entity:
The entity is an object about information can be recorded..
Query - Page #19
For example, the employee and dept entity has some relationship between them...
1. One to One
2. One to Many
3. Many to Many
{Chen notation}
Employee has one to one relationship with Dept ( one employee has to work in only one dept)
Dept has one to many relationship with Employee ( one dept has many employees)
so we depict one to many relationship with these two entites....( one to one[left to right] and
one to many[right to left] realationship comes either side,Take a one to many relationship...)
For ex:
1.(emp)one instance of employee has how many instances of dept...(0,1){(min,max)}
(dept)one instance of dept has how many instances of employee...(0,M)
emp has a existence dependent with dept ( dept has to created before emp...)
Existence Dependent: It means that with out having a entry in dept table,the emp id can not
have an dept id ( Foreign key rules apply here..)
One professor can guide many students...[one to many relationship in left to right] in some
cases the one professor not giving guidence to any students....
One Student can get advise from one professor [one to one relationship in right to left]
one professor can have zero or one room [ one to one left to rigth ]
one room is allotted to zero or one professor [ one to one right to left ]
one theatre can show many films [ one to Many left to rigth ]
one film is shown in many theatres [ one to Many right to left ]
Query - Page #20
The oracle and sql server can not support for many to many relationship....For these cases
we have to split the relationship into two one to many relationship...
one author can write many books [ one to Many left to rigth ]
one title is written by many authors [ one to Many right to left ]
-------------------------------------------------------------------------------------------------
Note: The calculated field(derived attribute) should not be stored in the database..For example
the age can be calculated with date-of-birth.....
-------------------------------------------------------------------------------------------------
25-jan-2002:
Normalization:
Segregating tables as to avoid redundancy...
DeNormalization:
introducing redundancy into tables to make more optimization or more performance the
Any database desin normally will not go beyond the third normal form....
Atomic values:
A field should record about the single attribute...
For example: To store address,we have to put street,city,state,country as a separate field names.
Then only possible to search the employees by city,state or country.....
(*) The field names shoud accept null values, if the no specefic info for that recor
and take to consideration the table should not have more null value fields.
Example:
---------------------------------------------------------------------------------------------------------
All the non key attributes should depend upon whole primary key or all the non key attributes
may depend on other non key attributes...
In the above table, the department id is partially belonging to the primary key,which means that the emp
itself only need to identify the department id and the project id is no longer needed...
*In order conform second normal form,we have take out the non key attribute which does not depend entril
the primary key and put it separate table along with the field on which the non key attribute is depen
eid did
---------
Query - Page #21
e1 IS
e2 IS
e3 NET
24 NET
nohrs is partially depend on primary key,which means the nohrs dependent on only project id...
pid nohrs
-----------
p1 20
p2 30 ( It is in third normal form,we can not split it again)
The dehead is not related to eid or pid...it is related to did.....so put dhead following table
---------------------------------------------------------------------------------------------------------
Third Normal Form:
All the non key attributes should be dependent only on the primary key
In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only th
did which is not a primary key of the table....
did dhead
--------------
IS boris
NET peter
---------------------------------------------------------------------------------------------------------
*************************************************************************************************
29-jan-2002:
Triggers:
Trigger is a stored procedure, it will be invoked automatically upon user action
(Insert,Update,Delete).
Cascade deletions:
The child table refers some field in the master table...We can not delete
any enty in the master table,which is refered by in the child table...The SQL server maintains
restrictions automatically...The cascade deletions is opposite of these restrictions....
Syntax:
The trigger can be depend on only one table...and the trigger can not defined on the views...
only three types of triggers ( Insert Trigger,Update Trigger,Delete Trigger) These are all after
trigger,The SQL could not support Before Triggers.....
Book Magazine
----------------------------
Bid Magid
Bname Mname
Author price
Transaction
--------------
Tid
Card_id
book_id
issue_date
return_date
--------------------------------------------------------------------------------------------------
Implementing primary key constraint:-
emp inserted
----------------------------------------------------
e1 boris d1 d1 HRD
e2 becker d2 d2 SYS
e3 sapeg d3
-------------------------------------------------------------------------------------------------
Implementing foreign key constraint:-
-------------------------------------------------------------------------------------------------
Note:
While creating trigger,the object should be exist on which the trigger imposed...but it
does not check the body of the statements....
-------------------------------------------------------------------------------------------------
Implementing Cascade Deletion:-
The value from Trigger table is moved into Trigger Test Table (Deleted Table)
-------------------------------------------------------------------------------------------------
Implementing Restriction on deletion:-
------------------------------------------------------------------------------------------------
Question:
Create a trigger to move the deleted records to that respective back_up tables?????
Hits provided:
declare @i int
select @i=Object_id(’publishers’)
------------------------------------------------------------------------------------------------
31-JAN-2002:
-------------------------------------------------------------------------------------------
Note: The rollback command will only work on triggers it will not work on procedures....
--------------------------------------------------------------------------------------------
Note: Through the delete and update command will affect many rows.., the trigger will be
executed for each row...
---------------------------------------------------------------------------------------------
create trigger tri
on invoice
for update
if update(oid) // if the user tries to update field oid it will return true
begin or it will retun false
rollback
return
end
if not exists (select * from products,inserted
where inserted.productid=products.proudctid
begin
print ’Fk violation on products’
rollback
return
end
--------------------------------------------------------------------------------------------
Note: For update triggers, the inserted and deleted virutal table will be created....
deleted followed by inserted...................
--------------------------------------------------------------------------------------------
TSQL Cursors:
The main application of cursors is ’report’ generation..........
1....Declare
2....Open
3....Fetch
4....Close
5....Deallocate
A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’..
1...Declare:
Syntax:
Declare cursorname cursor
for
select statement
Note: It check the existence of the object but it would not compile and execute
-------------------------------------------------------------------------------------------------
2...Open:
Open cur; // Opening a cursor
Note: The select statement is executed and the resultset is stored inside the memory
-------------------------------------------------------------------------------------------------
3....Fetch:
Fetch next from cur;
Fetch prior from cur;
Fetch first from cur;
Fetch last from cur;
Note: It goes and bring the records one by one from the resultset which is stored in the memory
The logical pointer is pointed bof at first time....
-------------------------------------------------------------------------------------------------
4.....Close:
Close cur;
exec sen_cur_pro;
Note: @@fetch_status is system defined global variable which is automatically set to 0 which
indicates for successful fetch...
------------------------------------------------------------------------------------------------
1-02-2002:
Application of Cursors:
exec sen_cpro
Note: The Compute by clause should not be used in the select stattement along with cursor....
The Compute by clause should not be used in the select stattement along with subquery...
We can use order by and group by clause in the select statement along with cursor......
------------------------------------------------------------------------------------------------
Question : Write the procedure to display all book which is published by each publisher in neat format???
open tcur
fetch next from tcur into @tid,@title,@price
while(@@fetch_status=0)
begin
print @tid + " " + @title + " " + convert(varchar,@price)
fetch next from tcur into @tid,@title,@price
end
close tcur
deallocate tcur
end
print ’------------------------------------------------’
fetch next from cur into @pid,@pname
end
close cur
deallocate cur
exec sen_publisher_books
---------------------------------------------------------------------------------------------------------
2-Feb-2002:
Indexing:
It is a sorting process to reduce the searching process time....
Syntax:
The field on which indexed is sorted in ascending order and build binary tree....
It take the first value and any middle arbitary value
------------------------------------------------------------------------------------------------
Note: Through the index is created, the optimizer will decide wheter to use index is feasible or
it is feasible for going for table scan......
--------------------------------------------------------------------------------------------------
Note: Primary key creates Clustered automaically but to make it nonClustered index is more
feasible than Clustered index
--------------------------------------------------------------------------------------------
Clustered:
-----------------------------------------------------------------------------------------------
Note: The clustered index points the page...but the nonclustered index points the exact match of
record...
------------------------------------------------------------------------------------------------
LIBRARY
------------------------------------------------------------------------------------------------
Project Specification:
Altair is a library renowned for its latest collection of books and
magazines.The number of members is increasing every month and it is becoming difficult to keep
track of so many members and transactions,which are currently maintained in registers. The chief
librarian approaches you to seek help for designing a computerized system. All members in the
library are given two member cards and one book is leased for each card. The membership fee for
each member is Rs 500. One time payment,refundable on relinquishing of the cards.Both books and
megazines are leased to the members.A book lent to a member can be with him for 15 days at most
and an extension of another 15 days is given to the member for that particular book if that book
is brought for renewal on the 15 th day after it is lent.The same member is not allowed to have
the book for another 15 days after it is returned.Magazines are lent only for 4 days and no
extension is allowed and there is no restriction for lending the magazine to the same member,as is
the case with books.
You need to store the book details for each book ( publisher name,title,author and the like ).
Each book is identified by a unique title number.Magazines are identified in the following format.
Each magazine has a short hand notation (Eg. otlk for the magazine outlook) To identify a particular
magazine the short hand notation is used along with the month and year of issue Eg. otlk-jan-1999
identifies Outlook magazine jan issue of 1999. You need to store the number of copies of each book
that is there in the library. One copy of each book is designated as reference and it is not lent
to any member.
-------------------------------------------------------------------------------------------------
Create Table sen_catlog
(
c_id varchar(10) constraint sc_pk primary key,
title varchar(20),
author varchar(20),
publisher varchar(20),
price float
);
set nocount on
---------------------------------------------------------------------------------------------------------
1. For each book you will have to generate the members to whom copies of it have been lent....
end
end
exec sen_books_issue
---------------------------------------------------------------------------------------------------------
2.Generate a report which displays all the books. You will have to include all the relevant information i
exec sen_books_details;
---------------------------------------------------------------------------------------------------------
3.On any particular day you will have to generate a report which will produce the details of all
books that are to be delivered on that particular day...
if(@r is null)
set @message=’Not Returned’
else
set @message=’Returned’
print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid + " " + @message
end
end
select @dday=DATEADD(day,-15,@date)
select @n=count(b_id)from sen_transaction where rdate is null and tdate<@dday
if(@n=0)
print ’No Over due books on that day’
else
begin
select b_id,card_id into #temp from sen_transaction where rdate is null and tdate<@dday
select @i = 1
while(@i<=@n)
begin
select top 1 @b=b_id,@c=card_id from #temp
select distinct @t_title=c.title,@t_bid=b.b_id from sen_catlog c,sen_books b,sen_transaction t
where t.b_id=@b and t.b_id=b.b_id and b.c_id = c.c_id
select distinct @t_name=m.mname,@t_card=c.card_id from sen_transaction t,sen_cards c,sen_member m
where t.card_id=@c and t.card_id=c.card_id and c.m_id=m.m_id
delete from #temp where card_id=@c and b_id=@b
select @i=@i+1
print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid
end
end
-------------------------------------------------------------------------------------------------
Query - Page #1
------------------------------------------------------------------------------------------------
LIBRARY
------------------------------------------------------------------------------------------------
Project Specification:
Altair is a library renowned for its latest collection of books and
magazines.The number of members is increasing every month and it is becoming difficult to keep
track of so many members and transactions,which are currently maintained in registers. The chief
librarian approaches you to seek help for designing a computerized system. All members in the
library are given two member cards and one book is leased for each card. The membership fee for
each member is Rs 500. One time payment,refundable on relinquishing of the cards.Both books and
megazines are leased to the members.A book lent to a member can be with him for 15 days at most
and an extension of another 15 days is given to the member for that particular book if that book
is brought for renewal on the 15 th day after it is lent.The same member is not allowed to have
the book for another 15 days after it is returned.Magazines are lent only for 4 days and no
extension is allowed and there is no restriction for lending the magazine to the same member,as is
the case with books.
You need to store the book details for each book ( publisher name,title,author and the like ).
Each book is identified by a unique title number.Magazines are identified in the following format.
Each magazine has a short hand notation (Eg. otlk for the magazine outlook) To identify a particular
magazine the short hand notation is used along with the month and year of issue Eg. otlk-jan-1999
identifies Outlook magazine jan issue of 1999. You need to store the number of copies of each book
that is there in the library. One copy of each book is designated as reference and it is not lent
to any member.
-------------------------------------------------------------------------------------------------
Create Table sen_catlog
(
c_id varchar(10) constraint sc_pk primary key,
title varchar(20),
author varchar(20),
publisher varchar(20),
price float
);
set nocount on
---------------------------------------------------------------------------------------------------------
1. For each book you will have to generate the members to whom copies of it have been lent....
end
end
exec sen_books_issue
---------------------------------------------------------------------------------------------------------
2.Generate a report which displays all the books. You will have to include all the relevant information i
exec sen_books_details;
---------------------------------------------------------------------------------------------------------
3.On any particular day you will have to generate a report which will produce the details of all
books that are to be delivered on that particular day...
if(@r is null)
set @message=’Not Returned’
else
set @message=’Returned’
print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid + " " + @message
end
end
select @dday=DATEADD(day,-15,@date)
select @n=count(b_id)from sen_transaction where rdate is null and tdate<@dday
if(@n=0)
print ’No Over due books on that day’
else
begin
select b_id,card_id into #temp from sen_transaction where rdate is null and tdate<@dday
select @i = 1
while(@i<=@n)
begin
select top 1 @b=b_id,@c=card_id from #temp
select distinct @t_title=c.title,@t_bid=b.b_id from sen_catlog c,sen_books b,sen_transaction t
where t.b_id=@b and t.b_id=b.b_id and b.c_id = c.c_id
select distinct @t_name=m.mname,@t_card=c.card_id from sen_transaction t,sen_cards c,sen_member m
where t.card_id=@c and t.card_id=c.card_id and c.m_id=m.m_id
delete from #temp where card_id=@c and b_id=@b
select @i=@i+1
print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid
end
end
-------------------------------------------------------------------------------------------------
Query - Page #1
--------------------------------------------------------------------------------------------
PRACTICE -1
------------------------------------------------------------------------------------------
1.)Display what each book’s price would be if a 20% price increase were to take
place. Show the title_id,old price and new price using meaningful column titles
select title,price 'Old Price', price * 120/100 'New Price' from titles;
select pub_id,sum(ytd_sales)
from titles
group by pub_id;
Select pub_id,title_id,price,ytd_sales
from titles
order by pub_id
compute sum(ytd_sales),avg(price) by pub_id;
4.) Display the name of each book and the month(in words) in which it was published.
5.)Display the names of books whose prices are greater than $20 and lesser than $25
(or)
(or)
from titles
where type = ’psychology’;
11.) Find out the average advance and sum of total_sales for each type of book
12.) Find the name and title of the most expensive book
select type,price
from titles
where price = ( select max(price) from titles );
select authors.au_id,count(*)
from authors,titleauthor,titles
where authors.au_id=titleauthor.au_id and
titleauthor.title_id=titles.title_id
group by authors.au_id
having count(*)>1
(Or)
---------------------------------------------------------------------------------------------
PRACTICE - 2
-----------------------------------------------------------------------------------------------
/* 1. Create a table named Vehicles and include the fields given below, assigning your own
data types to them all fields should allow null values vech_num, type , mileage ,
model , company_name */
Ans:
Ans:
/* 3. Add a field contractor_id to the table vehicles and set a reference to the contractor_id
field of the contractor’s table. Figure out the problem if any */
Ans:
Error: There are no primary or candidate keys in the referenced table 'contractor' that
match the referencing column list in the foreign key 'fk'.
Ans:
Create table sen_contractor
(
contractor_id varchar(10),
contractor_name varchar(20),
address varchar(20),
phone varchar(20),
city varchar(20)
);
/* 5. Alter the table to add a default value for the city column */
Ans:
/* 6. Add a check constraint to check that the data inserted for the phone field is atleast
six characters long and check that the check constraint is fired on an insert into the table */
Ans:
If some values are not matching the check constraint in the phone field already,
Query - Page #2
Ans:
Alter table sen_contractor Add constraint sen_pchk unique(phone);
Ans:
Alter table sen_contractor Alter column contractor_id int;
Ans:
Insert into sen_contractor values(123,’senthil’,’2nd street’,123456,’T.gode’);
Ans:
/* 11. Insert some records and see how the value for the identity column is generated */
Ans:
Insert into sen_temp values(’senthil’,10);
Ans:
Insert into sen_temp values(100,’senthil’,10);
Error: An explicit value for the identity column in table ’sen_temp’ can only be specified
when a column list is used and IDENTITY_INSERT is ON.
1. When set identity_insert <TableName> on flag is true, we can insert our own values
Error: An explicit value for the identity column in table ’sen_temp’ can only be
specified when a column list is used and IDENTITY_INSERT is ON.
/* 13. Delete one record from the middle of the table and insert another record to see the
Query - Page #3
Ans:
Note: It takes largest value in that particular field and then plus one and assign it
to the next record....
/* 14. Add a field contractor_id to the table vehicles and set a reference to the
contractor_id field of the contractor’s table */
Ans:
Alter table sen_vehicles Add contractor_id int
constraint senfk foreign key references sen_contractor(contractor_id);
Error : There are no primary or candidate keys in the referenced table 'contractor'
that match the referencing column list in the foreign key 'senfk'.
Error : Cannot define PRIMARY KEY constraint on nullable column in table 'sen_contractor'.
/* 15. Create a table to include driver details have driver_id as the primary key.Include
other necessary fields. */
Ans:
/* 16. Create a table vehicle_allot to store information as to which vehicle has been
allotted to which driver. Include driver_id,vehicle_id,allot_date as fields in the table.
Designate driver_id and vehicle_id as composite primary key */
Ans:
Create Table sen_vehicle_allot
(
driver_id int,
vech_num int,
adate datetime
);
Another Method....
/* 17. Try inserting two records with identical values for driver_id and vehicle_id.
Figure out the problem if any and rectify it. */
Ans:
Insert into sen_vehicle_allot values(100,200,’10/10/2001’); // okey
Error: Violation of PRIMARY KEY constraint ’senckd1’. Cannot insert duplicate key in
object ’sen_vehicle_allot’.The statement has been terminated.
//////////////////////////////////////////////////////////////////////////////////////////////////
Query - Page #1
----------------------------------------------------------------------------------------------
PRACTICE - 3
----------------------------------------------------------------------------------------------
Query - Page #1
----------------------------------------------------------------------------------------------
PRACTICE - 3
----------------------------------------------------------------------------------------------
Create the table definitions and set integrity constraints . Insert data into the tables
using the sample data given to you as an attachment.
Ans:
Create Table sen_sailors
(
sid varchar(10) constraint _sen_pk primary key,
sname varchar(20),
rating int,
age int
);
1.) Find the names of sailors who have reserved a red or green boat.
Ans:
select distinct s.sname
from sen_sailors s,sen_boats b,sen_reserves r
where s.sid = r.sid and
r.bid = b.bid and
b.color in (’red’,’green’);
2.) Find the names of sailors who have reserved a red boat and a green boat.
Ans:
select sname
from sen_sailors
where sid in(select sid from sen_reserves where bid in(select bid from sen_boats where co
and sid in(select sid from sen_reserves where bid in(select bid from sen_boats where co
3.) Find the names of sailors who have reserved a red boat.
Ans:
Query - Page #2
4.) Find the names of sailors who have not reserved a red boat.
Ans:
select sname from sen_sailors where sid not in
( select sid from sen_reserves where bid in
( select bid from sen_boats where color=’red’)) and sid in
( select sid from sen_reserves where bid in
( select bid from sen_boats where color !=’red’));
Ans:
6.) Find the names of sailors who are older than the oldest sailor with a rating of 10.
Ans:
7.) Find the age of the youngest sailor who is eligible to vote for each rating level with at
least two such sailors.
Ans:
select min(age) from sen_sailors where rating in
(select rating from sen_sailors where age>18 group by rating having count(*)>=2);
8.) For each red boat find the number of reservations for this boat.
Ans:
select count(sid)’No of Red boat Reservations’ from sen_reserves
where bid in ( select bid from sen_boats where color=’red’);
9.) Find the sid of all sailors who have a rating of 10 or have reserved boat number 106.
10.) Find the names of sailors who have reserved boat number 103.
*************************************************************************************************
Query - Page #1
----------------------------------------------------------------------------------------------
PRACTICE - 5
----------------------------------------------------------------------------------------------
1. Using each pilot who is certified for more than two aircraft models,find the employee_id and
the maximum cruising range of the aircraft models that he ( or she ) is certified for.
2. Find the names of pilots whose salary is less than the sum of cruising range of all the aircraft
models.
select ename from sen_emp where salary < ( select sum(cspeed) from sen_airmodels )and eid like ’P%’;
3. For all the aircraft models with cruising range over 700, find the salary of all pilots certified
for the aircraft model.
5. Identity the routes that can be piloted by every pilot who earns a salary of more than 15,000.
Display the employee_id,flight_no,model_id,start place and destination.
6. Print the names of pilots who can operate planes with cruising range greater than 800 miles, but
are not certified on any Boeing aircraft.
(or)
7. Find the names of all employees who are certified to fly a boeing aircraft but not certified
to fly any of the the aircraft models of type VTL.
(or)
8. Compute the total salary of a pilot and the average salary of all employees excluding pilots.
select * from
sen_emp e1, sen_emp e2
where e1.eid like ’P%’ and e2.eid like ’e%’;
output:
select eid,ename,salary + (select avg(salary) from sen_emp where eid like ’e%’) from sen_emp
where eid like ’P%’;
9. Print the name and salary of every non pilot whose salary is more than the average
salary of pilots
10. Find the flight no and model_id of all the aircraft models that can be used to fly from LA to
CA and from LA to NY.
where flight_no in
(select flight_no from sen_flights
where flight_no in (select flight_no from sen_flights where start=’LA’ and dest=’NY’)
and flight_no in (select flight_no from sen_flights where start=’LA’ and dest=’CA’))
and model_id in
(select model_id from sen_flights
where model_id in (select model_id from sen_flights where start=’LA’ and dest=’NY’)
or model_id in (select model_id from sen_flights where start=’LA’ and dest=’CA’))
*************************************************************************************************
Query - Page #1
----------------------------------------------------------------------------------------------
PRACTICE - 6
----------------------------------------------------------------------------------------------
1.Find the titles of all books of the type "trad_cook" and the names of their authors
Ans:
select au_lname,au_fname from authors where au_id in
(select au_id from titleauthor where title_id in
(select title_id from titles where type =’trad_cook’));
select a.au_lname,a.au_fname,t.title
from titles t,titleauthor ta,authors a
where t.title_id=ta.title_id and t.type=’trad_cook’ and ta.au_id=a.au_id;
2.Find the names of the authors who live in the city in which the publisher "Algodata Systems"
is located.
Ans:
select a.au_lname,a.au_fname
from authors a,publishers p
where p.pub_name=’Algodata Infosystems’ and p.city = a.city;
3.Find the books priced higher than the lowest priced book that has the type "Trad_cook"
Ans:
Ans:
5.Find the names of authors who have written atleast one "Popular_comp" book type.
Ans:
6.Find the states of the whose book is published by the pub_id 0877
Ans:
7.Find the books that received an advance larger than the advance amount paid by
"Algodata systems"
Ans:
8.Find the names of the authors who live in a city in which no publisher is located.
Ans:
9. Find the titles of books published by any publisher located in a city that begins with
the letter ’B’.
Ans:
10. Double the price of all books published by "New Moon Books".
Ans:
11. Find the titles and author names of books published by more than one publisher
Ans:
12. Find the books which have price greater than the average price of all books of its type
Ans:
***************************************************************************************************
Query - Page #1
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
Test II
----------------------------------------------------------------------------------------------
Specification:
Note:
1) No table level constraints should be defined and all integrity constraints have to be
enforced using triggers.
2) Reports are to be generated using cursors.
A movie production company needs to record information about movies that they produce including
all the details of the movie, where it has been shot, in which theatres it has been screened and
the like. Your task is to create a database design for the production company to record all the
details.
The specification and constraints that you have to take into account are as follows..
1) The information for all directors, theatres and studios have to be stored
2) One director can direct many movies and one movie can have many actors. One studio can be
used for many movies and one movie can be shot only in one studio.
3) For each theatre, you will have to record the movies screened in the theatre, screen date
and the collections on each day for the movie till the screening is stopped in the particular
theatre.
4) You also need to maintain the total collections for each movie.
5) Details of all actors as to in which movie the actor acted, the total amount which he has been
promisied and the amount that he has been paid has to be recorded. The amount promisied can
be paid in a maximum of three installments.
6) At any time the outstanding amount that has to be paid to a particular actor for a particular
movie should be made available.
Design an E-R Diagram for the above specification and arrive at a table design primary and
foreign keys have to be indicated in the table.
1) Insertion of duplicate values in primary key fields has to be checked using triggers for
any tow tables of your choice. The primary key field should not be allowed to be updated.
2) Referential integrity of foreign key fields has to be enforced using triggers between any
two tables of your choice.
3) For any table of your choice, you need to perform a cascade delete on deletion of the
primary key of that table.
1) You have to check that the advance amount received is not greater than the total amount
promisied for the actor.
2) For insertion of amount details for an actor for a movie check that the number of current
installment is less than or equal to three.
’Reports to be generated:’
1) For each movie, you need to display the total amount that has been incurred by way of
payment to actors
Format:
Movie Name Actor Name Amount
---------- ---------- --------
Query - Page #2
---------- --------
---------- --------
---------- --------
Format:
Theatre Name Date Amount
------------ ---------- ----------
---------- ----------
---------- ----------
---------- ----------
3) For each movie you will have to display the studio where the movie has been shot, theatres
in which the movie has been screened and the screen date
-------------------------------------------------------------------------------------------------
(
t_id varchar(20),
tdate datetime,
amt float
)
-------------------------------------------------------------------------------------------------
Director---Movie [One to Many]
Movie---Actor [Many to Many] so Acting table is used
Movie---studio [one to many]
Movie--Theatre [Many to Many] so screening table is used
Collection table is used for calculating day to day collections of theatere no need of
considering films is running in the theatre
Installment table is used to store the installment amounts for an actor
-------------------------------------------------------------------------------------------------
Triggers:
------------------------------------------------------------------------------------------------
//// Update Trigger for Sen_movie Table //////
create trigger sen_movie_update
on sen_movie
for update
as
if(update(m_id))
begin
print ’coud not updated,primary key are not allowed to update’
rollback
return
end
------------------------------------------------------------------------------------------------
insert into sen_director values(’D001’,’BalaChandar’);
insert into sen_director values(’D002’,’BharathiRaja’);
------------------------------------------------------------------------------------------------
rollback
end
------------------------------------------------------------------------------------------------
// Foreign key Trigger for sen_acting Table
------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------
// Cascade Deletion Trigger...for Sen_Theatre Table.......
if(@n>3)
begin
print ’Invalid installment : Only 3 installment is allowed....’
rollback
return
end
if(@n=0)
begin
select @pamt=act.p_amt from sen_acting act,inserted i where act.ins_id=i.ins_id
Query - Page #6
if(@n > 0)
begin
select @pamt=act.p_amt from sen_acting act,inserted i where act.ins_id=i.ins_id
select @amt= sum(inst.amt) from sen_installment inst,inserted i where inst.ins_id=i.ins_id
if(@amt>@pamt)
begin
print ’Error:amount exceeds the the promise amount’
rollback
return
end
end
exec movie_payment
drop procedure movie_payment
-------------------------------------------------------------------------------------------------
create procedure theatre_amount
as
set nocount on
declare @tid varchar(20),@tname varchar(20)
declare @collection float
declare @ddate datetime
declare @total float
select @total=0
print "TheatreName "+"Date "+"Amount"
print "----------------------------------------------------------------"
declare tcur cursor scroll
for
select distinct c.t_id,t.t_name from sen_collection c,sen_theatre t
where t.t_id=c.t_id
open tcur
fetch next from tcur into @tid,@tname
while(@@fetch_status=0)
begin
print @tname
declare acur cursor scroll
for select c.tdate,c.amt from sen_collection c where c.t_id=@tid
open acur
fetch next from acur into @ddate,@collection
while(@@fetch_status=0)
begin
print " " +convert(varchar,@ddate) + " " + convert(varchar,@col
fetch next from acur into @ddate,@collection
select @total = @total + @collection
end
print ’----------------------------------------------------------------------’
print ’ Total=’ + convert(varchar,@total)
print ’----------------------------------------------------------------------’
close acur
deallocate acur
select @total=0
fetch next from tcur into @tid,@tname
end
close tcur
deallocate tcur
exec theatre_amount
close mcur
deallocate mcur
exec sen_movie_details
----------------------------------------------------------------------------------------------
Test III
----------------------------------------------------------------------------------------------
A two-wheeler service station needs to record details about the vehicles that come in for
servicing each day. The vehicles that come in for servicing are done maintenance type servicing
which will include labourers to perform the job and each vehicle type(eg: Suzuki, Kawasaki,
Escorts, Kinetic) can have different maintenance types(eg: engine maintenance, gearbox
maintenance, electrical maintenance..) and more than one vehicle type can have the same
maintenance type. A vehicle type number identifies each vehicle type. It is necessary to record
the approximate time that each vehicle type needs for servicing. The total time that a vehicle
type needs for servicing for a maintenance type is msplit into labor types and the approximate
time needed for each labor type is recorded in advance, which is a one-time recording of
details
These details are recorded so that when vehicles come in for servicing, the maintenance types
that are needed for that particular vehicle are identified and the approximate time that it
will take for servicing the vehicle and the approximate cost (without the parts replacement
cost if any) can be presented to the customer.
A Regn No identifies each vehicle that comes in for servicing and a job card is allotted for
that particular vehicle. The details in the Job card should include the vehicle Regn No, the
job card number, the vehicle type, the types of servicing the vehicle needs, the labor charge
for the service, and the parts replacement cost for any part that is replaced in the vehicle,
the total KM run as identified from the odometer, vehicle in time, expected out time,
the customer name, his address and contact number, the supervisor name for that vehicle and
other miscellaneous details. All these details are entered prior to the vehicle being taken
to the service depot. The labels for the details to be entered have to be pre printed in the
form that will be displayed for data entry, after the vehicle type is identified.
Each Vehicle type has a different type of Job Card.
After the vehicle is taken to the service depot, the supervisor for that particular vehicle
is intimated and he allots tasks for the laborers working under him, to service the vehicle.
Each supervisor has around five laborers working under him. One laborer can be asked to
service more than one vehicle per day, depending upon the workload assigned for him.
The supervisor after allotting a task for each laborer constantly maintains the status of
their work and other miscellaneous details (eg: replacement of a part in the vehicle (or)
expected time of completion). All the details are provided to the clerk who generated the
job card, who then updates the Parts charge column in the job card and then generates a bill
for the customer based on the details in the job card.
You are required to create a clustered index on all the primary keys and non clustered index
for all the foreign keys.
--------------------------------------------------------------------------------------------
Create Table sen_vehicle
(
v_id varchar(10) constraint sv_pk primary key,
v_name varchar(20)
);
-- Index Table--------------------------------------------------------------------------
Create Table sen_labour
(
l_id varchar(10) constraint sl_pk primary key nonclustered,
lname varchar(30) not null,
address varchar(30),
sup_id varchar(10) constraint sl_fk foreign key references sen_labour(l_id)
);
end
else
begin
print ’Invalid Labourd id under Supervisior id’
rollback
end
----------------------------------------------------------------------------------------------------
insert into sen_vehicle values(’V001’,’TVS-XL Super’);
insert into sen_vehicle values(’V002’,’SUZUKI MAX 100’);
insert into sen_vehicle values(’V003’,’SUZUKI MAX 100-R’);
insert into sen_vehicle values(’V004’,’YAMAHA 100 CC’);
-------------------------------------------------------------------------------------------------
insert into sen_maintenance values(’M001’,’Engine’);
insert into sen_maintenance values(’M002’,’Gear Box’);
insert into sen_maintenance values(’M003’,’Electrical’);
--------------------------------------------------------------------------------------------------
insert into sen_service_cost values(’V001’,’M001’,450)
insert into sen_service_cost values(’V002’,’M001’,750)
insert into sen_service_cost values(’V002’,’M002’,300)
insert into sen_service_cost values(’V003’,’M001’,750)
insert into sen_service_cost values(’V003’,’M002’,300)
insert into sen_service_cost values(’V003’,’M003’,150)
insert into sen_service_cost values(’V004’,’M001’,820)
insert into sen_service_cost values(’V004’,’M002’,340)
insert into sen_service_cost values(’V004’,’M003’,150)
--------------------------------------------------------------------------------------------------
insert into sen_labour values(’SP01’,’Senthil’,’Salem’,null)
insert into sen_labour values(’SP02’,’Sabitha’,’Salem’,null)
Ans:
create procedure sen_labour_report(@lid varchar(10),@date datetime)
as
set nocount on
print ’Month ’ + convert(varchar,month(@date)) + ’ Year ’ + convert(varchar,year(@date))
print ’---------------------------------------------------------------’
select l.lname ’Labour Name’,v.v_name ’Vehicle Type’,count(v.v_id) ’Nos’
from sen_servicing s,sen_job_card j,sen_labour l,sen_vehicle v
where s.l_id=@lid and s.j_id=j.j_id and j.v_id=v.v_id and s.l_id=l.l_id and
month(sdate)=month(@date) and year(sdate)=year(@date)
group by l.lname,v.v_name
print ’----------------------------------------------------------------------’
print ’Labour Changes Summary’
print ’----------------------------------------------------------------------’
select @ltcost=sum(sc.cost)
from sen_job_card c,sen_maintenance m,sen_service_cost sc,sen_servicing s
where c.j_id=s.j_id and s.m_id = sc.m_id and c.v_id=sc.v_id and sc.m_id = m.m_id and c.j_id=@j_id
print ’-----------------------------------------------------------------------’
print ’Replacement/Repaired Summary’
print ’-----------------------------------------------------------------------’
Query - Page #6
print ’-----------------------------------------------------------------------’
select @tcost=total_cost from sen_job_card where j_id=@j_id
print ’ Total Amount ’ + convert(varchar,@tcost)
print ’-----------------------------------------------------------------------’
if(@qty>1)
begin
select @tid=t_id from inserted
update sen_stores set qih=qih-1 where t_id=@tid
select @price=uprice from sen_stores where t_id=@tid
select @jid=j_id from sen_servicing s,inserted i where i.s_id=s.s_id
print @jid + convert(varchar,@price)
update sen_job_card set total_cost=total_cost+@price where j_id=@jid
select @total = total_cost from sen_job_card where j_id=@jid
print ’The running total cost is Rs ’ + convert(varchar,@total) + ’/.’
end
else
begin
print ’Unavailable qty in hand’
rollback
end
insert into sen_replacement values(’S012’,’T003’)
Query - Page #7
--------------------------------------------------------------------------------------------------
10.) At the end of each month the total revenue got by sale of parts and labour charges
has to be made available.The report should contain the part name and labour type
Ans:
create procedure sen_total_revenue(@date datetime)
as
declare @ltotal numeric(8,2)
declare @ttotal numeric(8,2)
declare @rev numeric(8,2)
set nocount on
print ’Month ’ + convert(varchar,month(@date)) + ’ Year ’ + convert(varchar,year(@date))
print ’----------------------------------------------------------------------’
print ’Labour Charge Summary’
print ’----------------------------------------------------------------------’
print ’---------------------------------------------------------------------’
print ’Tools Sale Summary’
print ’---------------------------------------------------------------------’
select @ltotal=sum(sc.cost)
from sen_job_card c,sen_maintenance m,sen_service_cost sc,sen_servicing s
where c.j_id=s.j_id and s.m_id = sc.m_id and c.v_id=sc.v_id and sc.m_id = m.m_id and
month(c.in_date)= month(@date) and
year(c.in_date) = year(@date)
print ’---------------------------------------------------------------------’
print ’ Total Labour Charge is Rs ’ + convert(varchar,@ltotal) + ’/.’
print ’ Total Tools Sale is Rs ’ + convert(varchar,@ttotal) + ’/.’
select @rev=@ltotal+@ttotal
print ’ Total Revenue is Rs ’ + convert(varchar,@rev) + ’/.’
print ’---------------------------------------------------------------------’
select v.v_id,v.v_name,m.m_id,m.m_name,c.cost
from sen_vehicle v,sen_maintenance m,sen_service_cost c
Query - Page #8
----------------------------------------------------------------------------------------------
Test IV
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
TRIGGERS - EXAMPLE
----------------------------------------------------------------------------------------------
Question: Create the following tables and impose the necessary constraints by using triggers.....
---------------------------------------------------------------------------------------------------------
Tables:
Customers:-
c_id int (primary key)
cname varchar(20)
Address varchar(20)
Constraints to be imposed:-
3.) Delete: do not allow the deletion if the c_id exists in the invoice Table....
Products:-
p_id int primary key
pname varchar(20)
qty_hand varchar(20)
Constraints to be imposed:-
3.) Delete: do not allow the deletion if the p_id exists in the invoice Table....
Invoice:-
o_id int primary key
c_id int
p_id int
idate datetime
qty int
Constraints to be imposed:-
---------------------------------------------------------------------------------------------------------
create Table sen_customers
(
c_id int,
cname varchar(20),
address varchar(40)
);
);
----------------------------------------------------------------------------------------------
FLIGHT EXAMPLE
----------------------------------------------------------------------------------------------
as
select @flag=0
if(@flag=0)
begin
select "housefull"
end
********************************************************************************************
Cancellation Procedure
*****************************************************************************
create procedure sen_cancellation(@pnr int,@cdate varchar(20))
as
*****************************************************************************
select ’senthil’+convert(varchar,10)
----------------------------------------------------------------------------------------------
// Computerized Bank
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
#include<dos.h>
#include<stdlib.h>
class Account
{
protected:
int Acc_no;
char name[20];
char address[20];
float balance;
Account *link; // Link to another node;
};
class Transaction
{
protected:
int Acc_no;
char mode[10]; // Mode of Transaction Cash/Cheque
char t_date[15]; // Transaction Date
char type[15]; // Deposit/Withdraw
float transact_amount;
Transaction *link; // Link to another node
};
//////////////////////////////////////////////////////////////////////////////
class Alist : public Account
{
private:
Alist *head,*prev,*cur,*temp;
public:
void Load_Account_Records();
void Open_Account();
void List_all_Accounts();
float List_Account(int);
void Modify_Account(int);
void Delete_Account(int);
void Update_Balance(int,float);
void Store_Account_Records();
};
};
/////////////////////////////////////////////////////////////////////////////
// Alist Class member function definitions
void Alist :: Load_Account_Records()
{
ifstream ifile("Accounts.dat",ios::binary | ios :: in | ios :: nocreate );
Query - Page #2
if(Total_Records == 0)
{ A_no= 1000; return; }
Alist A;
for(int i=1;i<=Total_Records;i++)
{
ifile.read((char *)&A,sizeof(Alist));
if(i==1)
{
head = cur;
head->link = NULL;
}
else
{
prev->link = cur;
cur->link = NULL;
}
cur->Acc_no = A.Acc_no;
strcpy(cur->name,A.name);
strcpy(cur->address,A.address);
cur->balance=A.balance;
prev = cur;
}// End of For loop
A_no = cur->Acc_no;
ifile.close();
}
/////////////////////////////////////////////////////////////////////////////
void Alist :: Open_Account()
{
cur = (Alist *) new Account;
cur->link = NULL;
cur->Acc_no = ++A_no;
cout<<"Acc_No : "<<cur->Acc_no<<endl;
cout<<"Name : ";
cin>>cur->name;
cout<<"Address : ";
cin>>cur->address;
again:
cout<<"Balance Not < 500 "<<endl;
cout<<"Initial Balance : ";
cin>>cur->balance;
if(cur->balance < 500)
goto again;
if(head==NULL)
{ head = cur;
prev = cur;
}
else
Query - Page #3
{
prev->link = cur;
prev = cur;
}
}
/////////////////////////////////////////////////////////////////////////////
void Alist :: List_all_Accounts()
{
cout<<"-----------------------------------------------------------------"<<endl;
cout<<" Acc_no Name Address Balance "<<endl;
cout<<"-----------------------------------------------------------------"<<endl;
temp = head;
while(temp!=NULL)
{
cout<<temp->Acc_no<<" "<<temp->name<<" "<<temp->address<<" "<<temp->balance<<endl;
temp = (Alist *) temp->link;
}
cout<<"-----------------------------------------------------------------"<<endl;
}
///////////////////////////////////////////////////////////////////////////////
float Alist :: List_Account(int a_no)
{
temp = head;
float balance = 0;
while(temp!=NULL)
{
if(temp->Acc_no==a_no)
{
cout<<"Acc_No : "<<temp->Acc_no<<endl;
cout<<"Name : "<<temp->name<<endl;
cout<<"Address : "<<temp->address<<endl;
cout<<"Balance : "<<temp->balance<<endl;
balance = temp->balance;
break;
}
while(temp !=NULL)
{
if(temp->Acc_no == a_no)
{
cout<<"Acc_No :"<<temp->Acc_no<<endl;
cout<<"New Name :";
cin>>temp->name;
cout<<"New Address :";
cin>>temp->address;
break;
}
Alist *p = head;
while(temp!=NULL)
Query - Page #4
{
if(temp->Acc_no == a_no)
{
if(temp==head) // Head Node
{
head = (Alist *) head->link;
delete temp;
}
else
{
p ->link = temp->link;
delete temp;
}
}
p = temp;
temp = (Alist *) temp->link;
}
}
//////////////////////////////////////////////////////////////////////////////
void Alist :: Update_Balance(int a_no,float Transact_amount)
{
temp = head;
while(temp!=NULL)
{
if(temp->Acc_no==a_no)
{ temp->balance += Transact_amount;
break;
}
temp = head;
while(temp != NULL)
{
ofile.write((char *)temp,sizeof(Alist));
temp = (Alist *) temp->link;
}
ofile.close();
}
/////////////////////////////////////////////////////////////////////////////
// Transaction Class Member Functions
void Tlist :: Load_Transaction_Records()
{
ifstream ifile("Transaction.dat",ios::binary | ios :: in | ios :: nocreate );
Tlist T;
for(int i=1;i<=Total_Records;i++)
{
ifile.read((char *)&T,sizeof(Tlist));
if(i==1)
{
Query - Page #5
head = cur;
head->link = NULL;
}
else
{
prev->link = cur;
cur->link = NULL;
}
cur->Acc_no = T.Acc_no;
strcpy(cur->mode,T.mode);
strcpy(cur->t_date,T.t_date);
strcpy(cur->type,T.type);
cur->transact_amount = T.transact_amount;
prev = cur;
}// End of For loop
ifile.close();
}
/////////////////////////////////////////////////////////////////////////////
float Tlist :: Make_Transaction(int a_no)
{
cur = (Tlist *) new Transaction;
cur->link = NULL;
cur->Acc_no = a_no;
cout<<"Mode : ";
cin>>cur->mode;
struct date d;
getdate(&d);
char temp[10];
itoa(d.da_day,cur->t_date,10);
strcat(cur->t_date,"/");
itoa(d.da_mon,temp,10);
strcat(cur->t_date,temp);
strcat(cur->t_date,"/");
itoa(d.da_year,temp,10);
strcat(cur->t_date,temp);
cout<<"Type : ";
cin>>cur->type;
cout<<"Amount : ";
cin>>cur->transact_amount;
if(head==NULL)
{ head = cur;
prev = cur;
}
else
{
prev->link = cur;
prev = cur;
}
if(strcmp(cur->type,"deposit")==0)
return(cur->transact_amount);
else
return( (-1) * (cur->transact_amount));
//////////////////////////////////////////////////////////////////////////////
void Tlist :: List_Transaction(int a_no,float balance)
{
temp = head;
float total_deposit=0;
Query - Page #6
float total_withdraw=0;
cout<<"-----------------------------------------------------"<<endl;
cout<<"Date Deposit Withdraw "<<endl;
cout<<"-----------------------------------------------------"<<endl;
while(temp != NULL)
{
if(temp->Acc_no == a_no)
{
cout<<temp->t_date<<" ";
if(!strcmp(temp->type,"deposit"))
{ cout<<temp->transact_amount<<endl;
total_deposit += temp->transact_amount;
}
else
{ cout<<" "<<temp->transact_amount<<endl;
total_withdraw += temp->transact_amount;
}
}
cout<<"--------------------------------------------------------"<<endl;
cout<<"Total "<<total_deposit<<" "<<total_withdraw
<<" Balance : "<<balance<<endl;
cout<<"---------------------------------------------------------"<<endl;
}
/////////////////////////////////////////////////////////////////////////////
void Tlist :: List_Daily_Transaction(char *today)
{
temp = head;
float total_deposit=0;
float total_withdraw=0;
cout<<"-----------------------------------------------------------"<<endl;
cout<<"Acc_no Deposit Withdraw "<<endl;
cout<<"-----------------------------------------------------------"<<endl;
while(temp != NULL)
{
if(!strcmp(temp->t_date,today))
{ cout<<temp->Acc_no<<" ";
if(strcmp(temp->type,"deposit")==0)
{ cout<<temp->transact_amount<<endl;
total_deposit += temp->transact_amount;
}
else
{ cout<<" "<<temp->transact_amount<<endl;
total_withdraw += temp->transact_amount;
}
}
cout<<"-----------------------------------------------------------"<<endl;
cout<<"-----------------------------------------------------------"<<endl;
}
////////////////////////////////////////////////////////////////////////////
float Tlist :: Delete_Transaction(int a_no,char *mode,char *date,char *type)
{
temp = head;
Query - Page #7
Tlist *p = head;
float T_amount=0;
while(temp!=NULL)
{
if((temp->Acc_no == a_no && strcmp(temp->mode,mode)==0 && // If equal
strcmp(temp->t_date,date) == 0 && strcmp(temp->type,type)==0) ||
temp->Acc_no == a_no && strcmp(type,"DAll"))
{
if(temp==head) // Head Node
{
head = (Tlist*)head->link;
T_amount = temp->transact_amount;
delete temp;
}
else
{
p ->link = temp->link;
T_amount = temp->transact_amount;
delete temp;
}
}
p = temp;
temp =(Tlist*) temp->link;
}
if(strcmp(temp->type,"deposit")==0)
return( -1 * T_amount);
else
return(T_amount);
}
//////////////////////////////////////////////////////////////////////////////
void Tlist :: Store_Transaction_Records()
{
ofstream ofile("Transaction.dat",ios::binary | ios :: out);
temp = head;
while(temp != NULL)
{
ofile.write((char *)temp,sizeof(Tlist));
temp = (Tlist *) temp->link;
}
ofile.close();
}
/////////////////////////////////////////////////////////////////////////////
// Main Function
void main()
{
clrscr();
int choice,acc_no;
char today[15],mode[15],type[15];
Alist A;
Tlist T;
while(next==’y’)
{
cout<<"1.Open New Account "<<endl;
Query - Page #8
switch(choice)
{
case 1 : A.Open_Account(); break;
T.List_Transaction(acc_no,balance);
getch(); break;
int return_something;
jump:
return_something = T.Delete_Transaction(acc_no,"DAll"," "," ");
A.Update_Balance(acc_no,(T.Delete_Transaction(acc_no,mode,
today,type)));
break;
clrscr();
}
Query - Page #9
A.Store_Account_Records();
T.Store_Transaction_Records();
/////////////////////////////////////////////////////////////////////////////
Query - Page #1
----------------------------------------------------------------------------------------------
// Computerized Libarary
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<fstream.h>
#include<dos.h>
#include<stdlib.h>
#include<iomanip.h>
//////////////////////////////////////////////////////////////////////////////
struct Book
{
int accession_no;
char title[20];
char author[20];
char publisher[20];
float price;
char purchase_date[20];
struct Book *link;
};
struct Member
{
int membership_no;
char name[20];
char address[20];
char current_date[20];
char exp_date[20];
float caution_deposit;
struct Member *link;
};
struct Issue_Register
{
int accession_no;
int membership_no;
char issue_date[20];
char return_date[20];
struct Issue_Register *link;
};
////////////////////////////////////////////////////////////////////////////
// Functions declarations
void Load_Books_Records();
void Load_Members_Records();
void Load_Issue_Register_Records();
void Add_Book();
void Delete_Book();
void List_A_Book();
void List_All_Books();
void Add_Member();
void Delete_Member();
void List_A_Member();
void List_All_Members();
Query - Page #2
void Book_Issue();
void Book_Return();
void Book_Issue_Details();
void List_Overdue_Books();
void Store_Books_Records();
void Store_Members_Records();
void Store_Issue_Register_Records();
//////////////////////////////////////////////////////////////////////////////
// Load Books Records Function definition
void Load_Books_Records()
{
ifstream iBfile("Books.dat",ios::binary | ios :: in | ios :: nocreate );
if(Total_Records == 0)
{ B_no=100; return; }
struct Book B;
for(int i=1;i<=Total_Records;i++)
{
iBfile.read((char *)&B,sizeof(Book));
if(i==1)
{
Bhead = Bcur;
Bhead->link = NULL;
}
else
{
Bprev->link = Bcur;
Bcur->link = NULL;
}
Bcur->accession_no = B.accession_no;
strcpy(Bcur->title,B.title);
strcpy(Bcur->author,B.author);
strcpy(Bcur->publisher,B.publisher);
Bcur->price=B.price;
strcpy(Bcur->purchase_date,B.purchase_date);
Bprev = Bcur;
}// End of For loop
B_no = Bcur->accession_no;
iBfile.close();
}
////////////////////////////////////////////////////////////////////////////
// Load Members Records Function definition
void Load_Members_Records()
{
ifstream iMfile("Members.dat",ios::binary | ios :: in | ios :: nocreate );
if(Total_Records == 0)
{ M_no=500; return; }
struct Member M;
for(int i=1;i<=Total_Records;i++)
{
iMfile.read((char *)&M,sizeof(Member));
if(i==1)
{
Mhead = Mcur;
Mhead->link = NULL;
}
else
{
Mprev->link = Mcur;
Mcur->link = NULL;
}
Mcur->membership_no = M.membership_no;
strcpy(Mcur->name,M.name);
strcpy(Mcur->address,M.address);
strcpy(Mcur->current_date,M.current_date);
strcpy(Mcur->exp_date,M.exp_date);
Mcur->caution_deposit = M.caution_deposit;
Mprev = Mcur;
}// End of For loop
M_no = Mcur->membership_no;
iMfile.close();
}
////////////////////////////////////////////////////////////////////////////
// Load Issue_Register Function definition
void Load_Issue_Register_Records()
{
ifstream iIRfile("IRegister.dat",ios::binary | ios :: in | ios :: nocreate );
if(Total_Records == 0)
{ return; }
for(int i=1;i<=Total_Records;i++)
{
iIRfile.read((char *)&IR,sizeof(Issue_Register));
if(i==1)
{
Query - Page #4
IRhead = IRcur;
IRhead->link = NULL;
}
else
{
IRprev->link = IRcur;
IRcur->link = NULL;
}
IRcur->accession_no = IR.accession_no;
IRcur->membership_no = IR.membership_no;
strcpy(IRcur->issue_date,IR.issue_date);
strcpy(IRcur->return_date,IR.return_date);
IRprev = IRcur;
}// End of For loop
iIRfile.close();
}
////////////////////////////////////////////////////////////////////////////
// Add Book function definition
void Add_Book()
{
Bcur = new Book;
Bcur->link = NULL;
Bcur->accession_no = ++B_no;
cout<<"Accession_No : "<<Bcur->accession_no<<endl;
cout<<"Title : ";
cin>>Bcur->title;
cout<<"Author : ";
cin>>Bcur->author;
cout<<"Publisher : ";
cin>>Bcur->publisher;
cout<<"Purchase Date : ";
cin>>Bcur->purchase_date;
cout<<"Price : ";
cin>>Bcur->price;
if(Bhead==NULL)
{ Bhead = Bcur;
Bprev = Bcur;
}
else
{
Bprev->link = Bcur;
Bprev = Bcur;
}
}
////////////////////////////////////////////////////////////////////////////
// List A Book Function definition
void List_A_Book()
{
Btemp = Bhead;
int a_no;
while(Btemp!=NULL)
{
if(Btemp->accession_no==a_no)
{
cout<<"Accession_No : "<<Btemp->accession_no<<endl;
cout<<"Title : "<<Btemp->title<<endl;
cout<<"Author : "<<Btemp->author<<endl;
cout<<"Publisher : "<<Btemp->publisher<<endl;
Query - Page #5
Btemp = Btemp->link;
}
if(Btemp==NULL)
cout<<"Book Not Found!!"<<endl;
}
///////////////////////////////////////////////////////////////////////////
// Delete Book Function
void Delete_Book()
{
Btemp = Bhead;
Book *p = Bhead;
int a_no;
while(Btemp!=NULL)
{
if(Btemp->accession_no == a_no)
{
if(Btemp==Bhead) // Head Node
{
Bhead = Bhead->link;
delete Btemp;
}
else
{
p ->link = Btemp->link;
delete Btemp;
}
}
p = Btemp;
Btemp = Btemp->link;
}
if(Btemp==NULL)
cout<<"Book Not Found!!"<<endl;
}
/////////////////////////////////////////////////////////////////////////////
// List_All_Books Function definition
void List_All_Books()
{
cout<<"-----------------------------------------------------------------"<<endl;
cout<<" Accssion_no Title Author Publisher "<<endl;
cout<<"-----------------------------------------------------------------"<<endl;
Btemp = Bhead;
while(Btemp!=NULL)
{
/* cout<<" "<<Btemp->accession_no<<" "<<Btemp->title<<" "<<Btemp->author<<
<<Btemp->publisher<<endl; */
Btemp = Btemp->link;
}
cout<<"-----------------------------------------------------------------"<<endl;
}
/////////////////////////////////////////////////////////////////////////////////
// Add Member function definition
Query - Page #6
void Add_Member()
{
Mcur = new Member;
Mcur->link = NULL;
Mcur->membership_no = ++M_no;
cout<<"Membership_No : "<<Mcur->membership_no<<endl;
cout<<"Name : ";
cin>>Mcur->name;
cout<<"Address : ";
cin>>Mcur->address;
cout<<"Caution Deposit : ";
cin>>Mcur->caution_deposit;
struct date d;
getdate(&d);
char temp[10];
itoa(d.da_day,Mcur->current_date,10);
strcat(Mcur->current_date,"/");
itoa(d.da_day,Mcur->exp_date,10);
strcat(Mcur->exp_date,"/");
itoa(d.da_mon,temp,10);
strcat(Mcur->current_date,temp);
strcat(Mcur->current_date,"/");
itoa(d.da_mon,temp,10);
strcat(Mcur->exp_date,temp);
strcat(Mcur->exp_date,"/");
itoa(d.da_year,temp,10);
strcat(Mcur->current_date,temp);
itoa((d.da_year+1),temp,10);
strcat(Mcur->exp_date,temp);
if(Mhead==NULL)
{ Mhead = Mcur;
Mprev = Mcur;
}
else
{
Mprev->link = Mcur;
Mprev = Mcur;
}
}
////////////////////////////////////////////////////////////////////////////
// List A Member Function definition
void List_A_Member()
{
Mtemp = Mhead;
int m_no;
while(Mtemp!=NULL)
{
if(Mtemp->membership_no==m_no)
{
cout<<"Membership_No : "<<Mtemp->membership_no<<endl;
cout<<"Name : "<<Mtemp->name<<endl;
cout<<"Address : "<<Mtemp->address<<endl;
cout<<"Current_date : "<<Mtemp->current_date<<endl;
cout<<"Exp Date : "<<Mtemp->exp_date<<endl;
Query - Page #7
Mtemp = Mtemp->link;
}
if(Mtemp==NULL)
cout<<"Member Not Found!!"<<endl;
}
///////////////////////////////////////////////////////////////////////////
// Delete Member Function
void Delete_Member()
{
Mtemp = Mhead;
Member *p = Mhead;
int m_no;
while(Mtemp!=NULL)
{
if(Mtemp->membership_no == m_no)
{
if(Mtemp==Mhead) // Head Node
{
Mhead = Mhead->link;
delete Mtemp;
}
else
{
p ->link = Mtemp->link;
delete Mtemp;
}
}
p = Mtemp;
Mtemp = Mtemp->link;
}
if(Mtemp==NULL)
cout<<"Member Not Found!!"<<endl;
}
/////////////////////////////////////////////////////////////////////////////
// List_All_Members Function definition
void List_All_Members()
{
cout<<"-----------------------------------------------------------------"<<endl;
cout<<" Membership_no Name Address Exp Date "<<endl;
cout<<"-----------------------------------------------------------------"<<endl;
Mtemp = Mhead;
while(Mtemp!=NULL)
{
cout<<" "<< Mtemp->membership_no<<" "<<Mtemp->name<<" "<<Mtemp->address<<"
<<Mtemp->exp_date<<endl;
Mtemp = Mtemp->link;
}
cout<<"-----------------------------------------------------------------"<<endl;
}
/////////////////////////////////////////////////////////////////////////////////
// Book Issue function details
void Book_Issue()
{
int a_no,m_no;
cout<<"Accession No : ";
cin>>a_no;
Query - Page #8
cout<<"Membership No : ";
cin>>m_no;
IRtemp = IRhead;
while(IRtemp != NULL)
{
if(IRtemp->accession_no == a_no || IRtemp->membership_no == m_no)
{ cout<<" Book Can’t be issued !!!"<<endl; getch();
return;
}
IRtemp = IRtemp->link;
}
Btemp = Bhead;
while(Btemp !=NULL)
{
if(Btemp->accession_no == a_no )
goto out;
Btemp = Btemp->link;
}
if(Btemp == NULL)
{ cout<<"Invalid Accession No !!"<<endl; getch(); return; }
out:
Mtemp = Mhead;
while(Mtemp !=NULL)
{
if(Mtemp->membership_no == m_no )
goto out1;
Mtemp = Mtemp->link;
}
if(Mtemp == NULL)
{ cout<<"Invalid Membership No !!"<<endl; getch(); return; }
out1:
IRcur->accession_no = a_no;
IRcur->membership_no = m_no;
struct date d;
getdate(&d);
char temp[10];
itoa(d.da_day,IRcur->issue_date,10);
strcat(IRcur->issue_date,"/");
itoa(d.da_mon,temp,10);
strcat(IRcur->issue_date,temp);
strcat(IRcur->issue_date,"/");
itoa(d.da_year,temp,10);
strcat(IRcur->issue_date,temp);
if(IRhead==NULL)
{ IRhead = IRcur;
IRprev = IRcur;
}
else
{
Query - Page #9
IRprev->link = IRcur;
IRprev = IRcur;
}
}
/////////////////////////////////////////////////////////////////////////////
void Book_Return()
{
int a_no,m_no;
cout<<"Accession No : ";
cin>>a_no;
cout<<"Membership No : ";
cin>>m_no;
IRtemp = IRhead;
Issue_Register *p = IRhead;
while(IRtemp!=NULL)
{
if((IRtemp->accession_no == a_no && IRtemp->membership_no==m_no))
{
if(IRtemp==IRhead) // Head Node
{
IRhead = IRhead->link;
delete IRtemp;
}
else
{
p ->link = IRtemp->link;
delete IRtemp;
}
}
p = IRtemp;
IRtemp = IRtemp->link;
}
}
/////////////////////////////////////////////////////////////////////////////
// Book Issue Details function definition
void Book_Issue_Details()
{
IRtemp = IRhead;
cout<<"------------------------------------------------------------------"<<endl;
cout<<"Accession_no Membership_no Issue_date Return_date "<<endl;
cout<<"------------------------------------------------------------------"<<endl;
while(IRtemp != NULL)
{
cout<<" "<<IRtemp->accession_no<<" ";
cout<<IRtemp->membership_no<<" ";
cout<<IRtemp->issue_date<<" ";
cout<<IRtemp->return_date<<endl;
IRtemp = IRtemp->link;
}
cout<<"-----------------------------------------------------------------"<<endl;
}
//////////////////////////////////////////////////////////////////////////////
// Book Issue Details function definition
void List_Overdue_Books()
{
char today[20];
IRtemp = IRhead;
Query - Page #10
cout<<"------------------------------------------------------------------"<<endl;
cout<<"Accession_no Membership_no Issue_date Return_date "<<endl;
cout<<"------------------------------------------------------------------"<<endl;
int x;
while(IRtemp != NULL)
{
x=strcmp(IRtemp->return_date,today);
if(x<0)
{
cout<<" "<<IRtemp->accession_no<<" ";
cout<<IRtemp->membership_no<<" ";
cout<<IRtemp->issue_date<<" ";
cout<<IRtemp->return_date<<endl;
}
IRtemp = IRtemp->link;
cout<<"-----------------------------------------------------------------"<<endl;
}
////////////////////////////////////////////////////////////////////////////
// Store Books Records Function
void Store_Books_Records()
{
ofstream oBfile("Books.dat",ios::binary | ios :: out);
Btemp = Bhead;
while(Btemp != NULL)
{
oBfile.write((char *)Btemp,sizeof(Book));
Btemp = Btemp->link;
}
oBfile.close();
}
//////////////////////////////////////////////////////////////////////////////
// Store Members Records Function
void Store_Members_Records()
{
ofstream oMfile("Members.dat",ios::binary | ios :: out);
Mtemp = Mhead;
while(Mtemp != NULL)
{
oMfile.write((char *)Mtemp,sizeof(Member));
Mtemp = Mtemp->link;
}
oMfile.close();
}
//////////////////////////////////////////////////////////////////////////////
// Store Issue Register Records Function
void Store_Issue_Register_Records()
{
ofstream oIRfile("IRegister.dat",ios::binary | ios :: out);
IRtemp = IRhead;
while(IRtemp != NULL)
{
oIRfile.write((char *)IRtemp,sizeof(Issue_Register));
IRtemp = IRtemp->link;
}
oIRfile.close();
}
//////////////////////////////////////////////////////////////////////////////
// Main Function
void main()
Query - Page #11
{
clrscr();
Load_Books_Records();
Load_Members_Records();
Load_Issue_Register_Records();
int choice;
char ch=’y’;
while(ch==’y’)
{
cout<<"Sen’s Book Paradise "<<endl<<endl;
cout<<"1. Add A Book "<<endl;
cout<<"2. Delete A Book "<<endl;
cout<<"3. List A Book "<<endl;
cout<<"4. List All Books "<<endl;
cout<<"-----------------------"<<endl;
cout<<"5. Add A member "<<endl;
cout<<"6. Delete A member "<<endl;
cout<<"7. List A member "<<endl;
cout<<"8. List All members "<<endl;
cout<<"-----------------------"<<endl;
cout<<"9. Book Issue "<<endl;
cout<<"10.Book Return "<<endl;
cout<<"11.Book Issue Details "<<endl;
cout<<"12.List Overdue Details"<<endl;
cout<<"13.Exit "<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1 : Add_Book(); break;
} // end of switch st
clrscr();
Store_Books_Records();
Store_Members_Records();
Store_Issue_Register_Records();
}
Query - Page #12
////////////////////////////////////////////////////////////////////////////
Query - Page #1
#include<stdio.h>
main()
{
int i,j;
/* Returning every element address
int *fun1();
int *p;
p=fun1();
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf("%d ",*(p+i*2+j));
printf("\n");
} */
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf("%d ",*(*(q+i)+j));
printf("\n");
} */
/* Returning 2’d Array Base Address
int (*fun3())[2][3];
int (*q)[2][3];
q = fun3();
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf("%d ",(*q)[i][j]);
printf("\n");
}
printf("\n %lu",q);
printf("\n %d",***q); */
int *fun1()
{
static int m[][2] = { {1,2},
{3,4} };
return (int *) m;
}
int (*fun2())[3]
{
static int m[][3] = { { 1,2,3 },
{ 4,5,6 } };
return m;
}
int (*fun3())[2][3]
{
static int m[][3] = { { 1,2,3 },
{ 4,5,6 } };
return (int (*)[2][3])m;
}
Query - Page #1
#include<stdio.h>
void main()
{
char names[][5] = { {"Sabit"},
{"Dee"},
{"Kumar"} };
char (*p)[5];
char (*q)[3][5];
char **m;
char *(*n)[3];
printf("Static Array");
printf("\n%s",*names);
printf("\n%s",names[0]);
printf("\n%s",&names[0][0]);
// printf("\n%s",*++names); Error
printf("\nPointer Array");
printf("\n%s",names1[0]);
printf("\n%s",*names1);
printf("\n%s",&(**names1));
p = names;
q = &names;
m = names1;
n = &names1;