260
1 Query - Page #1 // Create A Table with out primary key CREATE TABLE sen_emp ( empno int, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int ); ************************************************************************************************ // Set Primary key with ALTER TABLE COMMAND ALTER TABLE sen_emp ALTER COLUMN empno int not null; ALTER TABLE sen_emp ADD CONSTRAINT __PK PRIMARY KEY (empno); // Before Adding PRIMARY KEY CONSTRAINT TO A COLUMN, // make sure it should not accept null values ********************************************************************************************** // Create A Table with a Primary key create table sen_dept ( dept_no int constraint _pk primary key, dname char(20), location char(20) ); ********************************************************************************************* // Set Referencial Integrity [ Joining two tables ] Alter table sen_emp Add constraint _fk foreign key(dept_no)references sen_dept(dept_no); ********************************************************************************************* // Create a table with primary key and foreign key CREATE TABLE sen_emp ( empno int CONSTRAINT PK PRIMARY KEY, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int CONSTRAINT FK FOREIGN KEY REFERENCES sen_dept(dept_no) ); *********************************************************************************************** // Droping a Constraint ALTER TABLE sen_emp DROP CONSTRAINT __PK; ************************************************************************************************* // Droping a Column in a Table ALTER TABLE sen_emp DROP COLUMN empno; *********************************************************************************************** // Create a Table with default value CREATE TABLE _TEMP ( empno int, ename varchar(20), city varchar(20) default ’cbe’ ); // Add a Default value to a column ALTER TABLE _TEMP ADD default ’sen’ for ename;

Query

Embed Size (px)

Citation preview

Page 1: Query

1

Query - Page #1

// Create A Table with out primary key

CREATE TABLE sen_emp ( empno int, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int );

************************************************************************************************// Set Primary key with ALTER TABLE COMMAND

ALTER TABLE sen_emp ALTER COLUMN empno int not null; ALTER TABLE sen_emp ADD CONSTRAINT __PK PRIMARY KEY (empno);

// Before Adding PRIMARY KEY CONSTRAINT TO A COLUMN, // make sure it should not accept null values **********************************************************************************************// Create A Table with a Primary key

create table sen_dept ( dept_no int constraint _pk primary key, dname char(20), location char(20) );

********************************************************************************************* // Set Referencial Integrity [ Joining two tables ]

Alter table sen_emp Add constraint _fk foreign key(dept_no)references sen_dept(dept_no);

*********************************************************************************************// Create a table with primary key and foreign key

CREATE TABLE sen_emp ( empno int CONSTRAINT PK PRIMARY KEY, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int CONSTRAINT FK FOREIGN KEY REFERENCES sen_dept(dept_no) );

***********************************************************************************************// Droping a Constraint

ALTER TABLE sen_emp DROP CONSTRAINT __PK;

*************************************************************************************************// Droping a Column in a Table

ALTER TABLE sen_emp DROP COLUMN empno;

***********************************************************************************************// Create a Table with default value

CREATE TABLE _TEMP ( empno int, ename varchar(20), city varchar(20) default ’cbe’);

// Add a Default value to a column

ALTER TABLE _TEMP ADD default ’sen’ for ename;

Page 2: Query

2

Query - Page #2

//Drop the Default constraint from a column

ALTER TABLE _TEMP DROP CONSTRAINT DF___TEMP__CITY__6C6E1476 ***********************************************************************************************// Creating Check Constraint for a column

ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );

*****************************************************************************************// Disabling Check constraint

ALTER TABLE _temp NOCHECK CONSTRAINT CKEMPNO;

// RE-Enabling Check constraint

ALTER TABLE _temp CHECK CONSTRAINT CKEMPNO;

******************************************************************************************// Create a new table and copy only some particular fields of another Table

select empno,second_name,salary into temp_sen_emp from sen_emp;

******************************************************************************************//Create A Table and copy the data from another Table

Create Table vinod ( name varchar(20) );

insert into vinod select second_name from sen_emp;

******************************************************************************************

select * from authors;

select * from authors where au_lname like ’[^a-r]%’;select * from authors where au_lname like ’[a-r]%’;select * from authors where au_lname like ’_[a-r]%’;

select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’

select * from sen_emp;

insert into sen_emp (empno,second_name) values (1500,’gallifer’);

*********************************************************************************************Grouping:

select sum(salary) from sen_emp;

select * from sen_emp;

select sum(salary) from sen_emp group by dept_no;

select sum(price) from titles group by type;

select sum(price) from titles;

select * from titles order by type;

select * from titles;

select sum(price) from titles group by type;

select sum(price) from titles;

select sum(price) as total_salary from titles;

select sum(price) "Total_salary" from titles;

select * from sen_emp;

Page 3: Query

3

Query - Page #3

select dept_no,sum(salary)’Total Salary’ from sen_emp group by dept_no order by dept_no;

select type, sum(type) from titles;

select sum(salary) from sen_emp order by dept_no group by dept_no; // Error

______________________________________________________________________________________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) from titles group by type,pub_id;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id order by type;

select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id desc;

sp_help titles

select type,sum(price) from titles group by type;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id

******************************************************************************************// Select keywords SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]******************************************************************************************

SELECT TYPE,PUB_ID,SUM(PRICE) "TOTAL PRICE"FROM TITLESGROUP BY TYPE,PUB_ID;

SELECT *FROM TITLESORDER BY TYPE DESC;

//////////////////////////////////////////////////////////////////////////////////////////select type,sum(price)from titlesgroup by typeorder 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 titlesgroup by typeorder by title_id; // Error

select type,title_id,sum(price)from titlesgroup by type,title_idorder by title_id;

select * from titles;

select sum(price)from titles ; order by titles

select sum(price)from titles

Page 4: Query

4

Query - Page #4

***********************************************************************select type, count(*) from titles group by type having count(*)=3;***********************************************************************

December 21 2001:-----------------

select type,sum(price) from titles group by type; Result set Business 1100 Computer 700 Novel 800

Compute By class:

select type,sum(price) from titles compute by type; // error

select type,price from titlesorder by type compute sum(price) by type; Rule: 1.Whenever we use compute By class, it must to use order by class. 2.The field which appear in compute by class is must appear in order by class 3.Whatever field in the aggregate funtion, which is also in the select list.

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 itselfable to generate Work Table...So the Compute by class relay order by class...

select type,pricefrom titlesorder by pub_idcompute 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 ofprice by Type...’

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type;

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by pub_id; // Error

Reason: Work Table

Type pub_id Price--------------------------Business p1 200Business p1 200Business p2 300Computer p2 400Computer p2 200Novel p1 200Novel p1 240Novel p2 450

In above work table, The pub_id is clubed according to the Typenot clubed alone...That is why it will flash error...

Page 5: Query

5

Query - Page #5

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type,pub_id;

select type,pub_id,title_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id,title_id;

select type,pub_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id;****************************************************

Afternoon:21-dec-2001

select type,pub_id from titles;

1...select distinct type,pub_id from titles;

2...select type,pub_id from titles group by type,pub_id;

Query 1 and 2 give the same result

select type,pub_id from titlesgroup by type,pub_id;

select distinct type,pub_id from titles;

// In the above query.. The Distinct applies both type and pub_id columns..We can not make to applyfor a particular column. It will apply all the columns in the select list

For Ex

Business p1 200Business p1 400Business p1 300Computer p2 500Computer p2 700

The Result is

Business p1 200Computer p2 500

/////////////////////////////////////////////////select type,sum(price),avg(price)from titlesgroup by price; // Error

Reason: The field name in group by clause which is not used in aggregate function in select list//////////////////////////////////////////////////////////

Having: Having clause should have group by class...but when using group by class it is optionalto use Having clause.

Page 6: Query

6

Query - Page #6

It affects the result of the Group By Class......

Work Table -----> Internal Result Set -----> Output

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...

Both 1 and 2 are gives same result......

Query 2 Work Table:

Olny Business Records are present

But Query 1 Work Table: All types of Records like Business,Computer and Novel and then take Business Records are Filtered

///////////////////////////////////////////////////////////////////////////////

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

// It would not work Reasons: 1. The left hand side of the where class shoul be column name... 2. Here The Group by class run after the where class...but where class we used aggregate functions...This aggregate function will not use group by class..

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select type,sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

/////////////////////////////////////////////////////////////////////////////////////////////////

December-26-2001

Joins:

select * from authors,publishers; // It does the cartisean product of two tables....

if the select statement contains more table in from clause without where clause, it is calledcross joining which is never used...

select * from authors,publishers

Page 7: Query

7

Query - Page #7

where authors.city = publishers.city;

Joins are evaluated just like Nested Loops....

for(i=0;i<=10;i++) One Table for(j=0;j<=5;j++) Another Table if(i==j) Where clause condition { }

select authors.au_id,authors.au_lname,authors.phone,publishers.pub_id,publishers.pub_name,publishers.cityfrom authors,publishers where authors.city = publishers.city;

select authors.*,pub_id,pub_name from authors,publisherswhere 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, publishers p where authors.city=p.city;

select p.*,au_id,au_lnamefrom authors a, publishers pwhere a.city = p.city and a.au_lname like ’c%’

select p.*,au_id,au_lnamefrom authors a, publishers pwhere au_lname like ’c%’ and a.city = p.city

Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select * from authors; select * from publishers; select * from titles; select * from titleauthor;

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

au_id au_lname ----------- ----------------------------a1 lockley

Page 8: Query

8

Query - Page #8

a2 peter

Table: Publisher

pub_id pub_name ------ -----------p1 samyp2 golgotiap3 samba

Table: Titles

title_id pub_id -------- --------t1 p1t2 p2t3 p3

Table: TitleAuthor

au_id title_id ----------- -------- a1 t1a1 t2a2 t1a2 t3

Virtual Tables:

[Authors] [TitleAuthor]aid aname au_id title_ida1 lockey a1 t1a1 lockey a1 t2

[authors] [titleAuthor] [titles]aid aname aid title_id title_id pub_ida1 lockey a1 t1 t1 p1a1 lockey a1 t2 t2 p2

[authors] [titleAuthor] [ titles ] [ publisher]aid aname aid title_id title_id pub_id pub_id pub_name a1 lockey a1 t1 t1 p1 p1 sams a1 lockey a1 t2 t2 p2 p2 golgotia

FAQ:

1. How the joins are works???

Ans: It works as Nested Loops

2.What is the Query Optimizer? Ans: The Query optimizer find out which join will be evaluated first and run the query in the optimized way....

3. How many Virtual Table created for N conditions?? Ans: (N-1) Virtual Tables are created for N tables

Cross Checking:

select * from authors where au_lname like ’Loc%’;select * from titleauthor where au_id = ’486-29-1786’;

Page 9: Query

9

Query - Page #9

select * from titles where title_id=’PC9999’ or title_id=’PS7777’; select * from publishers where pub_id =’1389’ or pub_id=’0736’;

////////////////////////////////////////////////////////////////////////////////////////////////

Renaming the Tables

sp_rename <OldTable> <NewTable>

////////////////////////////////////////////////////////////////////////////////////////////////

Taking a Copy of the Table:

Create Table vinod_temp( eno int identity(1,1), ename varchar(20), dept_id int);

insert into vinod_temp(ename,dept_id) select ename,dept_id from sen_temp;////////////////////////////////////////////////////////////////////////////////////////////////

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

Result set would be A1A6A2A3

select a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays duplicate Records

select state,count(*) from authorsgroup by statehaving count(*)>1 // We should not use group by function in the self joining situations

Page 10: Query

10

Query - Page #10

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays distinct records but it dispalys one author lives in the city

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered...

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id order by a.city; // It displays the perfect result Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Create Table patdat( patno varchar(20) not null, name varchar(20) not null, address varchar(20));

Create Table patadm( patno varchar(20) not null, admno varchar(20) not null, addate datetime, constraint sen_pk2 primary key(patno,admno), constraint fk foreign key(patno) references patdat1(patno));

Create Table operdat( patno varchar(20), admno varchar(20), opno int, opdate datetime, type varchar(20)

constraint sen_pk2 primary key(patno,admno,opno), constraint sen_fk foreign key(patno) references patdat(patno), constraint fk1 foreign key(admno) references patadm1(admno) );

Note: constaint fk1 could not be created.... ’We can not refer the part of the primary key(composite key) in another Table’

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Question: Find the author id who has written more than one book??? select distinct ta1.au_id from titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id;

Question: Find the title_id which has been written by more than one author?

select distinct ta1.title_id from titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id;

Question: Find the author Names who has written more than one book???

select distinct a.au_lname,a.au_fname from authors a,titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id and ta1.au_id = a.au_id;

Page 11: Query

11

Query - Page #11

Question: Find the titles which has been written by more than one author? select distinct t.title from titles t,titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id and ta1.title_id = t.title_id;

/////////////////////////////////////////////////////////////////////////////////////////////////Jan 02 2002:

Outer join: emp e1 boris HRDe2 becker HRDe3 peter SYSe4 Anderw SYSe5 Lafer null

dep

HRD Human ResSYS SystemsPER personalNET network

emp

enoenamed_id

dept

ddiddname

Display the emp details along with dept id??

select emp.* d.did from emp e,dept dwhere e.did=d.did

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYS

select emp.*,d.did from e,dept dwhere e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax)

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYSe5 lafer

select emp.*,d.did from e,dept dwhere e.did =* d.did; // Display the matching records and addition to all unmatching records form dept (SQL Server Syntax)

select * from employee inner join dept on e.deptid=d.detptid (ANSI Syntax)

The above two query gives the same result..

////////////////////////////////////////////////////////////////////////////////////////////

Page 12: Query

12

Query - Page #12

Full outer join: select employee.eno,employee.name,d.did from employee full outer join dept on employee.did=dept.did (ANSI Syntax) [ Where <filter condition> ]

///////////////////////////////////////////////////////////////////////////////////////////////

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;

select * from titles where price = (select max(price) from titles);**************************************************************************************************

Jan-04-2002:

Exists: select cname from customers where exists ( select cid from orders where customers.id=orders.id);

Exists has equal meaning of =Any

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 becausethe join inside the subquery it does not make correlated subquery.]

2.The field in the join is from the outer query table... [Either the right or left side of the join should include the field in the outer query]

The execution of the correlated sub query is like join...

Example: select cname from customers where exists ( select cid from orders where customers.id=orders.id); 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...

It(Exist) is Intersection of the values in the different table..

But simple query Not Exist is equal to Difference

select cname from customers where cid in ( select * from orders ); // Error . We can not compare one field with many fields. select cname from customers where exists ( select * from orders where customers.id=orders.id); // It would not give any error because the inner query will give only boolean values.... --------------------------------------------------------------------------------------------------------

Page 13: Query

13

Query - Page #13

7-01-2002:

select distinct a.au_fname from authors a, authors bwhere a.state = b.state and a.au_id <> b.au_id;

Any self join can be carried out through correlated sub query.

select a.au_fnamefrom authors awhere 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 outer table.

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 executed...If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct clause in the correlated sub query.

What is difference between self join and correlated sub query??Ans: The self join continues until all the records matched but the correlated sub query becomes true, it would not go further.

------------------------------------------------------------------------------------------------------------------Union:

It gives common and uncommon things in the two query....

select * into sen_temp_table from authors where state = ’LA’; select * from authors union select * from sen_temp_table; // It will not give the duplicates of the records 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 type needed select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mismatach,If the implicit conversion possible it will work

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 order by au_id; // Allowed 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:

Find total purchase for each customer??????????

Ans:drop vicreate view v_sample asselect 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

select max(tprice) from v_sample

Find which customer purchased more????

Ans:select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p where o.proid=p.pid group by o.cuid;

Page 14: Query

14

Query - Page #14

-------------------------------------------------------------------------------------------------------------

11-01-2002:

Syntax:Grant select|update|insert|delete on Table_name to UserGrant All Table_name to UserRevoke select|update|insert|delete on Table_name from UserRevoke All Table_name from User

select * from syspermissions;sp_pkeys sen_traveller; View: The View is the Projection of the base tables...

Syntax: Create View view_name as select statement

Create view sen_view_empdatasselect eid,ename,did,dname from emp,deptwhere emp.did = dept.did;

Grant select on v_empdat to sa

Step 1:create view sen_view_v1 asselect * 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;

select * from authors;

select * from titles;

*************************************************************************************************

16-January-2002:

The View can include on only "select" statement.

Ex:

create view v1 as select.....

We can use delete,insert,update and select on views. Create view v2 asselect 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

To make work the above statement....

create view v2 asselect pub_id,sum(price) as "Total" from titles group by pub_id (or)create view v2(publishers_id,price) asselect pub_id,sum(price) as "Total" from titles group by pub_id

//////////////////////////////////////////////////////////////////////////////////////////////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.//////////////////////////////////////////////////////////////////////////////////////////////

Page 15: Query

15

Query - Page #15

create table emp( empno varchar(20) not null, emp_name varchar(20) not null, salary float not null, dept_id varchar(20) not null, phone varchar(20) not null);

create view v1 as select emp_no,emp_name,dept_id,phone from emp; // It would not work...

create view v1 asselect * form emp; // It will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olnyit 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...

Views using joins: 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...

////////////////////////////////////////////////////////////////////////////////////////////////

create view v_emp asselect * from emp where dept_id = ’HRD’;

select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS table and 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....

select * from emp where sal>2500 and dept_id=’HRD’;

Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpretedas below....

Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....

With Check option: create view v_emp as select * from emp where dept_id=’HRD’ with check option

insert v_emp values(’e1001’,’boris’,’HRD’,2000); // It works fine

insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view hasbeen created by with check option condition. It allow only the where clause condition is match, itmeans that we can insert only ’HRD’ type......

/////////////////////////////////////////////////////////////////////////////////////////////////

Question: Find which type sales is greater???

We can not write in single select statement....

create view sen_v1 asselect type,sum(price)as "Total_sales" from titles group by type

select type,max(Total_sales) from sen_v1 group by type,Total_sales having Total_sales= (select max(Total_sales) from sen_v1)

select type from sen_vl where Total_sales =(select max(Total_sales) from sen_v1)

Page 16: Query

16

Query - Page #16

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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. One procedure can have 1024 parameters.

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...

create procedure procedure_name[(parameters)] [ ]--->optional as sql statements;

create procedure pro as select * from authors,publishers where authors.city = publishers.city;

create procedure pro as select * from emp; // In this statement,While creating procedure, it checks only the syntax errors it will not check the existence of the objets. In other words the object need not be existence while creating procedures but view the objects has to exist.

create procedure pro as select sal from emp; // In this statement, it checks the existence of the object,if it is, itchecks the existence of the column, if it is, the procudure will be created...if the column doesnot exist,it will give error....If there is non existence of the object,it will not check the existence of the column,the procedure will be created....

Either existence of object or non-existence of the object,the procedure will be created....

The created procedure have an entry in sysobjects table.....The statements are used in procedure will be stored in syscomments table. To execute the procedure...

Exec pro // while creating procudure, it checks only the syntax, while executing, the compilationprocess is done..

select object_id (’demo’); // we can get the table id what the sql server maintains...

create procedure pro(parameters) with recompileas sql statements; // It will be recompiled for every execution of this procedure.....

//////////////////////////////////////////////////////////////////////////////////////////////what is Query plan????

The query plan is nothing but the path of the execution in the sql statements...

Exec pro;

step 1: the procedure is compiled step 2: creates query plan,this query plan is stord in procedure cache it is like obj file step 3: it executes the obj file and gives the output....

The step 1 and step 2 will be executed at the first execution of the procedure..if u executethe procedure another time, it will no go for compilation process,it just checks the procedurecache 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:

Page 17: Query

17

Query - Page #17

Create procedure sen_sample_procedure(@param varchar(20)) as -- sen_sample_procedure(@param varchar(20) = ’psychology’)// default parameter -- sen_sample_procedure(@param varchar(20) = ’psychology’,@price=20.0) // Overridding default parameters declare @price float

select @price = sum(price) from titles group by type having type = @param;

if(@price <=100) return 1; if(@price>100 and @price<=200) return 2; if(@price >200) return 3;

-------------------------------------

declare @ret int

exec @ret=sen_sample_procedure ’psychology’ --exec @ret=sen_sample_procedure default,50 // Overridding default parameters --exec @ret=sen_sample_procedure @price=50,@param=’business’ // Explicit passing values if @ret = 1 begin select "Return 1"; end if @ret = 2 begin select "Return 2"; end

if @ret = 3 begin select "Return 3"; end

Note: The TSQL does not contain for loop,arrays..... goto,else,break are there

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

declare @value int,@expr int select @value = case @ex when 1 then only one value when 2 then only one value when 3 then only one value

Note: To assign to value to variable select @ret = 1; (or) set @ret = 1;

Example:

SELECT ’Price Category’ = CASE WHEN price IS NULL THEN ’Not yet priced’ WHEN price < 10 THEN ’Very Reasonable Title’ WHEN price >= 10 and price < 20 THEN ’Coffee Table Title’ ELSE ’Expensive book!’

END,title AS ’Shortened Title’ FROM titles

Example

declare @ret int set @ret = 1 select @ret =

case(@ret) when 1 then 10 when 2 then 20 when 3 then 30

Page 18: Query

18

Query - Page #18

end select @ret /////////////////////////////////////////////////////////////////////////////////////////////////

19-01-2002:

Output Parameters:

Question: Write the procedure to find the city and state of the given publishers????

create procedure sen_pro(@pub_name varchar(20), @city varchar(20) output, @state varchar(20) output) as select @state=state,@city=city from publishers where pub_name like @pub_name;

create procedure sen_callpro(@param varchar(20)) as declare @rstate varchar(20); declare @rcity varchar(20); exec sen_pro @param,@city=@rcity output,@state=@rstate output; select "pub state " + @rstate; select "pub city " + @rcity;

exec sen_callpro "New Moon Books";------------------------------------------------------------------------------------------------

Question: Write a procedure to check the given title_id has been written 2 authors, if so print the 2 author names

Create procedure sen_proce(@t_id varchar(20)) as declare @a varchar(20) if exists(select ta.title_id from titleauthor ta,titles t where ta.title_id=t.title_id and t.title_id = @t_id group by ta.title_id having count(*) = 2) begin select ta.au_id into #temp from titleauthor ta,titles t where ta.title_id = t.title_id and t.title_id = @t_id; select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a delete from #temp where au_id = @a select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a end else print "the book does not have exactly 2 authors" exec sen_proce ’PS2091’

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:

create proc pro asgoto aa:print "dgs"-------------------------------------------------------------------------------------------------

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...

The are 3 different types of relationship....

1. One to One2. One to Many3. Many to Many

Page 19: Query

19

Query - Page #19

{Chen notation}

[Entity] [Relation] [Entity]Employee---------- Works In ----------------Dept|[Rect] [Diamond] [Rect]||-------has --------Address [Diamond] [Rect]

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] andone to many[right to left] realationship comes either side,Take a one to many relationship...)

Employee(Optional-entity) Dept ( Optional-entity)eid did did dname(Attributes) (Attributes)e1 d1 d1e2 d1 d2e3 d2 d3e4 d2 (one dept can have zero or many employees)e5 null (employee has not been assigned to zero or one dept)

Cardinality: no of occurences of field value in dependant entity...

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...)

2.emp(1,M) one employee has one or many address.. address(1,1) one address has only one employee.. emp has existence dependent with address (address can not be created before emp so we change to Address has existence dependent with 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..)

Example:(one to many relationship) ( contains two Tables) [Rect] [Diamond] [Rect] Professor -------------- Advises -----------Student [Entity](0,N) [Entity](1,1)

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]

Example:(one to one relationship) ( contains only one table)

[Rect] [Diamond] [Rect] Professor -------------- is allotted -----------Room [Entity](0,1) [Entity](0,1)

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 ]

Example:(Many to Many relationship) ( contains 3 tables)

[Rect] [Diamond rounded square] [Rect] Theater -------------- is shown ---------------- Films [Composite Entity](1,N) [Composite Entity](1,N)

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...

Theatre (entity) Films (entity) TheatreFilm (Associative Entity) or Junction Table ------------------------------------------------------------------------------------------ tid (pk) fid (pk) tid tname fname fid

Page 20: Query

20

Query - Page #20

no_seats hero composite primary key(tid,fid) location heroine

Example:(Many to Many relationship) ( contains three tables)

[Rect] [Diamond rounded square] [Rect] Authors -------------- Writes ------------------ titles [Composite Entity](1,N) [Composite Entity](1,N)

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 qurey...

Any database desin normally will not go beyond the third normal form....

First Normal from: Drive the table using E-R Diagrams... (*) Any table should have atomic values(Every field should record atomic information)

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 record...and take to consideration the table should not have more null value fields.

Example:

eid pid did nohrs dhead-------------------------- e1 p1 is 20 boris e2 p1 is 20 boris e3 p2 net 30 peter e4 p2 net 30 sampry e1 p2 is 30 Andrew

* Primary key should be identified [ composite primary key(eid,pid) ] ---------------------------------------------------------------------------------------------------------

Second Normal Form:

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 id 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 entrily on the primary key and put it separate table along with the field on which the non key attribute is dependent on...

so we take off did from the above table

eid did --------- e1 IS e2 IS e3 NET 24 NET

nohrs is partially depend on primary key,which means the nohrs dependent on only project id...

Page 21: Query

21

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 eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

---------------------------------------------------------------------------------------------------------Third Normal Form: All the non key attributes should be dependent only on the primary key

eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only thedid which is not a primary key of the table....

Take the dhead along with it is dependent....

did dhead-------------- IS boris NET peter

----------------------------------------------------------------------------------------------------------

Database is a collection of data with controlled redundancy.....

*************************************************************************************************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 deleteany enty in the master table,which is refered by in the child table...The SQL server maintainsrestrictions automatically...The cascade deletions is opposite of these restrictions....

Syntax:

Create trigger trigger_name on table for operation as SQL Statements....

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 aftertrigger,The SQL could not support Before Triggers.....

Trigger can not accept parameters.....

Book Magazine----------------------------Bid MagidBname MnameAuthor price

Page 22: Query

22

Query - Page #22

Transaction--------------TidCard_idbook_idissue_datereturn_date--------------------------------------------------------------------------------------------------Implementing primary key constraint:-

Create trigger tri on tempfor insert asdeclare @icount intselect @icount=count(*) from temp,insertedwhere temp pk = insert pkif @icount >1begin print ’Duplicate Record’ rollbackendelse print ’Successfully on inserting the record’

inserted--->trigger test table (or) magic table-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on empfor insert asif not exists(select * from dept,inserted wheredept.did=inserted.did)begin print "Integrity violation" rollback;endelse print "successfull insertion into the table"

emp inserted----------------------------------------------------e1 boris d1 d1 HRDe2 becker d2 d2 SYSe3 sapeg d3

-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on trans_member for insert asif not exists (select * from books,inserted where book.book_id =inserted.book_id)begin if not exists (select * from magazines inserted where magizines.mag_id = inserted.book_id) begin print ’Ref integrity violation’ rollback end else print ’Successfully inserted into the table’endelse print ’Successfully inserted into the table’

-------------------------------------------------------------------------------------------------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:-

Page 23: Query

23

Query - Page #23

Create trigger dtrion publishersfor deleteasdelete from titles where titles.pub_id = deleted.pub_id

publisher table-->Trigger Table

The value from Trigger table is moved into Trigger Test Table (Deleted Table) -------------------------------------------------------------------------------------------------Implementing Restriction on deletion:-

Create trigger dtrion publishersfor deleteasif exists( select * from titles,deleted where titles.pub_id=deleted.pub_id)begin print ’Attempt to create orphan Records’ rollbackend

------------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables?????

Hits provided:declare @i intselect @i=Object_id(’publishers’)

if exists(select * from sysobjects where id=@i) insert back_up select * from deleted

------------------------------------------------------------------------------------------------

31-JAN-2002:

customers invoice products----------------------------------------------cid oid pidcname cid pname pid qoh (quantity in hand) qty price

create trigger trion invoicefor insertasupdate products set qoh=qoh-inserted.qty from products,insertedwhere products.pid=inserted.pid

checking the availability of products:---------------------------------------

select @iqty = inserted.qty from insertedselect @qty = products.qty from inserted,productswhere inserted.pid=products.pidif(@qty<@iqty)begin print "invalid transaction" rollback returnend

-------------------------------------------------------------------------------------------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

Page 24: Query

24

Query - Page #24

on invoicefor updateif update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback returnendif not exists (select * from products,insertedwhere inserted.productid=products.proudctidbegin print ’Fk violation on products’ rollback returnend--------------------------------------------------------------------------------------------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..........

The cursor contains following five ’jargons’

1....Declare2....Open3....Fetch4....Close5....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

// The scroll keyword is used to move the cursor up and down...declare cur cursor scroll for select c_id,title,author,publisher from sen_catlog

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;

Note: When closing the cursor, it destroies the result set.....-------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Note: It destroies the cursor [ like dropping tables ] -------------------------------------------------------------------------------------------------

Example with procedure:-

create procedure sen_cur_pro as

Page 25: Query

25

Query - Page #25

declare cur cursor scrollforselect * from sen_catlogopen curfetch next from curwhile(@@fetch_status=0)begin fetch next from curendclose curdeallocate cur

exec sen_cur_pro;

Note: @@fetch_status is system defined global variable which is automatically set to 0 whichindicates for successful fetch...------------------------------------------------------------------------------------------------1-02-2002:

Application of Cursors:

Create procedure sen_cpro asdeclare @tid varchar(20),@title varchar(20),@price floatdeclare cur cursor scrollforselect title_id,title,price from titlesopen curfetch next from cur into @tid,@title,@pricewhile(@@fetch_status=0)begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@priceendclose curdeallocate cur

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??????

create procedure sen_publisher_books asset nocount ondeclare @pid varchar(20),@pname varchar(20)declare @tid varchar(20),@title varchar(20),@price floatdeclare @n intdeclare cur cursor scrollforselect pub_id,pub_name from publishersopen curfetch next from cur into @pid,@pnamewhile(@@fetch_status=0)begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid 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

Page 26: Query

26

Query - Page #26

close tcur deallocate tcur end print ’------------------------------------------------’ fetch next from cur into @pid,@pnameendclose curdeallocate cur exec sen_publisher_books --------------------------------------------------------------------------------------------------------------2-Feb-2002:

Indexing: It is a sorting process to reduce the searching process time....

Syntax:

Create { nonClustered } index index_nameon table_name(field_name)

Default is Clustered indexing................-------------------------------------------------------------------------------------------------NonClustered:

create nonclustered index emp_enoon emp(eno)

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 orit 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:

create clustered index emp_enoon emp(eno)

The table itself will be sorted on a field name

-----------------------------------------------------------------------------------------------Note: The clustered index points the page...but the nonclustered index points the exact match ofrecord...

1...The Clusterd index is efficiant for duplicte records ( Foreign key)2...The nonClustered index is efficient for unique records (primary key), for the primary key creation the SQL server creates Clusterd index, it is our responsiblity to give nonClusterd index when creating the primary key......------------------------------------------------------------------------------------------------Note: One Clustered index is allowed for a table, but as many nonClustered index is allowed for a table------------------------------------------------------------------------------------------------

Page 27: Query

27

Query - Page #1

// Create A Table with out primary key

CREATE TABLE sen_emp ( empno int, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int );

************************************************************************************************// Set Primary key with ALTER TABLE COMMAND

ALTER TABLE sen_emp ALTER COLUMN empno int not null; ALTER TABLE sen_emp ADD CONSTRAINT __PK PRIMARY KEY (empno);

// Before Adding PRIMARY KEY CONSTRAINT TO A COLUMN, // make sure it should not accept null values **********************************************************************************************// Create A Table with a Primary key

create table sen_dept ( dept_no int constraint _pk primary key, dname char(20), location char(20) );

********************************************************************************************* // Set Referencial Integrity [ Joining two tables ]

Alter table sen_emp Add constraint _fk foreign key(dept_no)references sen_dept(dept_no);

*********************************************************************************************// Create a table with primary key and foreign key

CREATE TABLE sen_emp ( empno int CONSTRAINT PK PRIMARY KEY, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int CONSTRAINT FK FOREIGN KEY REFERENCES sen_dept(dept_no) );

***********************************************************************************************// Droping a Constraint

ALTER TABLE sen_emp DROP CONSTRAINT __PK;

*************************************************************************************************// Droping a Column in a Table

ALTER TABLE sen_emp DROP COLUMN empno;

***********************************************************************************************// Create a Table with default value

CREATE TABLE _TEMP ( empno int, ename varchar(20), city varchar(20) default ’cbe’);

// Add a Default value to a column

ALTER TABLE _TEMP ADD default ’sen’ for ename;

Page 28: Query

28

Query - Page #2

//Drop the Default constraint from a column

ALTER TABLE _TEMP DROP CONSTRAINT DF___TEMP__CITY__6C6E1476 ***********************************************************************************************// Creating Check Constraint for a column

ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );

*****************************************************************************************// Disabling Check constraint

ALTER TABLE _temp NOCHECK CONSTRAINT CKEMPNO;

// RE-Enabling Check constraint

ALTER TABLE _temp CHECK CONSTRAINT CKEMPNO;

******************************************************************************************// Create a new table and copy only some particular fields of another Table

select empno,second_name,salary into temp_sen_emp from sen_emp;

******************************************************************************************//Create A Table and copy the data from another Table

Create Table vinod ( name varchar(20) );

insert into vinod select second_name from sen_emp;

******************************************************************************************

select * from authors;

select * from authors where au_lname like ’[^a-r]%’;select * from authors where au_lname like ’[a-r]%’;select * from authors where au_lname like ’_[a-r]%’;

select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’

select * from sen_emp;

insert into sen_emp (empno,second_name) values (1500,’gallifer’);

*********************************************************************************************Grouping:

select sum(salary) from sen_emp;

select * from sen_emp;

select sum(salary) from sen_emp group by dept_no;

select sum(price) from titles group by type;

select sum(price) from titles;

select * from titles order by type;

select * from titles;

select sum(price) from titles group by type;

select sum(price) from titles;

select sum(price) as total_salary from titles;

select sum(price) "Total_salary" from titles;

select * from sen_emp;

Page 29: Query

29

Query - Page #3

select dept_no,sum(salary)’Total Salary’ from sen_emp group by dept_no order by dept_no;

select type, sum(type) from titles;

select sum(salary) from sen_emp order by dept_no group by dept_no; // Error

______________________________________________________________________________________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) from titles group by type,pub_id;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id order by type;

select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id desc;

sp_help titles

select type,sum(price) from titles group by type;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id

******************************************************************************************// Select keywords SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]******************************************************************************************

SELECT TYPE,PUB_ID,SUM(PRICE) "TOTAL PRICE"FROM TITLESGROUP BY TYPE,PUB_ID;

SELECT *FROM TITLESORDER BY TYPE DESC;

//////////////////////////////////////////////////////////////////////////////////////////select type,sum(price)from titlesgroup by typeorder 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 titlesgroup by typeorder by title_id; // Error

select type,title_id,sum(price)from titlesgroup by type,title_idorder by title_id;

select * from titles;

select sum(price)from titles ; order by titles

select sum(price)from titles

Page 30: Query

30

Query - Page #4

***********************************************************************select type, count(*) from titles group by type having count(*)=3;***********************************************************************

December 21 2001:-----------------

select type,sum(price) from titles group by type; Result set Business 1100 Computer 700 Novel 800

Compute By class:

select type,sum(price) from titles compute by type; // error

select type,price from titlesorder by type compute sum(price) by type; Rule: 1.Whenever we use compute By class, it must to use order by class. 2.The field which appear in compute by class is must appear in order by class 3.Whatever field in the aggregate funtion, which is also in the select list.

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 itselfable to generate Work Table...So the Compute by class relay order by class...

select type,pricefrom titlesorder by pub_idcompute 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 ofprice by Type...’

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type;

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by pub_id; // Error

Reason: Work Table

Type pub_id Price--------------------------Business p1 200Business p1 200Business p2 300Computer p2 400Computer p2 200Novel p1 200Novel p1 240Novel p2 450

In above work table, The pub_id is clubed according to the Typenot clubed alone...That is why it will flash error...

Page 31: Query

31

Query - Page #5

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type,pub_id;

select type,pub_id,title_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id,title_id;

select type,pub_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id;****************************************************

Afternoon:21-dec-2001

select type,pub_id from titles;

1...select distinct type,pub_id from titles;

2...select type,pub_id from titles group by type,pub_id;

Query 1 and 2 give the same result

select type,pub_id from titlesgroup by type,pub_id;

select distinct type,pub_id from titles;

// In the above query.. The Distinct applies both type and pub_id columns..We can not make to applyfor a particular column. It will apply all the columns in the select list

For Ex

Business p1 200Business p1 400Business p1 300Computer p2 500Computer p2 700

The Result is

Business p1 200Computer p2 500

/////////////////////////////////////////////////select type,sum(price),avg(price)from titlesgroup by price; // Error

Reason: The field name in group by clause which is not used in aggregate function in select list//////////////////////////////////////////////////////////

Having: Having clause should have group by class...but when using group by class it is optionalto use Having clause.

Page 32: Query

32

Query - Page #6

It affects the result of the Group By Class......

Work Table -----> Internal Result Set -----> Output

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...

Both 1 and 2 are gives same result......

Query 2 Work Table:

Olny Business Records are present

But Query 1 Work Table: All types of Records like Business,Computer and Novel and then take Business Records are Filtered

///////////////////////////////////////////////////////////////////////////////

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

// It would not work Reasons: 1. The left hand side of the where class shoul be column name... 2. Here The Group by class run after the where class...but where class we used aggregate functions...This aggregate function will not use group by class..

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select type,sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

/////////////////////////////////////////////////////////////////////////////////////////////////

December-26-2001

Joins:

select * from authors,publishers; // It does the cartisean product of two tables....

if the select statement contains more table in from clause without where clause, it is calledcross joining which is never used...

select * from authors,publishers

Page 33: Query

33

Query - Page #7

where authors.city = publishers.city;

Joins are evaluated just like Nested Loops....

for(i=0;i<=10;i++) One Table for(j=0;j<=5;j++) Another Table if(i==j) Where clause condition { }

select authors.au_id,authors.au_lname,authors.phone,publishers.pub_id,publishers.pub_name,publishers.cityfrom authors,publishers where authors.city = publishers.city;

select authors.*,pub_id,pub_name from authors,publisherswhere 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, publishers p where authors.city=p.city;

select p.*,au_id,au_lnamefrom authors a, publishers pwhere a.city = p.city and a.au_lname like ’c%’

select p.*,au_id,au_lnamefrom authors a, publishers pwhere au_lname like ’c%’ and a.city = p.city

Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select * from authors; select * from publishers; select * from titles; select * from titleauthor;

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

au_id au_lname ----------- ----------------------------a1 lockley

Page 34: Query

34

Query - Page #8

a2 peter

Table: Publisher

pub_id pub_name ------ -----------p1 samyp2 golgotiap3 samba

Table: Titles

title_id pub_id -------- --------t1 p1t2 p2t3 p3

Table: TitleAuthor

au_id title_id ----------- -------- a1 t1a1 t2a2 t1a2 t3

Virtual Tables:

[Authors] [TitleAuthor]aid aname au_id title_ida1 lockey a1 t1a1 lockey a1 t2

[authors] [titleAuthor] [titles]aid aname aid title_id title_id pub_ida1 lockey a1 t1 t1 p1a1 lockey a1 t2 t2 p2

[authors] [titleAuthor] [ titles ] [ publisher]aid aname aid title_id title_id pub_id pub_id pub_name a1 lockey a1 t1 t1 p1 p1 sams a1 lockey a1 t2 t2 p2 p2 golgotia

FAQ:

1. How the joins are works???

Ans: It works as Nested Loops

2.What is the Query Optimizer? Ans: The Query optimizer find out which join will be evaluated first and run the query in the optimized way....

3. How many Virtual Table created for N conditions?? Ans: (N-1) Virtual Tables are created for N tables

Cross Checking:

select * from authors where au_lname like ’Loc%’;select * from titleauthor where au_id = ’486-29-1786’;

Page 35: Query

35

Query - Page #9

select * from titles where title_id=’PC9999’ or title_id=’PS7777’; select * from publishers where pub_id =’1389’ or pub_id=’0736’;

////////////////////////////////////////////////////////////////////////////////////////////////

Renaming the Tables

sp_rename <OldTable> <NewTable>

////////////////////////////////////////////////////////////////////////////////////////////////

Taking a Copy of the Table:

Create Table vinod_temp( eno int identity(1,1), ename varchar(20), dept_id int);

insert into vinod_temp(ename,dept_id) select ename,dept_id from sen_temp;////////////////////////////////////////////////////////////////////////////////////////////////

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

Result set would be A1A6A2A3

select a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays duplicate Records

select state,count(*) from authorsgroup by statehaving count(*)>1 // We should not use group by function in the self joining situations

Page 36: Query

36

Query - Page #10

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays distinct records but it dispalys one author lives in the city

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered...

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id order by a.city; // It displays the perfect result Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Create Table patdat( patno varchar(20) not null, name varchar(20) not null, address varchar(20));

Create Table patadm( patno varchar(20) not null, admno varchar(20) not null, addate datetime, constraint sen_pk2 primary key(patno,admno), constraint fk foreign key(patno) references patdat1(patno));

Create Table operdat( patno varchar(20), admno varchar(20), opno int, opdate datetime, type varchar(20)

constraint sen_pk2 primary key(patno,admno,opno), constraint sen_fk foreign key(patno) references patdat(patno), constraint fk1 foreign key(admno) references patadm1(admno) );

Note: constaint fk1 could not be created.... ’We can not refer the part of the primary key(composite key) in another Table’

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Question: Find the author id who has written more than one book??? select distinct ta1.au_id from titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id;

Question: Find the title_id which has been written by more than one author?

select distinct ta1.title_id from titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id;

Question: Find the author Names who has written more than one book???

select distinct a.au_lname,a.au_fname from authors a,titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id and ta1.au_id = a.au_id;

Page 37: Query

37

Query - Page #11

Question: Find the titles which has been written by more than one author? select distinct t.title from titles t,titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id and ta1.title_id = t.title_id;

/////////////////////////////////////////////////////////////////////////////////////////////////Jan 02 2002:

Outer join: emp e1 boris HRDe2 becker HRDe3 peter SYSe4 Anderw SYSe5 Lafer null

dep

HRD Human ResSYS SystemsPER personalNET network

emp

enoenamed_id

dept

ddiddname

Display the emp details along with dept id??

select emp.* d.did from emp e,dept dwhere e.did=d.did

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYS

select emp.*,d.did from e,dept dwhere e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax)

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYSe5 lafer

select emp.*,d.did from e,dept dwhere e.did =* d.did; // Display the matching records and addition to all unmatching records form dept (SQL Server Syntax)

select * from employee inner join dept on e.deptid=d.detptid (ANSI Syntax)

The above two query gives the same result..

////////////////////////////////////////////////////////////////////////////////////////////

Page 38: Query

38

Query - Page #12

Full outer join: select employee.eno,employee.name,d.did from employee full outer join dept on employee.did=dept.did (ANSI Syntax) [ Where <filter condition> ]

///////////////////////////////////////////////////////////////////////////////////////////////

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;

select * from titles where price = (select max(price) from titles);**************************************************************************************************

Jan-04-2002:

Exists: select cname from customers where exists ( select cid from orders where customers.id=orders.id);

Exists has equal meaning of =Any

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 becausethe join inside the subquery it does not make correlated subquery.]

2.The field in the join is from the outer query table... [Either the right or left side of the join should include the field in the outer query]

The execution of the correlated sub query is like join...

Example: select cname from customers where exists ( select cid from orders where customers.id=orders.id); 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...

It(Exist) is Intersection of the values in the different table..

But simple query Not Exist is equal to Difference

select cname from customers where cid in ( select * from orders ); // Error . We can not compare one field with many fields. select cname from customers where exists ( select * from orders where customers.id=orders.id); // It would not give any error because the inner query will give only boolean values.... --------------------------------------------------------------------------------------------------------

Page 39: Query

39

Query - Page #13

7-01-2002:

select distinct a.au_fname from authors a, authors bwhere a.state = b.state and a.au_id <> b.au_id;

Any self join can be carried out through correlated sub query.

select a.au_fnamefrom authors awhere 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 outer table.

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 executed...If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct clause in the correlated sub query.

What is difference between self join and correlated sub query??Ans: The self join continues until all the records matched but the correlated sub query becomes true, it would not go further.

------------------------------------------------------------------------------------------------------------------Union:

It gives common and uncommon things in the two query....

select * into sen_temp_table from authors where state = ’LA’; select * from authors union select * from sen_temp_table; // It will not give the duplicates of the records 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 type needed select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mismatach,If the implicit conversion possible it will work

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 order by au_id; // Allowed 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:

Find total purchase for each customer??????????

Ans:drop vicreate view v_sample asselect 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

select max(tprice) from v_sample

Find which customer purchased more????

Ans:select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p where o.proid=p.pid group by o.cuid;

Page 40: Query

40

Query - Page #14

-------------------------------------------------------------------------------------------------------------

11-01-2002:

Syntax:Grant select|update|insert|delete on Table_name to UserGrant All Table_name to UserRevoke select|update|insert|delete on Table_name from UserRevoke All Table_name from User

select * from syspermissions;sp_pkeys sen_traveller; View: The View is the Projection of the base tables...

Syntax: Create View view_name as select statement

Create view sen_view_empdatasselect eid,ename,did,dname from emp,deptwhere emp.did = dept.did;

Grant select on v_empdat to sa

Step 1:create view sen_view_v1 asselect * 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;

select * from authors;

select * from titles;

*************************************************************************************************

16-January-2002:

The View can include on only "select" statement.

Ex:

create view v1 as select.....

We can use delete,insert,update and select on views. Create view v2 asselect 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

To make work the above statement....

create view v2 asselect pub_id,sum(price) as "Total" from titles group by pub_id (or)create view v2(publishers_id,price) asselect pub_id,sum(price) as "Total" from titles group by pub_id

//////////////////////////////////////////////////////////////////////////////////////////////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.//////////////////////////////////////////////////////////////////////////////////////////////

Page 41: Query

41

Query - Page #15

create table emp( empno varchar(20) not null, emp_name varchar(20) not null, salary float not null, dept_id varchar(20) not null, phone varchar(20) not null);

create view v1 as select emp_no,emp_name,dept_id,phone from emp; // It would not work...

create view v1 asselect * form emp; // It will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olnyit 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...

Views using joins: 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...

////////////////////////////////////////////////////////////////////////////////////////////////

create view v_emp asselect * from emp where dept_id = ’HRD’;

select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS table and 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....

select * from emp where sal>2500 and dept_id=’HRD’;

Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpretedas below....

Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....

With Check option: create view v_emp as select * from emp where dept_id=’HRD’ with check option

insert v_emp values(’e1001’,’boris’,’HRD’,2000); // It works fine

insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view hasbeen created by with check option condition. It allow only the where clause condition is match, itmeans that we can insert only ’HRD’ type......

/////////////////////////////////////////////////////////////////////////////////////////////////

Question: Find which type sales is greater???

We can not write in single select statement....

create view sen_v1 asselect type,sum(price)as "Total_sales" from titles group by type

select type,max(Total_sales) from sen_v1 group by type,Total_sales having Total_sales= (select max(Total_sales) from sen_v1)

select type from sen_vl where Total_sales =(select max(Total_sales) from sen_v1)

Page 42: Query

42

Query - Page #16

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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. One procedure can have 1024 parameters.

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...

create procedure procedure_name[(parameters)] [ ]--->optional as sql statements;

create procedure pro as select * from authors,publishers where authors.city = publishers.city;

create procedure pro as select * from emp; // In this statement,While creating procedure, it checks only the syntax errors it will not check the existence of the objets. In other words the object need not be existence while creating procedures but view the objects has to exist.

create procedure pro as select sal from emp; // In this statement, it checks the existence of the object,if it is, itchecks the existence of the column, if it is, the procudure will be created...if the column doesnot exist,it will give error....If there is non existence of the object,it will not check the existence of the column,the procedure will be created....

Either existence of object or non-existence of the object,the procedure will be created....

The created procedure have an entry in sysobjects table.....The statements are used in procedure will be stored in syscomments table. To execute the procedure...

Exec pro // while creating procudure, it checks only the syntax, while executing, the compilationprocess is done..

select object_id (’demo’); // we can get the table id what the sql server maintains...

create procedure pro(parameters) with recompileas sql statements; // It will be recompiled for every execution of this procedure.....

//////////////////////////////////////////////////////////////////////////////////////////////what is Query plan????

The query plan is nothing but the path of the execution in the sql statements...

Exec pro;

step 1: the procedure is compiled step 2: creates query plan,this query plan is stord in procedure cache it is like obj file step 3: it executes the obj file and gives the output....

The step 1 and step 2 will be executed at the first execution of the procedure..if u executethe procedure another time, it will no go for compilation process,it just checks the procedurecache 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:

Page 43: Query

43

Query - Page #17

Create procedure sen_sample_procedure(@param varchar(20)) as -- sen_sample_procedure(@param varchar(20) = ’psychology’)// default parameter -- sen_sample_procedure(@param varchar(20) = ’psychology’,@price=20.0) // Overridding default parameters declare @price float

select @price = sum(price) from titles group by type having type = @param;

if(@price <=100) return 1; if(@price>100 and @price<=200) return 2; if(@price >200) return 3;

-------------------------------------

declare @ret int

exec @ret=sen_sample_procedure ’psychology’ --exec @ret=sen_sample_procedure default,50 // Overridding default parameters --exec @ret=sen_sample_procedure @price=50,@param=’business’ // Explicit passing values if @ret = 1 begin select "Return 1"; end if @ret = 2 begin select "Return 2"; end

if @ret = 3 begin select "Return 3"; end

Note: The TSQL does not contain for loop,arrays..... goto,else,break are there

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

declare @value int,@expr int select @value = case @ex when 1 then only one value when 2 then only one value when 3 then only one value

Note: To assign to value to variable select @ret = 1; (or) set @ret = 1;

Example:

SELECT ’Price Category’ = CASE WHEN price IS NULL THEN ’Not yet priced’ WHEN price < 10 THEN ’Very Reasonable Title’ WHEN price >= 10 and price < 20 THEN ’Coffee Table Title’ ELSE ’Expensive book!’

END,title AS ’Shortened Title’ FROM titles

Example

declare @ret int set @ret = 1 select @ret =

case(@ret) when 1 then 10 when 2 then 20 when 3 then 30

Page 44: Query

44

Query - Page #18

end select @ret /////////////////////////////////////////////////////////////////////////////////////////////////

19-01-2002:

Output Parameters:

Question: Write the procedure to find the city and state of the given publishers????

create procedure sen_pro(@pub_name varchar(20), @city varchar(20) output, @state varchar(20) output) as select @state=state,@city=city from publishers where pub_name like @pub_name;

create procedure sen_callpro(@param varchar(20)) as declare @rstate varchar(20); declare @rcity varchar(20); exec sen_pro @param,@city=@rcity output,@state=@rstate output; select "pub state " + @rstate; select "pub city " + @rcity;

exec sen_callpro "New Moon Books";------------------------------------------------------------------------------------------------

Question: Write a procedure to check the given title_id has been written 2 authors, if so print the 2 author names

Create procedure sen_proce(@t_id varchar(20)) as declare @a varchar(20) if exists(select ta.title_id from titleauthor ta,titles t where ta.title_id=t.title_id and t.title_id = @t_id group by ta.title_id having count(*) = 2) begin select ta.au_id into #temp from titleauthor ta,titles t where ta.title_id = t.title_id and t.title_id = @t_id; select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a delete from #temp where au_id = @a select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a end else print "the book does not have exactly 2 authors" exec sen_proce ’PS2091’

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:

create proc pro asgoto aa:print "dgs"-------------------------------------------------------------------------------------------------

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...

The are 3 different types of relationship....

1. One to One2. One to Many3. Many to Many

Page 45: Query

45

Query - Page #19

{Chen notation}

[Entity] [Relation] [Entity]Employee---------- Works In ----------------Dept|[Rect] [Diamond] [Rect]||-------has --------Address [Diamond] [Rect]

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] andone to many[right to left] realationship comes either side,Take a one to many relationship...)

Employee(Optional-entity) Dept ( Optional-entity)eid did did dname(Attributes) (Attributes)e1 d1 d1e2 d1 d2e3 d2 d3e4 d2 (one dept can have zero or many employees)e5 null (employee has not been assigned to zero or one dept)

Cardinality: no of occurences of field value in dependant entity...

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...)

2.emp(1,M) one employee has one or many address.. address(1,1) one address has only one employee.. emp has existence dependent with address (address can not be created before emp so we change to Address has existence dependent with 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..)

Example:(one to many relationship) ( contains two Tables) [Rect] [Diamond] [Rect] Professor -------------- Advises -----------Student [Entity](0,N) [Entity](1,1)

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]

Example:(one to one relationship) ( contains only one table)

[Rect] [Diamond] [Rect] Professor -------------- is allotted -----------Room [Entity](0,1) [Entity](0,1)

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 ]

Example:(Many to Many relationship) ( contains 3 tables)

[Rect] [Diamond rounded square] [Rect] Theater -------------- is shown ---------------- Films [Composite Entity](1,N) [Composite Entity](1,N)

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...

Theatre (entity) Films (entity) TheatreFilm (Associative Entity) or Junction Table ------------------------------------------------------------------------------------------ tid (pk) fid (pk) tid tname fname fid

Page 46: Query

46

Query - Page #20

no_seats hero composite primary key(tid,fid) location heroine

Example:(Many to Many relationship) ( contains three tables)

[Rect] [Diamond rounded square] [Rect] Authors -------------- Writes ------------------ titles [Composite Entity](1,N) [Composite Entity](1,N)

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 qurey...

Any database desin normally will not go beyond the third normal form....

First Normal from: Drive the table using E-R Diagrams... (*) Any table should have atomic values(Every field should record atomic information)

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 record...and take to consideration the table should not have more null value fields.

Example:

eid pid did nohrs dhead-------------------------- e1 p1 is 20 boris e2 p1 is 20 boris e3 p2 net 30 peter e4 p2 net 30 sampry e1 p2 is 30 Andrew

* Primary key should be identified [ composite primary key(eid,pid) ] ---------------------------------------------------------------------------------------------------------

Second Normal Form:

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 id 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 entrily on the primary key and put it separate table along with the field on which the non key attribute is dependent on...

so we take off did from the above table

eid did --------- e1 IS e2 IS e3 NET 24 NET

nohrs is partially depend on primary key,which means the nohrs dependent on only project id...

Page 47: Query

47

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 eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

---------------------------------------------------------------------------------------------------------Third Normal Form: All the non key attributes should be dependent only on the primary key

eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only thedid which is not a primary key of the table....

Take the dhead along with it is dependent....

did dhead-------------- IS boris NET peter

----------------------------------------------------------------------------------------------------------

Database is a collection of data with controlled redundancy.....

*************************************************************************************************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 deleteany enty in the master table,which is refered by in the child table...The SQL server maintainsrestrictions automatically...The cascade deletions is opposite of these restrictions....

Syntax:

Create trigger trigger_name on table for operation as SQL Statements....

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 aftertrigger,The SQL could not support Before Triggers.....

Trigger can not accept parameters.....

Book Magazine----------------------------Bid MagidBname MnameAuthor price

Page 48: Query

48

Query - Page #22

Transaction--------------TidCard_idbook_idissue_datereturn_date--------------------------------------------------------------------------------------------------Implementing primary key constraint:-

Create trigger tri on tempfor insert asdeclare @icount intselect @icount=count(*) from temp,insertedwhere temp pk = insert pkif @icount >1begin print ’Duplicate Record’ rollbackendelse print ’Successfully on inserting the record’

inserted--->trigger test table (or) magic table-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on empfor insert asif not exists(select * from dept,inserted wheredept.did=inserted.did)begin print "Integrity violation" rollback;endelse print "successfull insertion into the table"

emp inserted----------------------------------------------------e1 boris d1 d1 HRDe2 becker d2 d2 SYSe3 sapeg d3

-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on trans_member for insert asif not exists (select * from books,inserted where book.book_id =inserted.book_id)begin if not exists (select * from magazines inserted where magizines.mag_id = inserted.book_id) begin print ’Ref integrity violation’ rollback end else print ’Successfully inserted into the table’endelse print ’Successfully inserted into the table’

-------------------------------------------------------------------------------------------------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:-

Page 49: Query

49

Query - Page #23

Create trigger dtrion publishersfor deleteasdelete from titles where titles.pub_id = deleted.pub_id

publisher table-->Trigger Table

The value from Trigger table is moved into Trigger Test Table (Deleted Table) -------------------------------------------------------------------------------------------------Implementing Restriction on deletion:-

Create trigger dtrion publishersfor deleteasif exists( select * from titles,deleted where titles.pub_id=deleted.pub_id)begin print ’Attempt to create orphan Records’ rollbackend

------------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables?????

Hits provided:declare @i intselect @i=Object_id(’publishers’)

if exists(select * from sysobjects where id=@i) insert back_up select * from deleted

------------------------------------------------------------------------------------------------

31-JAN-2002:

customers invoice products----------------------------------------------cid oid pidcname cid pname pid qoh (quantity in hand) qty price

create trigger trion invoicefor insertasupdate products set qoh=qoh-inserted.qty from products,insertedwhere products.pid=inserted.pid

checking the availability of products:---------------------------------------

select @iqty = inserted.qty from insertedselect @qty = products.qty from inserted,productswhere inserted.pid=products.pidif(@qty<@iqty)begin print "invalid transaction" rollback returnend

-------------------------------------------------------------------------------------------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

Page 50: Query

50

Query - Page #24

on invoicefor updateif update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback returnendif not exists (select * from products,insertedwhere inserted.productid=products.proudctidbegin print ’Fk violation on products’ rollback returnend--------------------------------------------------------------------------------------------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..........

The cursor contains following five ’jargons’

1....Declare2....Open3....Fetch4....Close5....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

// The scroll keyword is used to move the cursor up and down...declare cur cursor scroll for select c_id,title,author,publisher from sen_catlog

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;

Note: When closing the cursor, it destroies the result set.....-------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Note: It destroies the cursor [ like dropping tables ] -------------------------------------------------------------------------------------------------

Example with procedure:-

create procedure sen_cur_pro as

Page 51: Query

51

Query - Page #25

declare cur cursor scrollforselect * from sen_catlogopen curfetch next from curwhile(@@fetch_status=0)begin fetch next from curendclose curdeallocate cur

exec sen_cur_pro;

Note: @@fetch_status is system defined global variable which is automatically set to 0 whichindicates for successful fetch...------------------------------------------------------------------------------------------------1-02-2002:

Application of Cursors:

Create procedure sen_cpro asdeclare @tid varchar(20),@title varchar(20),@price floatdeclare cur cursor scrollforselect title_id,title,price from titlesopen curfetch next from cur into @tid,@title,@pricewhile(@@fetch_status=0)begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@priceendclose curdeallocate cur

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??????

create procedure sen_publisher_books asset nocount ondeclare @pid varchar(20),@pname varchar(20)declare @tid varchar(20),@title varchar(20),@price floatdeclare @n intdeclare cur cursor scrollforselect pub_id,pub_name from publishersopen curfetch next from cur into @pid,@pnamewhile(@@fetch_status=0)begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid 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

Page 52: Query

52

Query - Page #26

close tcur deallocate tcur end print ’------------------------------------------------’ fetch next from cur into @pid,@pnameendclose curdeallocate cur exec sen_publisher_books --------------------------------------------------------------------------------------------------------------2-Feb-2002:

Indexing: It is a sorting process to reduce the searching process time....

Syntax:

Create { nonClustered } index index_nameon table_name(field_name)

Default is Clustered indexing................-------------------------------------------------------------------------------------------------NonClustered:

create nonclustered index emp_enoon emp(eno)

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 orit 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:

create clustered index emp_enoon emp(eno)

The table itself will be sorted on a field name

-----------------------------------------------------------------------------------------------Note: The clustered index points the page...but the nonclustered index points the exact match ofrecord...

1...The Clusterd index is efficiant for duplicte records ( Foreign key)2...The nonClustered index is efficient for unique records (primary key), for the primary key creation the SQL server creates Clusterd index, it is our responsiblity to give nonClusterd index when creating the primary key......------------------------------------------------------------------------------------------------Note: One Clustered index is allowed for a table, but as many nonClustered index is allowed for a table------------------------------------------------------------------------------------------------

Page 53: Query

53

Query - Page #1

------------------SQL NOTE -------------------------------------------------------------- Author : E Senthil -----------------------------------------------------------------------------------------

// Create A Table with out primary key

CREATE TABLE sen_emp ( empno int, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int );

************************************************************************************************// Set Primary key with ALTER TABLE COMMAND

ALTER TABLE sen_emp ALTER COLUMN empno int not null; ALTER TABLE sen_emp ADD CONSTRAINT __PK PRIMARY KEY (empno);

// Before Adding PRIMARY KEY CONSTRAINT TO A COLUMN, // make sure it should not accept null values **********************************************************************************************// Create A Table with a Primary key

create table sen_dept ( dept_no int constraint _pk primary key, dname char(20), location char(20) );

********************************************************************************************* // Set Referencial Integrity [ Joining two tables ]

Alter table sen_emp Add constraint _fk foreign key(dept_no)references sen_dept(dept_no);

*********************************************************************************************// Create a table with primary key and foreign key

CREATE TABLE sen_emp ( empno int CONSTRAINT PK PRIMARY KEY, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int CONSTRAINT FK FOREIGN KEY REFERENCES sen_dept(dept_no) );

***********************************************************************************************// Droping a Constraint

ALTER TABLE sen_emp DROP CONSTRAINT __PK;

*************************************************************************************************// Droping a Column in a Table

ALTER TABLE sen_emp DROP COLUMN empno;

***********************************************************************************************// Create a Table with default value

CREATE TABLE _TEMP ( empno int,

Page 54: Query

54

Query - Page #2

ename varchar(20), city varchar(20) default ’cbe’);

// Add a Default value to a column

ALTER TABLE _TEMP ADD default ’sen’ for ename;

//Drop the Default constraint from a column

ALTER TABLE _TEMP DROP CONSTRAINT DF___TEMP__CITY__6C6E1476 ***********************************************************************************************// Creating Check Constraint for a column

ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );

*****************************************************************************************// Disabling Check constraint

ALTER TABLE _temp NOCHECK CONSTRAINT CKEMPNO;

// RE-Enabling Check constraint

ALTER TABLE _temp CHECK CONSTRAINT CKEMPNO;

******************************************************************************************// Create a new table and copy only some particular fields of another Table

select empno,second_name,salary into temp_sen_emp from sen_emp;

******************************************************************************************//Create A Table and copy the data from another Table

Create Table vinod ( name varchar(20) );

insert into vinod select second_name from sen_emp;

******************************************************************************************

select * from authors;

select * from authors where au_lname like ’[^a-r]%’;select * from authors where au_lname like ’[a-r]%’;select * from authors where au_lname like ’_[a-r]%’;

select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’

select * from sen_emp;

insert into sen_emp (empno,second_name) values (1500,’gallifer’);

*********************************************************************************************Grouping:

select sum(salary) from sen_emp;

select * from sen_emp;

select sum(salary) from sen_emp group by dept_no;

select sum(price) from titles group by type;

select sum(price) from titles;

select * from titles order by type;

select * from titles;

select sum(price) from titles group by type;

Page 55: Query

55

Query - Page #3

select sum(price) from titles;

select sum(price) as total_salary from titles;

select sum(price) "Total_salary" from titles;

select * from sen_emp;

select dept_no,sum(salary)’Total Salary’ from sen_emp group by dept_no order by dept_no;

select type, sum(type) from titles;

select sum(salary) from sen_emp order by dept_no group by dept_no; // Error

______________________________________________________________________________________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) from titles group by type,pub_id;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id order by type;

select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id desc;

sp_help titles

select type,sum(price) from titles group by type;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id

******************************************************************************************// Select keywords SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]******************************************************************************************

SELECT TYPE,PUB_ID,SUM(PRICE) "TOTAL PRICE"FROM TITLESGROUP BY TYPE,PUB_ID;

SELECT *FROM TITLESORDER BY TYPE DESC;

//////////////////////////////////////////////////////////////////////////////////////////select type,sum(price)from titlesgroup by typeorder 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 titlesgroup by typeorder by title_id; // Error

select type,title_id,sum(price)from titlesgroup by type,title_idorder by title_id;

select * from titles;

Page 56: Query

56

Query - Page #4

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:-----------------

select type,sum(price) from titles group by type; Result set Business 1100 Computer 700 Novel 800

Compute By class:

select type,sum(price) from titles compute by type; // error

select type,price from titlesorder by type compute sum(price) by type; Rule: 1.Whenever we use compute By class, it must to use order by class. 2.The field which appear in compute by class is must appear in order by class 3.Whatever field in the aggregate funtion, which is also in the select list.

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 itselfable to generate Work Table...So the Compute by class relay order by class...

select type,pricefrom titlesorder by pub_idcompute 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 ofprice by Type...’

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type;

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by pub_id; // Error

Reason: Work Table

Type pub_id Price--------------------------Business p1 200Business p1 200Business p2 300Computer p2 400

Page 57: Query

57

Query - Page #5

Computer p2 200Novel p1 200Novel p1 240Novel p2 450

In above work table, The pub_id is clubed according to the Typenot clubed alone...That is why it will flash error...

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type,pub_id;

select type,pub_id,title_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id,title_id;

select type,pub_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id;****************************************************

Afternoon:21-dec-2001

select type,pub_id from titles;

1...select distinct type,pub_id from titles;

2...select type,pub_id from titles group by type,pub_id;

Query 1 and 2 give the same result

select type,pub_id from titlesgroup by type,pub_id;

select distinct type,pub_id from titles;

// In the above query.. The Distinct applies both type and pub_id columns..We can not make to applyfor a particular column. It will apply all the columns in the select list

For Ex

Business p1 200Business p1 400Business p1 300Computer p2 500Computer p2 700

The Result is

Business p1 200Computer p2 500

/////////////////////////////////////////////////select type,sum(price),avg(price)from titlesgroup by price; // Error

Reason: The field name in group by clause which is not used in aggregate function in select list

Page 58: Query

58

Query - Page #6

//////////////////////////////////////////////////////////

Having: Having clause should have group by class...but when using group by class it is optionalto use Having clause.

It affects the result of the Group By Class......

Work Table -----> Internal Result Set -----> Output

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...

Both 1 and 2 are gives same result......

Query 2 Work Table:

Olny Business Records are present

But Query 1 Work Table: All types of Records like Business,Computer and Novel and then take Business Records are Filtered

///////////////////////////////////////////////////////////////////////////////

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

// It would not work Reasons: 1. The left hand side of the where class shoul be column name... 2. Here The Group by class run after the where class...but where class we used aggregate functions...This aggregate function will not use group by class..

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select type,sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

/////////////////////////////////////////////////////////////////////////////////////////////////

December-26-2001

Joins:

select * from authors,publishers; // It does the cartisean product of two tables....

Page 59: Query

59

Query - Page #7

if the select statement contains more table in from clause without where clause, it is calledcross joining which is never used...

select * from authors,publisherswhere authors.city = publishers.city;

Joins are evaluated just like Nested Loops....

for(i=0;i<=10;i++) One Table for(j=0;j<=5;j++) Another Table if(i==j) Where clause condition { }

select authors.au_id,authors.au_lname,authors.phone,publishers.pub_id,publishers.pub_name,publishers.cityfrom authors,publishers where authors.city = publishers.city;

select authors.*,pub_id,pub_name from authors,publisherswhere 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, publishers p where authors.city=p.city;

select p.*,au_id,au_lnamefrom authors a, publishers pwhere a.city = p.city and a.au_lname like ’c%’

select p.*,au_id,au_lnamefrom authors a, publishers pwhere au_lname like ’c%’ and a.city = p.city

Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select * from authors; select * from publishers; select * from titles; select * from titleauthor;

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:.................

Page 60: Query

60

Query - Page #8

Explanation:

Title: Authors

au_id au_lname ----------- ----------------------------a1 lockleya2 peter

Table: Publisher

pub_id pub_name ------ -----------p1 samyp2 golgotiap3 samba

Table: Titles

title_id pub_id -------- --------t1 p1t2 p2t3 p3

Table: TitleAuthor

au_id title_id ----------- -------- a1 t1a1 t2a2 t1a2 t3

Virtual Tables:

[Authors] [TitleAuthor]aid aname au_id title_ida1 lockey a1 t1a1 lockey a1 t2

[authors] [titleAuthor] [titles]aid aname aid title_id title_id pub_ida1 lockey a1 t1 t1 p1a1 lockey a1 t2 t2 p2

[authors] [titleAuthor] [ titles ] [ publisher]aid aname aid title_id title_id pub_id pub_id pub_name a1 lockey a1 t1 t1 p1 p1 sams a1 lockey a1 t2 t2 p2 p2 golgotia

FAQ:

1. How the joins are works???

Ans: It works as Nested Loops

2.What is the Query Optimizer? Ans: The Query optimizer find out which join will be evaluated first and run the query in the optimized way....

3. How many Virtual Table created for N conditions??

Page 61: Query

61

Query - Page #9

Ans: (N-1) Virtual Tables are created for N tables

Cross Checking:

select * from authors where au_lname like ’Loc%’;select * from titleauthor where au_id = ’486-29-1786’; select * from titles where title_id=’PC9999’ or title_id=’PS7777’; select * from publishers where pub_id =’1389’ or pub_id=’0736’;

////////////////////////////////////////////////////////////////////////////////////////////////

Renaming the Tables

sp_rename <OldTable> <NewTable>

////////////////////////////////////////////////////////////////////////////////////////////////

Taking a Copy of the Table:

Create Table vinod_temp( eno int identity(1,1), ename varchar(20), dept_id int);

insert into vinod_temp(ename,dept_id) select ename,dept_id from sen_temp;////////////////////////////////////////////////////////////////////////////////////////////////

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

Result set would be A1A6A2A3

select a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays duplicate Records

Page 62: Query

62

Query - Page #10

select state,count(*) from authorsgroup by statehaving count(*)>1 // We should not use group by function in the self joining situations

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays distinct records but it dispalys one author lives in the city

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered...

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id order by a.city; // It displays the perfect result Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Create Table patdat( patno varchar(20) not null, name varchar(20) not null, address varchar(20));

Create Table patadm( patno varchar(20) not null, admno varchar(20) not null, addate datetime, constraint sen_pk2 primary key(patno,admno), constraint fk foreign key(patno) references patdat1(patno));

Create Table operdat( patno varchar(20), admno varchar(20), opno int, opdate datetime, type varchar(20)

constraint sen_pk2 primary key(patno,admno,opno), constraint sen_fk foreign key(patno) references patdat(patno), constraint fk1 foreign key(admno) references patadm1(admno) );

Note: constaint fk1 could not be created.... ’We can not refer the part of the primary key(composite key) in another Table’

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Question: Find the author id who has written more than one book??? select distinct ta1.au_id from titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id;

Question: Find the title_id which has been written by more than one author?

select distinct ta1.title_id from titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id;

Question: Find the author Names who has written more than one book???

Page 63: Query

63

Query - Page #11

select distinct a.au_lname,a.au_fname from authors a,titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id and ta1.au_id = a.au_id;

Question: Find the titles which has been written by more than one author? select distinct t.title from titles t,titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id and ta1.title_id = t.title_id;

/////////////////////////////////////////////////////////////////////////////////////////////////Jan 02 2002:

Outer join: emp e1 boris HRDe2 becker HRDe3 peter SYSe4 Anderw SYSe5 Lafer null

dep

HRD Human ResSYS SystemsPER personalNET network

emp

enoenamed_id

dept

ddiddname

Display the emp details along with dept id??

select emp.* d.did from emp e,dept dwhere e.did=d.did

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYS

select emp.*,d.did from e,dept dwhere e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax)

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYSe5 lafer

select emp.*,d.did from e,dept dwhere e.did =* d.did; // Display the matching records and addition to all

Page 64: Query

64

Query - Page #12

unmatching records form dept (SQL Server Syntax)

select * from employee inner join dept on e.deptid=d.detptid (ANSI Syntax)

The above two query gives the same result..

////////////////////////////////////////////////////////////////////////////////////////////

Full outer join: select employee.eno,employee.name,d.did from employee full outer join dept on employee.did=dept.did (ANSI Syntax) [ Where <filter condition> ]

///////////////////////////////////////////////////////////////////////////////////////////////

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;

select * from titles where price = (select max(price) from titles);**************************************************************************************************

Jan-04-2002:

Exists: select cname from customers where exists ( select cid from orders where customers.id=orders.id);

Exists has equal meaning of =Any

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 becausethe join inside the subquery it does not make correlated subquery.]

2.The field in the join is from the outer query table... [Either the right or left side of the join should include the field in the outer query]

The execution of the correlated sub query is like join...

Example: select cname from customers where exists ( select cid from orders where customers.id=orders.id); 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...

It(Exist) is Intersection of the values in the different table..

But simple query Not Exist is equal to Difference

select cname from customers where cid in ( select * from orders ); // Error . We can not compare one field with many fields.

Page 65: Query

65

Query - Page #13

select cname from customers where exists ( select * from orders where customers.id=orders.id); // It would not give any error because the inner query will give only boolean values.... --------------------------------------------------------------------------------------------------------

7-01-2002:

select distinct a.au_fname from authors a, authors bwhere a.state = b.state and a.au_id <> b.au_id;

Any self join can be carried out through correlated sub query.

select a.au_fnamefrom authors awhere 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 outer table.

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 executed...If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct clause in the correlated sub query.

What is difference between self join and correlated sub query??Ans: The self join continues until all the records matched but the correlated sub query becomes true, it would not go further.

------------------------------------------------------------------------------------------------------------------Union:

It gives common and uncommon things in the two query....

select * into sen_temp_table from authors where state = ’LA’; select * from authors union select * from sen_temp_table; // It will not give the duplicates of the records 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 type needed select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mismatach,If the implicit conversion possible it will work

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 order by au_id; // Allowed 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:

Find total purchase for each customer??????????

Ans:drop vicreate view v_sample asselect 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

select max(tprice) from v_sample

Page 66: Query

66

Query - Page #14

Find which customer purchased more????

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 UserGrant All Table_name to UserRevoke select|update|insert|delete on Table_name from UserRevoke All Table_name from User

select * from syspermissions;sp_pkeys sen_traveller; View: The View is the Projection of the base tables...

Syntax: Create View view_name as select statement

Create view sen_view_empdatasselect eid,ename,did,dname from emp,deptwhere emp.did = dept.did;

Grant select on v_empdat to sa

Step 1:create view sen_view_v1 asselect * 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;

select * from authors;

select * from titles;

*************************************************************************************************

16-January-2002:

The View can include on only "select" statement.

Ex:

create view v1 as select.....

We can use delete,insert,update and select on views. Create view v2 asselect 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

To make work the above statement....

create view v2 asselect pub_id,sum(price) as "Total" from titles group by pub_id (or)create view v2(publishers_id,price) asselect pub_id,sum(price) as "Total" from titles group by pub_id

Page 67: Query

67

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 table emp( empno varchar(20) not null, emp_name varchar(20) not null, salary float not null, dept_id varchar(20) not null, phone varchar(20) not null);

create view v1 as select emp_no,emp_name,dept_id,phone from emp; // It would not work...

create view v1 asselect * form emp; // It will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olnyit 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...

Views using joins: 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...

////////////////////////////////////////////////////////////////////////////////////////////////

create view v_emp asselect * from emp where dept_id = ’HRD’;

select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS table and 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....

select * from emp where sal>2500 and dept_id=’HRD’;

Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpretedas below....

Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....

With Check option: create view v_emp as select * from emp where dept_id=’HRD’ with check option

insert v_emp values(’e1001’,’boris’,’HRD’,2000); // It works fine

insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view hasbeen created by with check option condition. It allow only the where clause condition is match, itmeans that we can insert only ’HRD’ type......

/////////////////////////////////////////////////////////////////////////////////////////////////

Question: Find which type sales is greater???

We can not write in single select statement....

create view sen_v1 as

Page 68: Query

68

Query - Page #16

select type,sum(price)as "Total_sales" from titles group by type

select type,max(Total_sales) from sen_v1 group by type,Total_sales having Total_sales= (select max(Total_sales) from sen_v1)

select type from sen_vl where Total_sales =(select max(Total_sales) from sen_v1)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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. One procedure can have 1024 parameters.

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...

create procedure procedure_name[(parameters)] [ ]--->optional as sql statements;

create procedure pro as select * from authors,publishers where authors.city = publishers.city;

create procedure pro as select * from emp; // In this statement,While creating procedure, it checks only the syntax errors it will not check the existence of the objets. In other words the object need not be existence while creating procedures but view the objects has to exist.

create procedure pro as select sal from emp; // In this statement, it checks the existence of the object,if it is, itchecks the existence of the column, if it is, the procudure will be created...if the column doesnot exist,it will give error....If there is non existence of the object,it will not check the existence of the column,the procedure will be created....

Either existence of object or non-existence of the object,the procedure will be created....

The created procedure have an entry in sysobjects table.....The statements are used in procedure will be stored in syscomments table. To execute the procedure...

Exec pro // while creating procudure, it checks only the syntax, while executing, the compilationprocess is done..

select object_id (’demo’); // we can get the table id what the sql server maintains...

create procedure pro(parameters) with recompileas sql statements; // It will be recompiled for every execution of this procedure.....

//////////////////////////////////////////////////////////////////////////////////////////////what is Query plan????

The query plan is nothing but the path of the execution in the sql statements...

Exec pro;

step 1: the procedure is compiled step 2: creates query plan,this query plan is stord in procedure cache it is like obj file step 3: it executes the obj file and gives the output....

The step 1 and step 2 will be executed at the first execution of the procedure..if u executethe procedure another time, it will no go for compilation process,it just checks the procedure

Page 69: Query

69

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:

Create procedure sen_sample_procedure(@param varchar(20)) as -- sen_sample_procedure(@param varchar(20) = ’psychology’)// default parameter -- sen_sample_procedure(@param varchar(20) = ’psychology’,@price=20.0) // Overridding default parameters declare @price float

select @price = sum(price) from titles group by type having type = @param;

if(@price <=100) return 1; if(@price>100 and @price<=200) return 2; if(@price >200) return 3;

-------------------------------------

declare @ret int

exec @ret=sen_sample_procedure ’psychology’ --exec @ret=sen_sample_procedure default,50 // Overridding default parameters --exec @ret=sen_sample_procedure @price=50,@param=’business’ // Explicit passing values if @ret = 1 begin select "Return 1"; end if @ret = 2 begin select "Return 2"; end

if @ret = 3 begin select "Return 3"; end

Note: The TSQL does not contain for loop,arrays..... goto,else,break are there

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

declare @value int,@expr int select @value = case @ex when 1 then only one value when 2 then only one value when 3 then only one value

Note: To assign to value to variable select @ret = 1; (or) set @ret = 1;

Example:

SELECT ’Price Category’ = CASE WHEN price IS NULL THEN ’Not yet priced’ WHEN price < 10 THEN ’Very Reasonable Title’ WHEN price >= 10 and price < 20 THEN ’Coffee Table Title’ ELSE ’Expensive book!’

END,title AS ’Shortened Title’ FROM titles

Example

Page 70: Query

70

Query - Page #18

declare @ret int set @ret = 1 select @ret =

case(@ret) when 1 then 10 when 2 then 20 when 3 then 30

end select @ret /////////////////////////////////////////////////////////////////////////////////////////////////

19-01-2002:

Output Parameters:

Question: Write the procedure to find the city and state of the given publishers????

create procedure sen_pro(@pub_name varchar(20), @city varchar(20) output, @state varchar(20) output) as select @state=state,@city=city from publishers where pub_name like @pub_name;

create procedure sen_callpro(@param varchar(20)) as declare @rstate varchar(20); declare @rcity varchar(20); exec sen_pro @param,@city=@rcity output,@state=@rstate output; select "pub state " + @rstate; select "pub city " + @rcity;

exec sen_callpro "New Moon Books";------------------------------------------------------------------------------------------------

Question: Write a procedure to check the given title_id has been written 2 authors, if so print the 2 author names

Create procedure sen_proce(@t_id varchar(20)) as declare @a varchar(20) if exists(select ta.title_id from titleauthor ta,titles t where ta.title_id=t.title_id and t.title_id = @t_id group by ta.title_id having count(*) = 2) begin select ta.au_id into #temp from titleauthor ta,titles t where ta.title_id = t.title_id and t.title_id = @t_id; select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a delete from #temp where au_id = @a select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a end else print "the book does not have exactly 2 authors" exec sen_proce ’PS2091’

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:

create proc pro asgoto aa:print "dgs"-------------------------------------------------------------------------------------------------

21-January-2002:

E-R Diagram: Entity: The entity is an object about information can be recorded..

Page 71: Query

71

Query - Page #19

For example, the employee and dept entity has some relationship between them...

The are 3 different types of relationship....

1. One to One2. One to Many3. Many to Many

{Chen notation}

[Entity] [Relation] [Entity]Employee---------- Works In ----------------Dept|[Rect] [Diamond] [Rect]||-------has --------Address [Diamond] [Rect]

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] andone to many[right to left] realationship comes either side,Take a one to many relationship...)

Employee(Optional-entity) Dept ( Optional-entity)eid did did dname(Attributes) (Attributes)e1 d1 d1e2 d1 d2e3 d2 d3e4 d2 (one dept can have zero or many employees)e5 null (employee has not been assigned to zero or one dept)

Cardinality: no of occurences of field value in dependant entity...

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...)

2.emp(1,M) one employee has one or many address.. address(1,1) one address has only one employee.. emp has existence dependent with address (address can not be created before emp so we change to Address has existence dependent with 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..)

Example:(one to many relationship) ( contains two Tables) [Rect] [Diamond] [Rect] Professor -------------- Advises -----------Student [Entity](0,N) [Entity](1,1)

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]

Example:(one to one relationship) ( contains only one table)

[Rect] [Diamond] [Rect] Professor -------------- is allotted -----------Room [Entity](0,1) [Entity](0,1)

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 ]

Example:(Many to Many relationship) ( contains 3 tables)

[Rect] [Diamond rounded square] [Rect] Theater -------------- is shown ---------------- Films [Composite Entity](1,N) [Composite Entity](1,N)

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 ]

Page 72: Query

72

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...

Theatre (entity) Films (entity) TheatreFilm (Associative Entity) or Junction Table ------------------------------------------------------------------------------------------ tid (pk) fid (pk) tid tname fname fid no_seats hero composite primary key(tid,fid) location heroine

Example:(Many to Many relationship) ( contains three tables)

[Rect] [Diamond rounded square] [Rect] Authors -------------- Writes ------------------ titles [Composite Entity](1,N) [Composite Entity](1,N)

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 qurey...

Any database desin normally will not go beyond the third normal form....

First Normal from: Drive the table using E-R Diagrams... (*) Any table should have atomic values(Every field should record atomic information)

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 record...and take to consideration the table should not have more null value fields.

Example:

eid pid did nohrs dhead-------------------------- e1 p1 is 20 boris e2 p1 is 20 boris e3 p2 net 30 peter e4 p2 net 30 sampry e1 p2 is 30 Andrew

* Primary key should be identified [ composite primary key(eid,pid) ] ---------------------------------------------------------------------------------------------------------

Second Normal Form:

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 id 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 entrily on the primary key and put it separate table along with the field on which the non key attribute is dependent on...

so we take off did from the above table

eid did ---------

Page 73: Query

73

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 eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

---------------------------------------------------------------------------------------------------------Third Normal Form: All the non key attributes should be dependent only on the primary key

eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only thedid which is not a primary key of the table....

Take the dhead along with it is dependent....

did dhead-------------- IS boris NET peter

----------------------------------------------------------------------------------------------------------

Database is a collection of data with controlled redundancy.....

*************************************************************************************************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 deleteany enty in the master table,which is refered by in the child table...The SQL server maintainsrestrictions automatically...The cascade deletions is opposite of these restrictions....

Syntax:

Create trigger trigger_name on table for operation as SQL Statements....

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 aftertrigger,The SQL could not support Before Triggers.....

Trigger can not accept parameters.....

Page 74: Query

74

Query - Page #22

Book Magazine----------------------------Bid MagidBname MnameAuthor price

Transaction--------------TidCard_idbook_idissue_datereturn_date--------------------------------------------------------------------------------------------------Implementing primary key constraint:-

Create trigger tri on tempfor insert asdeclare @icount intselect @icount=count(*) from temp,insertedwhere temp pk = insert pkif @icount >1begin print ’Duplicate Record’ rollbackendelse print ’Successfully on inserting the record’

inserted--->trigger test table (or) magic table-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on empfor insert asif not exists(select * from dept,inserted wheredept.did=inserted.did)begin print "Integrity violation" rollback;endelse print "successfull insertion into the table"

emp inserted----------------------------------------------------e1 boris d1 d1 HRDe2 becker d2 d2 SYSe3 sapeg d3

-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on trans_member for insert asif not exists (select * from books,inserted where book.book_id =inserted.book_id)begin if not exists (select * from magazines inserted where magizines.mag_id = inserted.book_id) begin print ’Ref integrity violation’ rollback end else print ’Successfully inserted into the table’endelse print ’Successfully inserted into the table’

Page 75: Query

75

Query - Page #23

-------------------------------------------------------------------------------------------------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:-

Create trigger dtrion publishersfor deleteasdelete from titles where titles.pub_id = deleted.pub_id

publisher table-->Trigger Table

The value from Trigger table is moved into Trigger Test Table (Deleted Table) -------------------------------------------------------------------------------------------------Implementing Restriction on deletion:-

Create trigger dtrion publishersfor deleteasif exists( select * from titles,deleted where titles.pub_id=deleted.pub_id)begin print ’Attempt to create orphan Records’ rollbackend

------------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables?????

Hits provided:declare @i intselect @i=Object_id(’publishers’)

if exists(select * from sysobjects where id=@i) insert back_up select * from deleted

------------------------------------------------------------------------------------------------

31-JAN-2002:

customers invoice products----------------------------------------------cid oid pidcname cid pname pid qoh (quantity in hand) qty price

create trigger trion invoicefor insertasupdate products set qoh=qoh-inserted.qty from products,insertedwhere products.pid=inserted.pid

checking the availability of products:---------------------------------------

select @iqty = inserted.qty from insertedselect @qty = products.qty from inserted,productswhere inserted.pid=products.pidif(@qty<@iqty)begin print "invalid transaction" rollback returnend

Page 76: Query

76

Query - Page #24

-------------------------------------------------------------------------------------------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 invoicefor updateif update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback returnendif not exists (select * from products,insertedwhere inserted.productid=products.proudctidbegin print ’Fk violation on products’ rollback returnend--------------------------------------------------------------------------------------------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..........

The cursor contains following five ’jargons’

1....Declare2....Open3....Fetch4....Close5....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

// The scroll keyword is used to move the cursor up and down...declare cur cursor scroll for select c_id,title,author,publisher from sen_catlog

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;

Note: When closing the cursor, it destroies the result set.....-------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Page 77: Query

77

Query - Page #25

Note: It destroies the cursor [ like dropping tables ] -------------------------------------------------------------------------------------------------

Example with procedure:-

create procedure sen_cur_pro asdeclare cur cursor scrollforselect * from sen_catlogopen curfetch next from curwhile(@@fetch_status=0)begin fetch next from curendclose curdeallocate cur

exec sen_cur_pro;

Note: @@fetch_status is system defined global variable which is automatically set to 0 whichindicates for successful fetch...------------------------------------------------------------------------------------------------1-02-2002:

Application of Cursors:

Create procedure sen_cpro asdeclare @tid varchar(20),@title varchar(20),@price floatdeclare cur cursor scrollforselect title_id,title,price from titlesopen curfetch next from cur into @tid,@title,@pricewhile(@@fetch_status=0)begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@priceendclose curdeallocate cur

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??????

create procedure sen_publisher_books asset nocount ondeclare @pid varchar(20),@pname varchar(20)declare @tid varchar(20),@title varchar(20),@price floatdeclare @n intdeclare cur cursor scrollforselect pub_id,pub_name from publishersopen curfetch next from cur into @pid,@pnamewhile(@@fetch_status=0)begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid

Page 78: Query

78

Query - Page #26

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,@pnameendclose curdeallocate cur exec sen_publisher_books --------------------------------------------------------------------------------------------------------------2-Feb-2002:

Indexing: It is a sorting process to reduce the searching process time....

Syntax:

Create { nonClustered } index index_nameon table_name(field_name)

Default is Clustered indexing................-------------------------------------------------------------------------------------------------NonClustered:

create nonclustered index emp_enoon emp(eno)

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 orit 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:

create clustered index emp_enoon emp(eno)

The table itself will be sorted on a field name

-----------------------------------------------------------------------------------------------Note: The clustered index points the page...but the nonclustered index points the exact match ofrecord...

1...The Clusterd index is efficiant for duplicte records ( Foreign key)2...The nonClustered index is efficient for unique records (primary key), for the primary key creation the SQL server creates Clusterd index, it is our responsiblity to give nonClusterd index when creating the primary key......------------------------------------------------------------------------------------------------Note: One Clustered index is allowed for a table, but as many nonClustered index is allowed for a table------------------------------------------------------------------------------------------------

Page 79: Query

79

Query - Page #1

------------------SQL NOTE -------------------------------------------------------------- Author : E Senthil -----------------------------------------------------------------------------------------

// Create A Table with out primary key

CREATE TABLE sen_emp ( empno int, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int );

************************************************************************************************// Set Primary key with ALTER TABLE COMMAND

ALTER TABLE sen_emp ALTER COLUMN empno int not null; ALTER TABLE sen_emp ADD CONSTRAINT __PK PRIMARY KEY (empno);

// Before Adding PRIMARY KEY CONSTRAINT TO A COLUMN, // make sure it should not accept null values **********************************************************************************************// Create A Table with a Primary key

create table sen_dept ( dept_no int constraint _pk primary key, dname char(20), location char(20) );

********************************************************************************************* // Set Referencial Integrity [ Joining two tables ]

Alter table sen_emp Add constraint _fk foreign key(dept_no)references sen_dept(dept_no);

*********************************************************************************************// Create a table with primary key and foreign key

CREATE TABLE sen_emp ( empno int CONSTRAINT PK PRIMARY KEY, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int CONSTRAINT FK FOREIGN KEY REFERENCES sen_dept(dept_no) );

***********************************************************************************************// Droping a Constraint

ALTER TABLE sen_emp DROP CONSTRAINT __PK;

*************************************************************************************************// Droping a Column in a Table

ALTER TABLE sen_emp DROP COLUMN empno;

***********************************************************************************************// Create a Table with default value

CREATE TABLE _TEMP ( empno int,

Page 80: Query

80

Query - Page #2

ename varchar(20), city varchar(20) default ’cbe’);

// Add a Default value to a column

ALTER TABLE _TEMP ADD default ’sen’ for ename;

//Drop the Default constraint from a column

ALTER TABLE _TEMP DROP CONSTRAINT DF___TEMP__CITY__6C6E1476 ***********************************************************************************************// Creating Check Constraint for a column

ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );

*****************************************************************************************// Disabling Check constraint

ALTER TABLE _temp NOCHECK CONSTRAINT CKEMPNO;

// RE-Enabling Check constraint

ALTER TABLE _temp CHECK CONSTRAINT CKEMPNO;

******************************************************************************************// Create a new table and copy only some particular fields of another Table

select empno,second_name,salary into temp_sen_emp from sen_emp;

******************************************************************************************//Create A Table and copy the data from another Table

Create Table vinod ( name varchar(20) );

insert into vinod select second_name from sen_emp;

******************************************************************************************

select * from authors;

select * from authors where au_lname like ’[^a-r]%’;select * from authors where au_lname like ’[a-r]%’;select * from authors where au_lname like ’_[a-r]%’;

select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’

select * from sen_emp;

insert into sen_emp (empno,second_name) values (1500,’gallifer’);

*********************************************************************************************Grouping:

select sum(salary) from sen_emp;

select * from sen_emp;

select sum(salary) from sen_emp group by dept_no;

select sum(price) from titles group by type;

select sum(price) from titles;

select * from titles order by type;

select * from titles;

select sum(price) from titles group by type;

Page 81: Query

81

Query - Page #3

select sum(price) from titles;

select sum(price) as total_salary from titles;

select sum(price) "Total_salary" from titles;

select * from sen_emp;

select dept_no,sum(salary)’Total Salary’ from sen_emp group by dept_no order by dept_no;

select type, sum(type) from titles;

select sum(salary) from sen_emp order by dept_no group by dept_no; // Error

______________________________________________________________________________________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) from titles group by type,pub_id;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id order by type;

select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id desc;

sp_help titles

select type,sum(price) from titles group by type;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id

******************************************************************************************// Select keywords SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]******************************************************************************************

SELECT TYPE,PUB_ID,SUM(PRICE) "TOTAL PRICE"FROM TITLESGROUP BY TYPE,PUB_ID;

SELECT *FROM TITLESORDER BY TYPE DESC;

//////////////////////////////////////////////////////////////////////////////////////////select type,sum(price)from titlesgroup by typeorder 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 titlesgroup by typeorder by title_id; // Error

select type,title_id,sum(price)from titlesgroup by type,title_idorder by title_id;

select * from titles;

Page 82: Query

82

Query - Page #4

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:-----------------

select type,sum(price) from titles group by type; Result set Business 1100 Computer 700 Novel 800

Compute By class:

select type,sum(price) from titles compute by type; // error

select type,price from titlesorder by type compute sum(price) by type; Rule: 1.Whenever we use compute By class, it must to use order by class. 2.The field which appear in compute by class is must appear in order by class 3.Whatever field in the aggregate funtion, which is also in the select list.

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 itselfable to generate Work Table...So the Compute by class relay order by class...

select type,pricefrom titlesorder by pub_idcompute 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 ofprice by Type...’

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type;

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by pub_id; // Error

Reason: Work Table

Type pub_id Price--------------------------Business p1 200Business p1 200Business p2 300Computer p2 400

Page 83: Query

83

Query - Page #5

Computer p2 200Novel p1 200Novel p1 240Novel p2 450

In above work table, The pub_id is clubed according to the Typenot clubed alone...That is why it will flash error...

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type,pub_id;

select type,pub_id,title_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id,title_id;

select type,pub_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id;****************************************************

Afternoon:21-dec-2001

select type,pub_id from titles;

1...select distinct type,pub_id from titles;

2...select type,pub_id from titles group by type,pub_id;

Query 1 and 2 give the same result

select type,pub_id from titlesgroup by type,pub_id;

select distinct type,pub_id from titles;

// In the above query.. The Distinct applies both type and pub_id columns..We can not make to applyfor a particular column. It will apply all the columns in the select list

For Ex

Business p1 200Business p1 400Business p1 300Computer p2 500Computer p2 700

The Result is

Business p1 200Computer p2 500

/////////////////////////////////////////////////select type,sum(price),avg(price)from titlesgroup by price; // Error

Reason: The field name in group by clause which is not used in aggregate function in select list

Page 84: Query

84

Query - Page #6

//////////////////////////////////////////////////////////

Having: Having clause should have group by class...but when using group by class it is optionalto use Having clause.

It affects the result of the Group By Class......

Work Table -----> Internal Result Set -----> Output

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...

Both 1 and 2 are gives same result......

Query 2 Work Table:

Olny Business Records are present

But Query 1 Work Table: All types of Records like Business,Computer and Novel and then take Business Records are Filtered

///////////////////////////////////////////////////////////////////////////////

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

// It would not work Reasons: 1. The left hand side of the where class shoul be column name... 2. Here The Group by class run after the where class...but where class we used aggregate functions...This aggregate function will not use group by class..

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select type,sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

/////////////////////////////////////////////////////////////////////////////////////////////////

December-26-2001

Joins:

select * from authors,publishers; // It does the cartisean product of two tables....

Page 85: Query

85

Query - Page #7

if the select statement contains more table in from clause without where clause, it is calledcross joining which is never used...

select * from authors,publisherswhere authors.city = publishers.city;

Joins are evaluated just like Nested Loops....

for(i=0;i<=10;i++) One Table for(j=0;j<=5;j++) Another Table if(i==j) Where clause condition { }

select authors.au_id,authors.au_lname,authors.phone,publishers.pub_id,publishers.pub_name,publishers.cityfrom authors,publishers where authors.city = publishers.city;

select authors.*,pub_id,pub_name from authors,publisherswhere 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, publishers p where authors.city=p.city;

select p.*,au_id,au_lnamefrom authors a, publishers pwhere a.city = p.city and a.au_lname like ’c%’

select p.*,au_id,au_lnamefrom authors a, publishers pwhere au_lname like ’c%’ and a.city = p.city

Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select * from authors; select * from publishers; select * from titles; select * from titleauthor;

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:.................

Page 86: Query

86

Query - Page #8

Explanation:

Title: Authors

au_id au_lname ----------- ----------------------------a1 lockleya2 peter

Table: Publisher

pub_id pub_name ------ -----------p1 samyp2 golgotiap3 samba

Table: Titles

title_id pub_id -------- --------t1 p1t2 p2t3 p3

Table: TitleAuthor

au_id title_id ----------- -------- a1 t1a1 t2a2 t1a2 t3

Virtual Tables:

[Authors] [TitleAuthor]aid aname au_id title_ida1 lockey a1 t1a1 lockey a1 t2

[authors] [titleAuthor] [titles]aid aname aid title_id title_id pub_ida1 lockey a1 t1 t1 p1a1 lockey a1 t2 t2 p2

[authors] [titleAuthor] [ titles ] [ publisher]aid aname aid title_id title_id pub_id pub_id pub_name a1 lockey a1 t1 t1 p1 p1 sams a1 lockey a1 t2 t2 p2 p2 golgotia

FAQ:

1. How the joins are works???

Ans: It works as Nested Loops

2.What is the Query Optimizer? Ans: The Query optimizer find out which join will be evaluated first and run the query in the optimized way....

3. How many Virtual Table created for N conditions??

Page 87: Query

87

Query - Page #9

Ans: (N-1) Virtual Tables are created for N tables

Cross Checking:

select * from authors where au_lname like ’Loc%’;select * from titleauthor where au_id = ’486-29-1786’; select * from titles where title_id=’PC9999’ or title_id=’PS7777’; select * from publishers where pub_id =’1389’ or pub_id=’0736’;

////////////////////////////////////////////////////////////////////////////////////////////////

Renaming the Tables

sp_rename <OldTable> <NewTable>

////////////////////////////////////////////////////////////////////////////////////////////////

Taking a Copy of the Table:

Create Table vinod_temp( eno int identity(1,1), ename varchar(20), dept_id int);

insert into vinod_temp(ename,dept_id) select ename,dept_id from sen_temp;////////////////////////////////////////////////////////////////////////////////////////////////

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

Result set would be A1A6A2A3

select a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays duplicate Records

Page 88: Query

88

Query - Page #10

select state,count(*) from authorsgroup by statehaving count(*)>1 // We should not use group by function in the self joining situations

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays distinct records but it dispalys one author lives in the city

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered...

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id order by a.city; // It displays the perfect result Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Create Table patdat( patno varchar(20) not null, name varchar(20) not null, address varchar(20));

Create Table patadm( patno varchar(20) not null, admno varchar(20) not null, addate datetime, constraint sen_pk2 primary key(patno,admno), constraint fk foreign key(patno) references patdat1(patno));

Create Table operdat( patno varchar(20), admno varchar(20), opno int, opdate datetime, type varchar(20)

constraint sen_pk2 primary key(patno,admno,opno), constraint sen_fk foreign key(patno) references patdat(patno), constraint fk1 foreign key(admno) references patadm1(admno) );

Note: constaint fk1 could not be created.... ’We can not refer the part of the primary key(composite key) in another Table’

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Question: Find the author id who has written more than one book??? select distinct ta1.au_id from titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id;

Question: Find the title_id which has been written by more than one author?

select distinct ta1.title_id from titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id;

Question: Find the author Names who has written more than one book???

Page 89: Query

89

Query - Page #11

select distinct a.au_lname,a.au_fname from authors a,titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id and ta1.au_id = a.au_id;

Question: Find the titles which has been written by more than one author? select distinct t.title from titles t,titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id and ta1.title_id = t.title_id;

/////////////////////////////////////////////////////////////////////////////////////////////////Jan 02 2002:

Outer join: emp e1 boris HRDe2 becker HRDe3 peter SYSe4 Anderw SYSe5 Lafer null

dep

HRD Human ResSYS SystemsPER personalNET network

emp

enoenamed_id

dept

ddiddname

Display the emp details along with dept id??

select emp.* d.did from emp e,dept dwhere e.did=d.did

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYS

select emp.*,d.did from e,dept dwhere e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax)

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYSe5 lafer

select emp.*,d.did from e,dept dwhere e.did =* d.did; // Display the matching records and addition to all

Page 90: Query

90

Query - Page #12

unmatching records form dept (SQL Server Syntax)

select * from employee inner join dept on e.deptid=d.detptid (ANSI Syntax)

The above two query gives the same result..

////////////////////////////////////////////////////////////////////////////////////////////

Full outer join: select employee.eno,employee.name,d.did from employee full outer join dept on employee.did=dept.did (ANSI Syntax) [ Where <filter condition> ]

///////////////////////////////////////////////////////////////////////////////////////////////

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;

select * from titles where price = (select max(price) from titles);**************************************************************************************************

Jan-04-2002:

Exists: select cname from customers where exists ( select cid from orders where customers.id=orders.id);

Exists has equal meaning of =Any

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 becausethe join inside the subquery it does not make correlated subquery.]

2.The field in the join is from the outer query table... [Either the right or left side of the join should include the field in the outer query]

The execution of the correlated sub query is like join...

Example: select cname from customers where exists ( select cid from orders where customers.id=orders.id); 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...

It(Exist) is Intersection of the values in the different table..

But simple query Not Exist is equal to Difference

select cname from customers where cid in ( select * from orders ); // Error . We can not compare one field with many fields.

Page 91: Query

91

Query - Page #13

select cname from customers where exists ( select * from orders where customers.id=orders.id); // It would not give any error because the inner query will give only boolean values.... --------------------------------------------------------------------------------------------------------

7-01-2002:

select distinct a.au_fname from authors a, authors bwhere a.state = b.state and a.au_id <> b.au_id;

Any self join can be carried out through correlated sub query.

select a.au_fnamefrom authors awhere 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 outer table.

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 executed...If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct clause in the correlated sub query.

What is difference between self join and correlated sub query??Ans: The self join continues until all the records matched but the correlated sub query becomes true, it would not go further.

------------------------------------------------------------------------------------------------------------------Union:

It gives common and uncommon things in the two query....

select * into sen_temp_table from authors where state = ’LA’; select * from authors union select * from sen_temp_table; // It will not give the duplicates of the records 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 type needed select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mismatach,If the implicit conversion possible it will work

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 order by au_id; // Allowed 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:

Find total purchase for each customer??????????

Ans:drop vicreate view v_sample asselect 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

select max(tprice) from v_sample

Page 92: Query

92

Query - Page #14

Find which customer purchased more????

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 UserGrant All Table_name to UserRevoke select|update|insert|delete on Table_name from UserRevoke All Table_name from User

select * from syspermissions;sp_pkeys sen_traveller; View: The View is the Projection of the base tables...

Syntax: Create View view_name as select statement

Create view sen_view_empdatasselect eid,ename,did,dname from emp,deptwhere emp.did = dept.did;

Grant select on v_empdat to sa

Step 1:create view sen_view_v1 asselect * 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;

select * from authors;

select * from titles;

*************************************************************************************************

16-January-2002:

The View can include on only "select" statement.

Ex:

create view v1 as select.....

We can use delete,insert,update and select on views. Create view v2 asselect 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

To make work the above statement....

create view v2 asselect pub_id,sum(price) as "Total" from titles group by pub_id (or)create view v2(publishers_id,price) asselect pub_id,sum(price) as "Total" from titles group by pub_id

Page 93: Query

93

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 table emp( empno varchar(20) not null, emp_name varchar(20) not null, salary float not null, dept_id varchar(20) not null, phone varchar(20) not null);

create view v1 as select emp_no,emp_name,dept_id,phone from emp; // It would not work...

create view v1 asselect * form emp; // It will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olnyit 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...

Views using joins: 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...

////////////////////////////////////////////////////////////////////////////////////////////////

create view v_emp asselect * from emp where dept_id = ’HRD’;

select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS table and 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....

select * from emp where sal>2500 and dept_id=’HRD’;

Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpretedas below....

Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....

With Check option: create view v_emp as select * from emp where dept_id=’HRD’ with check option

insert v_emp values(’e1001’,’boris’,’HRD’,2000); // It works fine

insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view hasbeen created by with check option condition. It allow only the where clause condition is match, itmeans that we can insert only ’HRD’ type......

/////////////////////////////////////////////////////////////////////////////////////////////////

Question: Find which type sales is greater???

We can not write in single select statement....

create view sen_v1 as

Page 94: Query

94

Query - Page #16

select type,sum(price)as "Total_sales" from titles group by type

select type,max(Total_sales) from sen_v1 group by type,Total_sales having Total_sales= (select max(Total_sales) from sen_v1)

select type from sen_vl where Total_sales =(select max(Total_sales) from sen_v1)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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. One procedure can have 1024 parameters.

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...

create procedure procedure_name[(parameters)] [ ]--->optional as sql statements;

create procedure pro as select * from authors,publishers where authors.city = publishers.city;

create procedure pro as select * from emp; // In this statement,While creating procedure, it checks only the syntax errors it will not check the existence of the objets. In other words the object need not be existence while creating procedures but view the objects has to exist.

create procedure pro as select sal from emp; // In this statement, it checks the existence of the object,if it is, itchecks the existence of the column, if it is, the procudure will be created...if the column doesnot exist,it will give error....If there is non existence of the object,it will not check the existence of the column,the procedure will be created....

Either existence of object or non-existence of the object,the procedure will be created....

The created procedure have an entry in sysobjects table.....The statements are used in procedure will be stored in syscomments table. To execute the procedure...

Exec pro // while creating procudure, it checks only the syntax, while executing, the compilationprocess is done..

select object_id (’demo’); // we can get the table id what the sql server maintains...

create procedure pro(parameters) with recompileas sql statements; // It will be recompiled for every execution of this procedure.....

//////////////////////////////////////////////////////////////////////////////////////////////what is Query plan????

The query plan is nothing but the path of the execution in the sql statements...

Exec pro;

step 1: the procedure is compiled step 2: creates query plan,this query plan is stord in procedure cache it is like obj file step 3: it executes the obj file and gives the output....

The step 1 and step 2 will be executed at the first execution of the procedure..if u executethe procedure another time, it will no go for compilation process,it just checks the procedure

Page 95: Query

95

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:

Create procedure sen_sample_procedure(@param varchar(20)) as -- sen_sample_procedure(@param varchar(20) = ’psychology’)// default parameter -- sen_sample_procedure(@param varchar(20) = ’psychology’,@price=20.0) // Overridding default parameters declare @price float

select @price = sum(price) from titles group by type having type = @param;

if(@price <=100) return 1; if(@price>100 and @price<=200) return 2; if(@price >200) return 3;

-------------------------------------

declare @ret int

exec @ret=sen_sample_procedure ’psychology’ --exec @ret=sen_sample_procedure default,50 // Overridding default parameters --exec @ret=sen_sample_procedure @price=50,@param=’business’ // Explicit passing values if @ret = 1 begin select "Return 1"; end if @ret = 2 begin select "Return 2"; end

if @ret = 3 begin select "Return 3"; end

Note: The TSQL does not contain for loop,arrays..... goto,else,break are there

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

declare @value int,@expr int select @value = case @ex when 1 then only one value when 2 then only one value when 3 then only one value

Note: To assign to value to variable select @ret = 1; (or) set @ret = 1;

Example:

SELECT ’Price Category’ = CASE WHEN price IS NULL THEN ’Not yet priced’ WHEN price < 10 THEN ’Very Reasonable Title’ WHEN price >= 10 and price < 20 THEN ’Coffee Table Title’ ELSE ’Expensive book!’

END,title AS ’Shortened Title’ FROM titles

Example

Page 96: Query

96

Query - Page #18

declare @ret int set @ret = 1 select @ret =

case(@ret) when 1 then 10 when 2 then 20 when 3 then 30

end select @ret /////////////////////////////////////////////////////////////////////////////////////////////////

19-01-2002:

Output Parameters:

Question: Write the procedure to find the city and state of the given publishers????

create procedure sen_pro(@pub_name varchar(20), @city varchar(20) output, @state varchar(20) output) as select @state=state,@city=city from publishers where pub_name like @pub_name;

create procedure sen_callpro(@param varchar(20)) as declare @rstate varchar(20); declare @rcity varchar(20); exec sen_pro @param,@city=@rcity output,@state=@rstate output; select "pub state " + @rstate; select "pub city " + @rcity;

exec sen_callpro "New Moon Books";------------------------------------------------------------------------------------------------

Question: Write a procedure to check the given title_id has been written 2 authors, if so print the 2 author names

Create procedure sen_proce(@t_id varchar(20)) as declare @a varchar(20) if exists(select ta.title_id from titleauthor ta,titles t where ta.title_id=t.title_id and t.title_id = @t_id group by ta.title_id having count(*) = 2) begin select ta.au_id into #temp from titleauthor ta,titles t where ta.title_id = t.title_id and t.title_id = @t_id; select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a delete from #temp where au_id = @a select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a end else print "the book does not have exactly 2 authors" exec sen_proce ’PS2091’

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:

create proc pro asgoto aa:print "dgs"-------------------------------------------------------------------------------------------------

21-January-2002:

E-R Diagram: Entity: The entity is an object about information can be recorded..

Page 97: Query

97

Query - Page #19

For example, the employee and dept entity has some relationship between them...

The are 3 different types of relationship....

1. One to One2. One to Many3. Many to Many

{Chen notation}

[Entity] [Relation] [Entity]Employee---------- Works In ----------------Dept|[Rect] [Diamond] [Rect]||-------has --------Address [Diamond] [Rect]

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] andone to many[right to left] realationship comes either side,Take a one to many relationship...)

Employee(Optional-entity) Dept ( Optional-entity)eid did did dname(Attributes) (Attributes)e1 d1 d1e2 d1 d2e3 d2 d3e4 d2 (one dept can have zero or many employees)e5 null (employee has not been assigned to zero or one dept)

Cardinality: no of occurences of field value in dependant entity...

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...)

2.emp(1,M) one employee has one or many address.. address(1,1) one address has only one employee.. emp has existence dependent with address (address can not be created before emp so we change to Address has existence dependent with 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..)

Example:(one to many relationship) ( contains two Tables) [Rect] [Diamond] [Rect] Professor -------------- Advises -----------Student [Entity](0,N) [Entity](1,1)

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]

Example:(one to one relationship) ( contains only one table)

[Rect] [Diamond] [Rect] Professor -------------- is allotted -----------Room [Entity](0,1) [Entity](0,1)

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 ]

Example:(Many to Many relationship) ( contains 3 tables)

[Rect] [Diamond rounded square] [Rect] Theater -------------- is shown ---------------- Films [Composite Entity](1,N) [Composite Entity](1,N)

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 ]

Page 98: Query

98

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...

Theatre (entity) Films (entity) TheatreFilm (Associative Entity) or Junction Table ------------------------------------------------------------------------------------------ tid (pk) fid (pk) tid tname fname fid no_seats hero composite primary key(tid,fid) location heroine

Example:(Many to Many relationship) ( contains three tables)

[Rect] [Diamond rounded square] [Rect] Authors -------------- Writes ------------------ titles [Composite Entity](1,N) [Composite Entity](1,N)

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 qurey...

Any database desin normally will not go beyond the third normal form....

First Normal from: Drive the table using E-R Diagrams... (*) Any table should have atomic values(Every field should record atomic information)

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 record...and take to consideration the table should not have more null value fields.

Example:

eid pid did nohrs dhead-------------------------- e1 p1 is 20 boris e2 p1 is 20 boris e3 p2 net 30 peter e4 p2 net 30 sampry e1 p2 is 30 Andrew

* Primary key should be identified [ composite primary key(eid,pid) ] ---------------------------------------------------------------------------------------------------------

Second Normal Form:

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 id 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 entrily on the primary key and put it separate table along with the field on which the non key attribute is dependent on...

so we take off did from the above table

eid did ---------

Page 99: Query

99

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 eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

---------------------------------------------------------------------------------------------------------Third Normal Form: All the non key attributes should be dependent only on the primary key

eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only thedid which is not a primary key of the table....

Take the dhead along with it is dependent....

did dhead-------------- IS boris NET peter

----------------------------------------------------------------------------------------------------------

Database is a collection of data with controlled redundancy.....

*************************************************************************************************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 deleteany enty in the master table,which is refered by in the child table...The SQL server maintainsrestrictions automatically...The cascade deletions is opposite of these restrictions....

Syntax:

Create trigger trigger_name on table for operation as SQL Statements....

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 aftertrigger,The SQL could not support Before Triggers.....

Trigger can not accept parameters.....

Page 100: Query

100

Query - Page #22

Book Magazine----------------------------Bid MagidBname MnameAuthor price

Transaction--------------TidCard_idbook_idissue_datereturn_date--------------------------------------------------------------------------------------------------Implementing primary key constraint:-

Create trigger tri on tempfor insert asdeclare @icount intselect @icount=count(*) from temp,insertedwhere temp pk = insert pkif @icount >1begin print ’Duplicate Record’ rollbackendelse print ’Successfully on inserting the record’

inserted--->trigger test table (or) magic table-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on empfor insert asif not exists(select * from dept,inserted wheredept.did=inserted.did)begin print "Integrity violation" rollback;endelse print "successfull insertion into the table"

emp inserted----------------------------------------------------e1 boris d1 d1 HRDe2 becker d2 d2 SYSe3 sapeg d3

-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on trans_member for insert asif not exists (select * from books,inserted where book.book_id =inserted.book_id)begin if not exists (select * from magazines inserted where magizines.mag_id = inserted.book_id) begin print ’Ref integrity violation’ rollback end else print ’Successfully inserted into the table’endelse print ’Successfully inserted into the table’

Page 101: Query

101

Query - Page #23

-------------------------------------------------------------------------------------------------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:-

Create trigger dtrion publishersfor deleteasdelete from titles where titles.pub_id = deleted.pub_id

publisher table-->Trigger Table

The value from Trigger table is moved into Trigger Test Table (Deleted Table) -------------------------------------------------------------------------------------------------Implementing Restriction on deletion:-

Create trigger dtrion publishersfor deleteasif exists( select * from titles,deleted where titles.pub_id=deleted.pub_id)begin print ’Attempt to create orphan Records’ rollbackend

------------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables?????

Hits provided:declare @i intselect @i=Object_id(’publishers’)

if exists(select * from sysobjects where id=@i) insert back_up select * from deleted

------------------------------------------------------------------------------------------------

31-JAN-2002:

customers invoice products----------------------------------------------cid oid pidcname cid pname pid qoh (quantity in hand) qty price

create trigger trion invoicefor insertasupdate products set qoh=qoh-inserted.qty from products,insertedwhere products.pid=inserted.pid

checking the availability of products:---------------------------------------

select @iqty = inserted.qty from insertedselect @qty = products.qty from inserted,productswhere inserted.pid=products.pidif(@qty<@iqty)begin print "invalid transaction" rollback returnend

Page 102: Query

102

Query - Page #24

-------------------------------------------------------------------------------------------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 invoicefor updateif update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback returnendif not exists (select * from products,insertedwhere inserted.productid=products.proudctidbegin print ’Fk violation on products’ rollback returnend--------------------------------------------------------------------------------------------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..........

The cursor contains following five ’jargons’

1....Declare2....Open3....Fetch4....Close5....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

// The scroll keyword is used to move the cursor up and down...declare cur cursor scroll for select c_id,title,author,publisher from sen_catlog

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;

Note: When closing the cursor, it destroies the result set.....-------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Page 103: Query

103

Query - Page #25

Note: It destroies the cursor [ like dropping tables ] -------------------------------------------------------------------------------------------------

Example with procedure:-

create procedure sen_cur_pro asdeclare cur cursor scrollforselect * from sen_catlogopen curfetch next from curwhile(@@fetch_status=0)begin fetch next from curendclose curdeallocate cur

exec sen_cur_pro;

Note: @@fetch_status is system defined global variable which is automatically set to 0 whichindicates for successful fetch...------------------------------------------------------------------------------------------------1-02-2002:

Application of Cursors:

Create procedure sen_cpro asdeclare @tid varchar(20),@title varchar(20),@price floatdeclare cur cursor scrollforselect title_id,title,price from titlesopen curfetch next from cur into @tid,@title,@pricewhile(@@fetch_status=0)begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@priceendclose curdeallocate cur

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??????

create procedure sen_publisher_books asset nocount ondeclare @pid varchar(20),@pname varchar(20)declare @tid varchar(20),@title varchar(20),@price floatdeclare @n intdeclare cur cursor scrollforselect pub_id,pub_name from publishersopen curfetch next from cur into @pid,@pnamewhile(@@fetch_status=0)begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid

Page 104: Query

104

Query - Page #26

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,@pnameendclose curdeallocate cur exec sen_publisher_books --------------------------------------------------------------------------------------------------------------2-Feb-2002:

Indexing: It is a sorting process to reduce the searching process time....

Syntax:

Create { nonClustered } index index_nameon table_name(field_name)

Default is Clustered indexing................-------------------------------------------------------------------------------------------------NonClustered:

create nonclustered index emp_enoon emp(eno)

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 orit 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:

create clustered index emp_enoon emp(eno)

The table itself will be sorted on a field name

-----------------------------------------------------------------------------------------------Note: The clustered index points the page...but the nonclustered index points the exact match ofrecord...

1...The Clusterd index is efficiant for duplicte records ( Foreign key)2...The nonClustered index is efficient for unique records (primary key), for the primary key creation the SQL server creates Clusterd index, it is our responsiblity to give nonClusterd index when creating the primary key......------------------------------------------------------------------------------------------------Note: One Clustered index is allowed for a table, but as many nonClustered index is allowed for a table------------------------------------------------------------------------------------------------

Page 105: Query

105

Query - Page #1

------------------SQL NOTE -------------------------------------------------------------- Author : E Senthil -----------------------------------------------------------------------------------------

// Create A Table with out primary key

CREATE TABLE sen_emp ( empno int, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int );

************************************************************************************************// Set Primary key with ALTER TABLE COMMAND

ALTER TABLE sen_emp ALTER COLUMN empno int not null; ALTER TABLE sen_emp ADD CONSTRAINT __PK PRIMARY KEY (empno);

// Before Adding PRIMARY KEY CONSTRAINT TO A COLUMN, // make sure it should not accept null values **********************************************************************************************// Create A Table with a Primary key

create table sen_dept ( dept_no int constraint _pk primary key, dname char(20), location char(20) );

********************************************************************************************* // Set Referencial Integrity [ Joining two tables ]

Alter table sen_emp Add constraint _fk foreign key(dept_no)references sen_dept(dept_no);

*********************************************************************************************// Create a table with primary key and foreign key

CREATE TABLE sen_emp ( empno int CONSTRAINT PK PRIMARY KEY, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int CONSTRAINT FK FOREIGN KEY REFERENCES sen_dept(dept_no) );

***********************************************************************************************// Droping a Constraint

ALTER TABLE sen_emp DROP CONSTRAINT __PK;

*************************************************************************************************// Droping a Column in a Table

ALTER TABLE sen_emp DROP COLUMN empno;

***********************************************************************************************// Create a Table with default value

CREATE TABLE _TEMP ( empno int,

Page 106: Query

106

Query - Page #2

ename varchar(20), city varchar(20) default ’cbe’);

// Add a Default value to a column

ALTER TABLE _TEMP ADD default ’sen’ for ename;

//Drop the Default constraint from a column

ALTER TABLE _TEMP DROP CONSTRAINT DF___TEMP__CITY__6C6E1476 ***********************************************************************************************// Creating Check Constraint for a column

ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );

*****************************************************************************************// Disabling Check constraint

ALTER TABLE _temp NOCHECK CONSTRAINT CKEMPNO;

// RE-Enabling Check constraint

ALTER TABLE _temp CHECK CONSTRAINT CKEMPNO;

******************************************************************************************// Create a new table and copy only some particular fields of another Table

select empno,second_name,salary into temp_sen_emp from sen_emp;

******************************************************************************************//Create A Table and copy the data from another Table

Create Table vinod ( name varchar(20) );

insert into vinod select second_name from sen_emp;

******************************************************************************************

select * from authors;

select * from authors where au_lname like ’[^a-r]%’;select * from authors where au_lname like ’[a-r]%’;select * from authors where au_lname like ’_[a-r]%’;

select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’

select * from sen_emp;

insert into sen_emp (empno,second_name) values (1500,’gallifer’);

*********************************************************************************************Grouping:

select sum(salary) from sen_emp;

select * from sen_emp;

select sum(salary) from sen_emp group by dept_no;

select sum(price) from titles group by type;

select sum(price) from titles;

select * from titles order by type;

select * from titles;

select sum(price) from titles group by type;

Page 107: Query

107

Query - Page #3

select sum(price) from titles;

select sum(price) as total_salary from titles;

select sum(price) "Total_salary" from titles;

select * from sen_emp;

select dept_no,sum(salary)’Total Salary’ from sen_emp group by dept_no order by dept_no;

select type, sum(type) from titles;

select sum(salary) from sen_emp order by dept_no group by dept_no; // Error

______________________________________________________________________________________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) from titles group by type,pub_id;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id order by type;

select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id desc;

sp_help titles

select type,sum(price) from titles group by type;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id

******************************************************************************************// Select keywords SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]******************************************************************************************

SELECT TYPE,PUB_ID,SUM(PRICE) "TOTAL PRICE"FROM TITLESGROUP BY TYPE,PUB_ID;

SELECT *FROM TITLESORDER BY TYPE DESC;

//////////////////////////////////////////////////////////////////////////////////////////select type,sum(price)from titlesgroup by typeorder 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 titlesgroup by typeorder by title_id; // Error

select type,title_id,sum(price)from titlesgroup by type,title_idorder by title_id;

select * from titles;

Page 108: Query

108

Query - Page #4

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:-----------------

select type,sum(price) from titles group by type; Result set Business 1100 Computer 700 Novel 800

Compute By class:

select type,sum(price) from titles compute by type; // error

select type,price from titlesorder by type compute sum(price) by type; Rule: 1.Whenever we use compute By class, it must to use order by class. 2.The field which appear in compute by class is must appear in order by class 3.Whatever field in the aggregate funtion, which is also in the select list.

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 itselfable to generate Work Table...So the Compute by class relay order by class...

select type,pricefrom titlesorder by pub_idcompute 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 ofprice by Type...’

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type;

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by pub_id; // Error

Reason: Work Table

Type pub_id Price--------------------------Business p1 200Business p1 200Business p2 300Computer p2 400

Page 109: Query

109

Query - Page #5

Computer p2 200Novel p1 200Novel p1 240Novel p2 450

In above work table, The pub_id is clubed according to the Typenot clubed alone...That is why it will flash error...

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type,pub_id;

select type,pub_id,title_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id,title_id;

select type,pub_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id;****************************************************

Afternoon:21-dec-2001

select type,pub_id from titles;

1...select distinct type,pub_id from titles;

2...select type,pub_id from titles group by type,pub_id;

Query 1 and 2 give the same result

select type,pub_id from titlesgroup by type,pub_id;

select distinct type,pub_id from titles;

// In the above query.. The Distinct applies both type and pub_id columns..We can not make to applyfor a particular column. It will apply all the columns in the select list

For Ex

Business p1 200Business p1 400Business p1 300Computer p2 500Computer p2 700

The Result is

Business p1 200Computer p2 500

/////////////////////////////////////////////////select type,sum(price),avg(price)from titlesgroup by price; // Error

Reason: The field name in group by clause which is not used in aggregate function in select list

Page 110: Query

110

Query - Page #6

//////////////////////////////////////////////////////////

Having: Having clause should have group by class...but when using group by class it is optionalto use Having clause.

It affects the result of the Group By Class......

Work Table -----> Internal Result Set -----> Output

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...

Both 1 and 2 are gives same result......

Query 2 Work Table:

Olny Business Records are present

But Query 1 Work Table: All types of Records like Business,Computer and Novel and then take Business Records are Filtered

///////////////////////////////////////////////////////////////////////////////

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

// It would not work Reasons: 1. The left hand side of the where class shoul be column name... 2. Here The Group by class run after the where class...but where class we used aggregate functions...This aggregate function will not use group by class..

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select type,sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

/////////////////////////////////////////////////////////////////////////////////////////////////

December-26-2001

Joins:

select * from authors,publishers; // It does the cartisean product of two tables....

Page 111: Query

111

Query - Page #7

if the select statement contains more table in from clause without where clause, it is calledcross joining which is never used...

select * from authors,publisherswhere authors.city = publishers.city;

Joins are evaluated just like Nested Loops....

for(i=0;i<=10;i++) One Table for(j=0;j<=5;j++) Another Table if(i==j) Where clause condition { }

select authors.au_id,authors.au_lname,authors.phone,publishers.pub_id,publishers.pub_name,publishers.cityfrom authors,publishers where authors.city = publishers.city;

select authors.*,pub_id,pub_name from authors,publisherswhere 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, publishers p where authors.city=p.city;

select p.*,au_id,au_lnamefrom authors a, publishers pwhere a.city = p.city and a.au_lname like ’c%’

select p.*,au_id,au_lnamefrom authors a, publishers pwhere au_lname like ’c%’ and a.city = p.city

Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select * from authors; select * from publishers; select * from titles; select * from titleauthor;

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:.................

Page 112: Query

112

Query - Page #8

Explanation:

Title: Authors

au_id au_lname ----------- ----------------------------a1 lockleya2 peter

Table: Publisher

pub_id pub_name ------ -----------p1 samyp2 golgotiap3 samba

Table: Titles

title_id pub_id -------- --------t1 p1t2 p2t3 p3

Table: TitleAuthor

au_id title_id ----------- -------- a1 t1a1 t2a2 t1a2 t3

Virtual Tables:

[Authors] [TitleAuthor]aid aname au_id title_ida1 lockey a1 t1a1 lockey a1 t2

[authors] [titleAuthor] [titles]aid aname aid title_id title_id pub_ida1 lockey a1 t1 t1 p1a1 lockey a1 t2 t2 p2

[authors] [titleAuthor] [ titles ] [ publisher]aid aname aid title_id title_id pub_id pub_id pub_name a1 lockey a1 t1 t1 p1 p1 sams a1 lockey a1 t2 t2 p2 p2 golgotia

FAQ:

1. How the joins are works???

Ans: It works as Nested Loops

2.What is the Query Optimizer? Ans: The Query optimizer find out which join will be evaluated first and run the query in the optimized way....

3. How many Virtual Table created for N conditions??

Page 113: Query

113

Query - Page #9

Ans: (N-1) Virtual Tables are created for N tables

Cross Checking:

select * from authors where au_lname like ’Loc%’;select * from titleauthor where au_id = ’486-29-1786’; select * from titles where title_id=’PC9999’ or title_id=’PS7777’; select * from publishers where pub_id =’1389’ or pub_id=’0736’;

////////////////////////////////////////////////////////////////////////////////////////////////

Renaming the Tables

sp_rename <OldTable> <NewTable>

////////////////////////////////////////////////////////////////////////////////////////////////

Taking a Copy of the Table:

Create Table vinod_temp( eno int identity(1,1), ename varchar(20), dept_id int);

insert into vinod_temp(ename,dept_id) select ename,dept_id from sen_temp;////////////////////////////////////////////////////////////////////////////////////////////////

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

Result set would be A1A6A2A3

select a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays duplicate Records

Page 114: Query

114

Query - Page #10

select state,count(*) from authorsgroup by statehaving count(*)>1 // We should not use group by function in the self joining situations

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays distinct records but it dispalys one author lives in the city

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered...

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id order by a.city; // It displays the perfect result Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Create Table patdat( patno varchar(20) not null, name varchar(20) not null, address varchar(20));

Create Table patadm( patno varchar(20) not null, admno varchar(20) not null, addate datetime, constraint sen_pk2 primary key(patno,admno), constraint fk foreign key(patno) references patdat1(patno));

Create Table operdat( patno varchar(20), admno varchar(20), opno int, opdate datetime, type varchar(20)

constraint sen_pk2 primary key(patno,admno,opno), constraint sen_fk foreign key(patno) references patdat(patno), constraint fk1 foreign key(admno) references patadm1(admno) );

Note: constaint fk1 could not be created.... ’We can not refer the part of the primary key(composite key) in another Table’

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Question: Find the author id who has written more than one book??? select distinct ta1.au_id from titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id;

Question: Find the title_id which has been written by more than one author?

select distinct ta1.title_id from titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id;

Question: Find the author Names who has written more than one book???

Page 115: Query

115

Query - Page #11

select distinct a.au_lname,a.au_fname from authors a,titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id and ta1.au_id = a.au_id;

Question: Find the titles which has been written by more than one author? select distinct t.title from titles t,titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id and ta1.title_id = t.title_id;

/////////////////////////////////////////////////////////////////////////////////////////////////Jan 02 2002:

Outer join: emp e1 boris HRDe2 becker HRDe3 peter SYSe4 Anderw SYSe5 Lafer null

dep

HRD Human ResSYS SystemsPER personalNET network

emp

enoenamed_id

dept

ddiddname

Display the emp details along with dept id??

select emp.* d.did from emp e,dept dwhere e.did=d.did

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYS

select emp.*,d.did from e,dept dwhere e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax)

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYSe5 lafer

select emp.*,d.did from e,dept dwhere e.did =* d.did; // Display the matching records and addition to all

Page 116: Query

116

Query - Page #12

unmatching records form dept (SQL Server Syntax)

select * from employee inner join dept on e.deptid=d.detptid (ANSI Syntax)

The above two query gives the same result..

////////////////////////////////////////////////////////////////////////////////////////////

Full outer join: select employee.eno,employee.name,d.did from employee full outer join dept on employee.did=dept.did (ANSI Syntax) [ Where <filter condition> ]

///////////////////////////////////////////////////////////////////////////////////////////////

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;

select * from titles where price = (select max(price) from titles);**************************************************************************************************

Jan-04-2002:

Exists: select cname from customers where exists ( select cid from orders where customers.id=orders.id);

Exists has equal meaning of =Any

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 becausethe join inside the subquery it does not make correlated subquery.]

2.The field in the join is from the outer query table... [Either the right or left side of the join should include the field in the outer query]

The execution of the correlated sub query is like join...

Example: select cname from customers where exists ( select cid from orders where customers.id=orders.id); 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...

It(Exist) is Intersection of the values in the different table..

But simple query Not Exist is equal to Difference

select cname from customers where cid in ( select * from orders ); // Error . We can not compare one field with many fields.

Page 117: Query

117

Query - Page #13

select cname from customers where exists ( select * from orders where customers.id=orders.id); // It would not give any error because the inner query will give only boolean values.... --------------------------------------------------------------------------------------------------------

7-01-2002:

select distinct a.au_fname from authors a, authors bwhere a.state = b.state and a.au_id <> b.au_id;

Any self join can be carried out through correlated sub query.

select a.au_fnamefrom authors awhere 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 outer table.

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 executed...If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct clause in the correlated sub query.

What is difference between self join and correlated sub query??Ans: The self join continues until all the records matched but the correlated sub query becomes true, it would not go further.

------------------------------------------------------------------------------------------------------------------Union:

It gives common and uncommon things in the two query....

select * into sen_temp_table from authors where state = ’LA’; select * from authors union select * from sen_temp_table; // It will not give the duplicates of the records 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 type needed select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mismatach,If the implicit conversion possible it will work

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 order by au_id; // Allowed 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:

Find total purchase for each customer??????????

Ans:drop vicreate view v_sample asselect 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

select max(tprice) from v_sample

Page 118: Query

118

Query - Page #14

Find which customer purchased more????

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 UserGrant All Table_name to UserRevoke select|update|insert|delete on Table_name from UserRevoke All Table_name from User

select * from syspermissions;sp_pkeys sen_traveller; View: The View is the Projection of the base tables...

Syntax: Create View view_name as select statement

Create view sen_view_empdatasselect eid,ename,did,dname from emp,deptwhere emp.did = dept.did;

Grant select on v_empdat to sa

Step 1:create view sen_view_v1 asselect * 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;

select * from authors;

select * from titles;

*************************************************************************************************

16-January-2002:

The View can include on only "select" statement.

Ex:

create view v1 as select.....

We can use delete,insert,update and select on views. Create view v2 asselect 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

To make work the above statement....

create view v2 asselect pub_id,sum(price) as "Total" from titles group by pub_id (or)create view v2(publishers_id,price) asselect pub_id,sum(price) as "Total" from titles group by pub_id

Page 119: Query

119

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 table emp( empno varchar(20) not null, emp_name varchar(20) not null, salary float not null, dept_id varchar(20) not null, phone varchar(20) not null);

create view v1 as select emp_no,emp_name,dept_id,phone from emp; // It would not work...

create view v1 asselect * form emp; // It will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olnyit 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...

Views using joins: 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...

////////////////////////////////////////////////////////////////////////////////////////////////

create view v_emp asselect * from emp where dept_id = ’HRD’;

select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS table and 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....

select * from emp where sal>2500 and dept_id=’HRD’;

Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpretedas below....

Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....

With Check option: create view v_emp as select * from emp where dept_id=’HRD’ with check option

insert v_emp values(’e1001’,’boris’,’HRD’,2000); // It works fine

insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view hasbeen created by with check option condition. It allow only the where clause condition is match, itmeans that we can insert only ’HRD’ type......

/////////////////////////////////////////////////////////////////////////////////////////////////

Question: Find which type sales is greater???

We can not write in single select statement....

create view sen_v1 as

Page 120: Query

120

Query - Page #16

select type,sum(price)as "Total_sales" from titles group by type

select type,max(Total_sales) from sen_v1 group by type,Total_sales having Total_sales= (select max(Total_sales) from sen_v1)

select type from sen_vl where Total_sales =(select max(Total_sales) from sen_v1)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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. One procedure can have 1024 parameters.

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...

create procedure procedure_name[(parameters)] [ ]--->optional as sql statements;

create procedure pro as select * from authors,publishers where authors.city = publishers.city;

create procedure pro as select * from emp; // In this statement,While creating procedure, it checks only the syntax errors it will not check the existence of the objets. In other words the object need not be existence while creating procedures but view the objects has to exist.

create procedure pro as select sal from emp; // In this statement, it checks the existence of the object,if it is, itchecks the existence of the column, if it is, the procudure will be created...if the column doesnot exist,it will give error....If there is non existence of the object,it will not check the existence of the column,the procedure will be created....

Either existence of object or non-existence of the object,the procedure will be created....

The created procedure have an entry in sysobjects table.....The statements are used in procedure will be stored in syscomments table. To execute the procedure...

Exec pro // while creating procudure, it checks only the syntax, while executing, the compilationprocess is done..

select object_id (’demo’); // we can get the table id what the sql server maintains...

create procedure pro(parameters) with recompileas sql statements; // It will be recompiled for every execution of this procedure.....

//////////////////////////////////////////////////////////////////////////////////////////////what is Query plan????

The query plan is nothing but the path of the execution in the sql statements...

Exec pro;

step 1: the procedure is compiled step 2: creates query plan,this query plan is stord in procedure cache it is like obj file step 3: it executes the obj file and gives the output....

The step 1 and step 2 will be executed at the first execution of the procedure..if u executethe procedure another time, it will no go for compilation process,it just checks the procedure

Page 121: Query

121

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:

Create procedure sen_sample_procedure(@param varchar(20)) as -- sen_sample_procedure(@param varchar(20) = ’psychology’)// default parameter -- sen_sample_procedure(@param varchar(20) = ’psychology’,@price=20.0) // Overridding default parameters declare @price float

select @price = sum(price) from titles group by type having type = @param;

if(@price <=100) return 1; if(@price>100 and @price<=200) return 2; if(@price >200) return 3;

-------------------------------------

declare @ret int

exec @ret=sen_sample_procedure ’psychology’ --exec @ret=sen_sample_procedure default,50 // Overridding default parameters --exec @ret=sen_sample_procedure @price=50,@param=’business’ // Explicit passing values if @ret = 1 begin select "Return 1"; end if @ret = 2 begin select "Return 2"; end

if @ret = 3 begin select "Return 3"; end

Note: The TSQL does not contain for loop,arrays..... goto,else,break are there

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

declare @value int,@expr int select @value = case @ex when 1 then only one value when 2 then only one value when 3 then only one value

Note: To assign to value to variable select @ret = 1; (or) set @ret = 1;

Example:

SELECT ’Price Category’ = CASE WHEN price IS NULL THEN ’Not yet priced’ WHEN price < 10 THEN ’Very Reasonable Title’ WHEN price >= 10 and price < 20 THEN ’Coffee Table Title’ ELSE ’Expensive book!’

END,title AS ’Shortened Title’ FROM titles

Example

Page 122: Query

122

Query - Page #18

declare @ret int set @ret = 1 select @ret =

case(@ret) when 1 then 10 when 2 then 20 when 3 then 30

end select @ret /////////////////////////////////////////////////////////////////////////////////////////////////

19-01-2002:

Output Parameters:

Question: Write the procedure to find the city and state of the given publishers????

create procedure sen_pro(@pub_name varchar(20), @city varchar(20) output, @state varchar(20) output) as select @state=state,@city=city from publishers where pub_name like @pub_name;

create procedure sen_callpro(@param varchar(20)) as declare @rstate varchar(20); declare @rcity varchar(20); exec sen_pro @param,@city=@rcity output,@state=@rstate output; select "pub state " + @rstate; select "pub city " + @rcity;

exec sen_callpro "New Moon Books";------------------------------------------------------------------------------------------------

Question: Write a procedure to check the given title_id has been written 2 authors, if so print the 2 author names

Create procedure sen_proce(@t_id varchar(20)) as declare @a varchar(20) if exists(select ta.title_id from titleauthor ta,titles t where ta.title_id=t.title_id and t.title_id = @t_id group by ta.title_id having count(*) = 2) begin select ta.au_id into #temp from titleauthor ta,titles t where ta.title_id = t.title_id and t.title_id = @t_id; select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a delete from #temp where au_id = @a select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a end else print "the book does not have exactly 2 authors" exec sen_proce ’PS2091’

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:

create proc pro asgoto aa:print "dgs"-------------------------------------------------------------------------------------------------

21-January-2002:

E-R Diagram: Entity: The entity is an object about information can be recorded..

Page 123: Query

123

Query - Page #19

For example, the employee and dept entity has some relationship between them...

The are 3 different types of relationship....

1. One to One2. One to Many3. Many to Many

{Chen notation}

[Entity] [Relation] [Entity]Employee---------- Works In ----------------Dept|[Rect] [Diamond] [Rect]||-------has --------Address [Diamond] [Rect]

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] andone to many[right to left] realationship comes either side,Take a one to many relationship...)

Employee(Optional-entity) Dept ( Optional-entity)eid did did dname(Attributes) (Attributes)e1 d1 d1e2 d1 d2e3 d2 d3e4 d2 (one dept can have zero or many employees)e5 null (employee has not been assigned to zero or one dept)

Cardinality: no of occurences of field value in dependant entity...

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...)

2.emp(1,M) one employee has one or many address.. address(1,1) one address has only one employee.. emp has existence dependent with address (address can not be created before emp so we change to Address has existence dependent with 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..)

Example:(one to many relationship) ( contains two Tables) [Rect] [Diamond] [Rect] Professor -------------- Advises -----------Student [Entity](0,N) [Entity](1,1)

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]

Example:(one to one relationship) ( contains only one table)

[Rect] [Diamond] [Rect] Professor -------------- is allotted -----------Room [Entity](0,1) [Entity](0,1)

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 ]

Example:(Many to Many relationship) ( contains 3 tables)

[Rect] [Diamond rounded square] [Rect] Theater -------------- is shown ---------------- Films [Composite Entity](1,N) [Composite Entity](1,N)

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 ]

Page 124: Query

124

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...

Theatre (entity) Films (entity) TheatreFilm (Associative Entity) or Junction Table ------------------------------------------------------------------------------------------ tid (pk) fid (pk) tid tname fname fid no_seats hero composite primary key(tid,fid) location heroine

Example:(Many to Many relationship) ( contains three tables)

[Rect] [Diamond rounded square] [Rect] Authors -------------- Writes ------------------ titles [Composite Entity](1,N) [Composite Entity](1,N)

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 qurey...

Any database desin normally will not go beyond the third normal form....

First Normal from: Drive the table using E-R Diagrams... (*) Any table should have atomic values(Every field should record atomic information)

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 record...and take to consideration the table should not have more null value fields.

Example:

eid pid did nohrs dhead-------------------------- e1 p1 is 20 boris e2 p1 is 20 boris e3 p2 net 30 peter e4 p2 net 30 sampry e1 p2 is 30 Andrew

* Primary key should be identified [ composite primary key(eid,pid) ] ---------------------------------------------------------------------------------------------------------

Second Normal Form:

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 id 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 entrily on the primary key and put it separate table along with the field on which the non key attribute is dependent on...

so we take off did from the above table

eid did ---------

Page 125: Query

125

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 eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

---------------------------------------------------------------------------------------------------------Third Normal Form: All the non key attributes should be dependent only on the primary key

eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only thedid which is not a primary key of the table....

Take the dhead along with it is dependent....

did dhead-------------- IS boris NET peter

----------------------------------------------------------------------------------------------------------

Database is a collection of data with controlled redundancy.....

*************************************************************************************************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 deleteany enty in the master table,which is refered by in the child table...The SQL server maintainsrestrictions automatically...The cascade deletions is opposite of these restrictions....

Syntax:

Create trigger trigger_name on table for operation as SQL Statements....

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 aftertrigger,The SQL could not support Before Triggers.....

Trigger can not accept parameters.....

Page 126: Query

126

Query - Page #22

Book Magazine----------------------------Bid MagidBname MnameAuthor price

Transaction--------------TidCard_idbook_idissue_datereturn_date--------------------------------------------------------------------------------------------------Implementing primary key constraint:-

Create trigger tri on tempfor insert asdeclare @icount intselect @icount=count(*) from temp,insertedwhere temp pk = insert pkif @icount >1begin print ’Duplicate Record’ rollbackendelse print ’Successfully on inserting the record’

inserted--->trigger test table (or) magic table-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on empfor insert asif not exists(select * from dept,inserted wheredept.did=inserted.did)begin print "Integrity violation" rollback;endelse print "successfull insertion into the table"

emp inserted----------------------------------------------------e1 boris d1 d1 HRDe2 becker d2 d2 SYSe3 sapeg d3

-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on trans_member for insert asif not exists (select * from books,inserted where book.book_id =inserted.book_id)begin if not exists (select * from magazines inserted where magizines.mag_id = inserted.book_id) begin print ’Ref integrity violation’ rollback end else print ’Successfully inserted into the table’endelse print ’Successfully inserted into the table’

Page 127: Query

127

Query - Page #23

-------------------------------------------------------------------------------------------------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:-

Create trigger dtrion publishersfor deleteasdelete from titles where titles.pub_id = deleted.pub_id

publisher table-->Trigger Table

The value from Trigger table is moved into Trigger Test Table (Deleted Table) -------------------------------------------------------------------------------------------------Implementing Restriction on deletion:-

Create trigger dtrion publishersfor deleteasif exists( select * from titles,deleted where titles.pub_id=deleted.pub_id)begin print ’Attempt to create orphan Records’ rollbackend

------------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables?????

Hits provided:declare @i intselect @i=Object_id(’publishers’)

if exists(select * from sysobjects where id=@i) insert back_up select * from deleted

------------------------------------------------------------------------------------------------

31-JAN-2002:

customers invoice products----------------------------------------------cid oid pidcname cid pname pid qoh (quantity in hand) qty price

create trigger trion invoicefor insertasupdate products set qoh=qoh-inserted.qty from products,insertedwhere products.pid=inserted.pid

checking the availability of products:---------------------------------------

select @iqty = inserted.qty from insertedselect @qty = products.qty from inserted,productswhere inserted.pid=products.pidif(@qty<@iqty)begin print "invalid transaction" rollback returnend

Page 128: Query

128

Query - Page #24

-------------------------------------------------------------------------------------------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 invoicefor updateif update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback returnendif not exists (select * from products,insertedwhere inserted.productid=products.proudctidbegin print ’Fk violation on products’ rollback returnend--------------------------------------------------------------------------------------------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..........

The cursor contains following five ’jargons’

1....Declare2....Open3....Fetch4....Close5....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

// The scroll keyword is used to move the cursor up and down...declare cur cursor scroll for select c_id,title,author,publisher from sen_catlog

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;

Note: When closing the cursor, it destroies the result set.....-------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Page 129: Query

129

Query - Page #25

Note: It destroies the cursor [ like dropping tables ] -------------------------------------------------------------------------------------------------

Example with procedure:-

create procedure sen_cur_pro asdeclare cur cursor scrollforselect * from sen_catlogopen curfetch next from curwhile(@@fetch_status=0)begin fetch next from curendclose curdeallocate cur

exec sen_cur_pro;

Note: @@fetch_status is system defined global variable which is automatically set to 0 whichindicates for successful fetch...------------------------------------------------------------------------------------------------1-02-2002:

Application of Cursors:

Create procedure sen_cpro asdeclare @tid varchar(20),@title varchar(20),@price floatdeclare cur cursor scrollforselect title_id,title,price from titlesopen curfetch next from cur into @tid,@title,@pricewhile(@@fetch_status=0)begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@priceendclose curdeallocate cur

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??????

create procedure sen_publisher_books asset nocount ondeclare @pid varchar(20),@pname varchar(20)declare @tid varchar(20),@title varchar(20),@price floatdeclare @n intdeclare cur cursor scrollforselect pub_id,pub_name from publishersopen curfetch next from cur into @pid,@pnamewhile(@@fetch_status=0)begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid

Page 130: Query

130

Query - Page #26

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,@pnameendclose curdeallocate cur exec sen_publisher_books --------------------------------------------------------------------------------------------------------------2-Feb-2002:

Indexing: It is a sorting process to reduce the searching process time....

Syntax:

Create { nonClustered } index index_nameon table_name(field_name)

Default is Clustered indexing................-------------------------------------------------------------------------------------------------NonClustered:

create nonclustered index emp_enoon emp(eno)

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 orit 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:

create clustered index emp_enoon emp(eno)

The table itself will be sorted on a field name

-----------------------------------------------------------------------------------------------Note: The clustered index points the page...but the nonclustered index points the exact match ofrecord...

1...The Clusterd index is efficiant for duplicte records ( Foreign key)2...The nonClustered index is efficient for unique records (primary key), for the primary key creation the SQL server creates Clusterd index, it is our responsiblity to give nonClusterd index when creating the primary key......------------------------------------------------------------------------------------------------Note: One Clustered index is allowed for a table, but as many nonClustered index is allowed for a table------------------------------------------------------------------------------------------------

Page 131: Query

131

Query - Page #1

------------------SQL NOTE -------------------------------------------------------------- Author : E Senthil -----------------------------------------------------------------------------------------

// Create A Table with out primary key

CREATE TABLE sen_emp ( empno int, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int );

************************************************************************************************// Set Primary key with ALTER TABLE COMMAND

ALTER TABLE sen_emp ALTER COLUMN empno int not null; ALTER TABLE sen_emp ADD CONSTRAINT __PK PRIMARY KEY (empno);

// Before Adding PRIMARY KEY CONSTRAINT TO A COLUMN, // make sure it should not accept null values **********************************************************************************************// Create A Table with a Primary key

create table sen_dept ( dept_no int constraint _pk primary key, dname char(20), location char(20) );

********************************************************************************************* // Set Referencial Integrity [ Joining two tables ]

Alter table sen_emp Add constraint _fk foreign key(dept_no)references sen_dept(dept_no);

*********************************************************************************************// Create a table with primary key and foreign key

CREATE TABLE sen_emp ( empno int CONSTRAINT PK PRIMARY KEY, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int CONSTRAINT FK FOREIGN KEY REFERENCES sen_dept(dept_no) );

***********************************************************************************************// Droping a Constraint

ALTER TABLE sen_emp DROP CONSTRAINT __PK;

*************************************************************************************************// Droping a Column in a Table

ALTER TABLE sen_emp DROP COLUMN empno;

***********************************************************************************************// Create a Table with default value

CREATE TABLE _TEMP ( empno int,

Page 132: Query

132

Query - Page #2

ename varchar(20), city varchar(20) default ’cbe’);

// Add a Default value to a column

ALTER TABLE _TEMP ADD default ’sen’ for ename;

//Drop the Default constraint from a column

ALTER TABLE _TEMP DROP CONSTRAINT DF___TEMP__CITY__6C6E1476 ***********************************************************************************************// Creating Check Constraint for a column

ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );

*****************************************************************************************// Disabling Check constraint

ALTER TABLE _temp NOCHECK CONSTRAINT CKEMPNO;

// RE-Enabling Check constraint

ALTER TABLE _temp CHECK CONSTRAINT CKEMPNO;

******************************************************************************************// Create a new table and copy only some particular fields of another Table

select empno,second_name,salary into temp_sen_emp from sen_emp;

******************************************************************************************//Create A Table and copy the data from another Table

Create Table vinod ( name varchar(20) );

insert into vinod select second_name from sen_emp;

******************************************************************************************

select * from authors;

select * from authors where au_lname like ’[^a-r]%’;select * from authors where au_lname like ’[a-r]%’;select * from authors where au_lname like ’_[a-r]%’;

select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’

select * from sen_emp;

insert into sen_emp (empno,second_name) values (1500,’gallifer’);

*********************************************************************************************Grouping:

select sum(salary) from sen_emp;

select * from sen_emp;

select sum(salary) from sen_emp group by dept_no;

select sum(price) from titles group by type;

select sum(price) from titles;

select * from titles order by type;

select * from titles;

select sum(price) from titles group by type;

Page 133: Query

133

Query - Page #3

select sum(price) from titles;

select sum(price) as total_salary from titles;

select sum(price) "Total_salary" from titles;

select * from sen_emp;

select dept_no,sum(salary)’Total Salary’ from sen_emp group by dept_no order by dept_no;

select type, sum(type) from titles;

select sum(salary) from sen_emp order by dept_no group by dept_no; // Error

______________________________________________________________________________________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) from titles group by type,pub_id;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id order by type;

select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id desc;

sp_help titles

select type,sum(price) from titles group by type;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id

******************************************************************************************// Select keywords SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]******************************************************************************************

SELECT TYPE,PUB_ID,SUM(PRICE) "TOTAL PRICE"FROM TITLESGROUP BY TYPE,PUB_ID;

SELECT *FROM TITLESORDER BY TYPE DESC;

//////////////////////////////////////////////////////////////////////////////////////////select type,sum(price)from titlesgroup by typeorder 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 titlesgroup by typeorder by title_id; // Error

select type,title_id,sum(price)from titlesgroup by type,title_idorder by title_id;

select * from titles;

Page 134: Query

134

Query - Page #4

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:-----------------

select type,sum(price) from titles group by type; Result set Business 1100 Computer 700 Novel 800

Compute By class:

select type,sum(price) from titles compute by type; // error

select type,price from titlesorder by type compute sum(price) by type; Rule: 1.Whenever we use compute By class, it must to use order by class. 2.The field which appear in compute by class is must appear in order by class 3.Whatever field in the aggregate funtion, which is also in the select list.

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 itselfable to generate Work Table...So the Compute by class relay order by class...

select type,pricefrom titlesorder by pub_idcompute 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 ofprice by Type...’

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type;

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by pub_id; // Error

Reason: Work Table

Type pub_id Price--------------------------Business p1 200Business p1 200Business p2 300Computer p2 400

Page 135: Query

135

Query - Page #5

Computer p2 200Novel p1 200Novel p1 240Novel p2 450

In above work table, The pub_id is clubed according to the Typenot clubed alone...That is why it will flash error...

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type,pub_id;

select type,pub_id,title_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id,title_id;

select type,pub_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id;****************************************************

Afternoon:21-dec-2001

select type,pub_id from titles;

1...select distinct type,pub_id from titles;

2...select type,pub_id from titles group by type,pub_id;

Query 1 and 2 give the same result

select type,pub_id from titlesgroup by type,pub_id;

select distinct type,pub_id from titles;

// In the above query.. The Distinct applies both type and pub_id columns..We can not make to applyfor a particular column. It will apply all the columns in the select list

For Ex

Business p1 200Business p1 400Business p1 300Computer p2 500Computer p2 700

The Result is

Business p1 200Computer p2 500

/////////////////////////////////////////////////select type,sum(price),avg(price)from titlesgroup by price; // Error

Reason: The field name in group by clause which is not used in aggregate function in select list

Page 136: Query

136

Query - Page #6

//////////////////////////////////////////////////////////

Having: Having clause should have group by class...but when using group by class it is optionalto use Having clause.

It affects the result of the Group By Class......

Work Table -----> Internal Result Set -----> Output

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...

Both 1 and 2 are gives same result......

Query 2 Work Table:

Olny Business Records are present

But Query 1 Work Table: All types of Records like Business,Computer and Novel and then take Business Records are Filtered

///////////////////////////////////////////////////////////////////////////////

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

// It would not work Reasons: 1. The left hand side of the where class shoul be column name... 2. Here The Group by class run after the where class...but where class we used aggregate functions...This aggregate function will not use group by class..

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select type,sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

/////////////////////////////////////////////////////////////////////////////////////////////////

December-26-2001

Joins:

select * from authors,publishers; // It does the cartisean product of two tables....

Page 137: Query

137

Query - Page #7

if the select statement contains more table in from clause without where clause, it is calledcross joining which is never used...

select * from authors,publisherswhere authors.city = publishers.city;

Joins are evaluated just like Nested Loops....

for(i=0;i<=10;i++) One Table for(j=0;j<=5;j++) Another Table if(i==j) Where clause condition { }

select authors.au_id,authors.au_lname,authors.phone,publishers.pub_id,publishers.pub_name,publishers.cityfrom authors,publishers where authors.city = publishers.city;

select authors.*,pub_id,pub_name from authors,publisherswhere 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, publishers p where authors.city=p.city;

select p.*,au_id,au_lnamefrom authors a, publishers pwhere a.city = p.city and a.au_lname like ’c%’

select p.*,au_id,au_lnamefrom authors a, publishers pwhere au_lname like ’c%’ and a.city = p.city

Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select * from authors; select * from publishers; select * from titles; select * from titleauthor;

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:.................

Page 138: Query

138

Query - Page #8

Explanation:

Title: Authors

au_id au_lname ----------- ----------------------------a1 lockleya2 peter

Table: Publisher

pub_id pub_name ------ -----------p1 samyp2 golgotiap3 samba

Table: Titles

title_id pub_id -------- --------t1 p1t2 p2t3 p3

Table: TitleAuthor

au_id title_id ----------- -------- a1 t1a1 t2a2 t1a2 t3

Virtual Tables:

[Authors] [TitleAuthor]aid aname au_id title_ida1 lockey a1 t1a1 lockey a1 t2

[authors] [titleAuthor] [titles]aid aname aid title_id title_id pub_ida1 lockey a1 t1 t1 p1a1 lockey a1 t2 t2 p2

[authors] [titleAuthor] [ titles ] [ publisher]aid aname aid title_id title_id pub_id pub_id pub_name a1 lockey a1 t1 t1 p1 p1 sams a1 lockey a1 t2 t2 p2 p2 golgotia

FAQ:

1. How the joins are works???

Ans: It works as Nested Loops

2.What is the Query Optimizer? Ans: The Query optimizer find out which join will be evaluated first and run the query in the optimized way....

3. How many Virtual Table created for N conditions??

Page 139: Query

139

Query - Page #9

Ans: (N-1) Virtual Tables are created for N tables

Cross Checking:

select * from authors where au_lname like ’Loc%’;select * from titleauthor where au_id = ’486-29-1786’; select * from titles where title_id=’PC9999’ or title_id=’PS7777’; select * from publishers where pub_id =’1389’ or pub_id=’0736’;

////////////////////////////////////////////////////////////////////////////////////////////////

Renaming the Tables

sp_rename <OldTable> <NewTable>

////////////////////////////////////////////////////////////////////////////////////////////////

Taking a Copy of the Table:

Create Table vinod_temp( eno int identity(1,1), ename varchar(20), dept_id int);

insert into vinod_temp(ename,dept_id) select ename,dept_id from sen_temp;////////////////////////////////////////////////////////////////////////////////////////////////

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

Result set would be A1A6A2A3

select a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays duplicate Records

Page 140: Query

140

Query - Page #10

select state,count(*) from authorsgroup by statehaving count(*)>1 // We should not use group by function in the self joining situations

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays distinct records but it dispalys one author lives in the city

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered...

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id order by a.city; // It displays the perfect result Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Create Table patdat( patno varchar(20) not null, name varchar(20) not null, address varchar(20));

Create Table patadm( patno varchar(20) not null, admno varchar(20) not null, addate datetime, constraint sen_pk2 primary key(patno,admno), constraint fk foreign key(patno) references patdat1(patno));

Create Table operdat( patno varchar(20), admno varchar(20), opno int, opdate datetime, type varchar(20)

constraint sen_pk2 primary key(patno,admno,opno), constraint sen_fk foreign key(patno) references patdat(patno), constraint fk1 foreign key(admno) references patadm1(admno) );

Note: constaint fk1 could not be created.... ’We can not refer the part of the primary key(composite key) in another Table’

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Question: Find the author id who has written more than one book??? select distinct ta1.au_id from titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id;

Question: Find the title_id which has been written by more than one author?

select distinct ta1.title_id from titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id;

Question: Find the author Names who has written more than one book???

Page 141: Query

141

Query - Page #11

select distinct a.au_lname,a.au_fname from authors a,titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id and ta1.au_id = a.au_id;

Question: Find the titles which has been written by more than one author? select distinct t.title from titles t,titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id and ta1.title_id = t.title_id;

/////////////////////////////////////////////////////////////////////////////////////////////////Jan 02 2002:

Outer join: emp e1 boris HRDe2 becker HRDe3 peter SYSe4 Anderw SYSe5 Lafer null

dep

HRD Human ResSYS SystemsPER personalNET network

emp

enoenamed_id

dept

ddiddname

Display the emp details along with dept id??

select emp.* d.did from emp e,dept dwhere e.did=d.did

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYS

select emp.*,d.did from e,dept dwhere e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax)

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYSe5 lafer

select emp.*,d.did from e,dept dwhere e.did =* d.did; // Display the matching records and addition to all

Page 142: Query

142

Query - Page #12

unmatching records form dept (SQL Server Syntax)

select * from employee inner join dept on e.deptid=d.detptid (ANSI Syntax)

The above two query gives the same result..

////////////////////////////////////////////////////////////////////////////////////////////

Full outer join: select employee.eno,employee.name,d.did from employee full outer join dept on employee.did=dept.did (ANSI Syntax) [ Where <filter condition> ]

///////////////////////////////////////////////////////////////////////////////////////////////

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;

select * from titles where price = (select max(price) from titles);**************************************************************************************************

Jan-04-2002:

Exists: select cname from customers where exists ( select cid from orders where customers.id=orders.id);

Exists has equal meaning of =Any

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 becausethe join inside the subquery it does not make correlated subquery.]

2.The field in the join is from the outer query table... [Either the right or left side of the join should include the field in the outer query]

The execution of the correlated sub query is like join...

Example: select cname from customers where exists ( select cid from orders where customers.id=orders.id); 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...

It(Exist) is Intersection of the values in the different table..

But simple query Not Exist is equal to Difference

select cname from customers where cid in ( select * from orders ); // Error . We can not compare one field with many fields.

Page 143: Query

143

Query - Page #13

select cname from customers where exists ( select * from orders where customers.id=orders.id); // It would not give any error because the inner query will give only boolean values.... --------------------------------------------------------------------------------------------------------

7-01-2002:

select distinct a.au_fname from authors a, authors bwhere a.state = b.state and a.au_id <> b.au_id;

Any self join can be carried out through correlated sub query.

select a.au_fnamefrom authors awhere 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 outer table.

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 executed...If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct clause in the correlated sub query.

What is difference between self join and correlated sub query??Ans: The self join continues until all the records matched but the correlated sub query becomes true, it would not go further.

------------------------------------------------------------------------------------------------------------------Union:

It gives common and uncommon things in the two query....

select * into sen_temp_table from authors where state = ’LA’; select * from authors union select * from sen_temp_table; // It will not give the duplicates of the records 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 type needed select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mismatach,If the implicit conversion possible it will work

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 order by au_id; // Allowed 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:

Find total purchase for each customer??????????

Ans:drop vicreate view v_sample asselect 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

select max(tprice) from v_sample

Page 144: Query

144

Query - Page #14

Find which customer purchased more????

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 UserGrant All Table_name to UserRevoke select|update|insert|delete on Table_name from UserRevoke All Table_name from User

select * from syspermissions;sp_pkeys sen_traveller; View: The View is the Projection of the base tables...

Syntax: Create View view_name as select statement

Create view sen_view_empdatasselect eid,ename,did,dname from emp,deptwhere emp.did = dept.did;

Grant select on v_empdat to sa

Step 1:create view sen_view_v1 asselect * 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;

select * from authors;

select * from titles;

*************************************************************************************************

16-January-2002:

The View can include on only "select" statement.

Ex:

create view v1 as select.....

We can use delete,insert,update and select on views. Create view v2 asselect 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

To make work the above statement....

create view v2 asselect pub_id,sum(price) as "Total" from titles group by pub_id (or)create view v2(publishers_id,price) asselect pub_id,sum(price) as "Total" from titles group by pub_id

Page 145: Query

145

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 table emp( empno varchar(20) not null, emp_name varchar(20) not null, salary float not null, dept_id varchar(20) not null, phone varchar(20) not null);

create view v1 as select emp_no,emp_name,dept_id,phone from emp; // It would not work...

create view v1 asselect * form emp; // It will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olnyit 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...

Views using joins: 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...

////////////////////////////////////////////////////////////////////////////////////////////////

create view v_emp asselect * from emp where dept_id = ’HRD’;

select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS table and 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....

select * from emp where sal>2500 and dept_id=’HRD’;

Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpretedas below....

Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....

With Check option: create view v_emp as select * from emp where dept_id=’HRD’ with check option

insert v_emp values(’e1001’,’boris’,’HRD’,2000); // It works fine

insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view hasbeen created by with check option condition. It allow only the where clause condition is match, itmeans that we can insert only ’HRD’ type......

/////////////////////////////////////////////////////////////////////////////////////////////////

Question: Find which type sales is greater???

We can not write in single select statement....

create view sen_v1 as

Page 146: Query

146

Query - Page #16

select type,sum(price)as "Total_sales" from titles group by type

select type,max(Total_sales) from sen_v1 group by type,Total_sales having Total_sales= (select max(Total_sales) from sen_v1)

select type from sen_vl where Total_sales =(select max(Total_sales) from sen_v1)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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. One procedure can have 1024 parameters.

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...

create procedure procedure_name[(parameters)] [ ]--->optional as sql statements;

create procedure pro as select * from authors,publishers where authors.city = publishers.city;

create procedure pro as select * from emp; // In this statement,While creating procedure, it checks only the syntax errors it will not check the existence of the objets. In other words the object need not be existence while creating procedures but view the objects has to exist.

create procedure pro as select sal from emp; // In this statement, it checks the existence of the object,if it is, itchecks the existence of the column, if it is, the procudure will be created...if the column doesnot exist,it will give error....If there is non existence of the object,it will not check the existence of the column,the procedure will be created....

Either existence of object or non-existence of the object,the procedure will be created....

The created procedure have an entry in sysobjects table.....The statements are used in procedure will be stored in syscomments table. To execute the procedure...

Exec pro // while creating procudure, it checks only the syntax, while executing, the compilationprocess is done..

select object_id (’demo’); // we can get the table id what the sql server maintains...

create procedure pro(parameters) with recompileas sql statements; // It will be recompiled for every execution of this procedure.....

//////////////////////////////////////////////////////////////////////////////////////////////what is Query plan????

The query plan is nothing but the path of the execution in the sql statements...

Exec pro;

step 1: the procedure is compiled step 2: creates query plan,this query plan is stord in procedure cache it is like obj file step 3: it executes the obj file and gives the output....

The step 1 and step 2 will be executed at the first execution of the procedure..if u executethe procedure another time, it will no go for compilation process,it just checks the procedure

Page 147: Query

147

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:

Create procedure sen_sample_procedure(@param varchar(20)) as -- sen_sample_procedure(@param varchar(20) = ’psychology’)// default parameter -- sen_sample_procedure(@param varchar(20) = ’psychology’,@price=20.0) // Overridding default parameters declare @price float

select @price = sum(price) from titles group by type having type = @param;

if(@price <=100) return 1; if(@price>100 and @price<=200) return 2; if(@price >200) return 3;

-------------------------------------

declare @ret int

exec @ret=sen_sample_procedure ’psychology’ --exec @ret=sen_sample_procedure default,50 // Overridding default parameters --exec @ret=sen_sample_procedure @price=50,@param=’business’ // Explicit passing values if @ret = 1 begin select "Return 1"; end if @ret = 2 begin select "Return 2"; end

if @ret = 3 begin select "Return 3"; end

Note: The TSQL does not contain for loop,arrays..... goto,else,break are there

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

declare @value int,@expr int select @value = case @ex when 1 then only one value when 2 then only one value when 3 then only one value

Note: To assign to value to variable select @ret = 1; (or) set @ret = 1;

Example:

SELECT ’Price Category’ = CASE WHEN price IS NULL THEN ’Not yet priced’ WHEN price < 10 THEN ’Very Reasonable Title’ WHEN price >= 10 and price < 20 THEN ’Coffee Table Title’ ELSE ’Expensive book!’

END,title AS ’Shortened Title’ FROM titles

Example

Page 148: Query

148

Query - Page #18

declare @ret int set @ret = 1 select @ret =

case(@ret) when 1 then 10 when 2 then 20 when 3 then 30

end select @ret /////////////////////////////////////////////////////////////////////////////////////////////////

19-01-2002:

Output Parameters:

Question: Write the procedure to find the city and state of the given publishers????

create procedure sen_pro(@pub_name varchar(20), @city varchar(20) output, @state varchar(20) output) as select @state=state,@city=city from publishers where pub_name like @pub_name;

create procedure sen_callpro(@param varchar(20)) as declare @rstate varchar(20); declare @rcity varchar(20); exec sen_pro @param,@city=@rcity output,@state=@rstate output; select "pub state " + @rstate; select "pub city " + @rcity;

exec sen_callpro "New Moon Books";------------------------------------------------------------------------------------------------

Question: Write a procedure to check the given title_id has been written 2 authors, if so print the 2 author names

Create procedure sen_proce(@t_id varchar(20)) as declare @a varchar(20) if exists(select ta.title_id from titleauthor ta,titles t where ta.title_id=t.title_id and t.title_id = @t_id group by ta.title_id having count(*) = 2) begin select ta.au_id into #temp from titleauthor ta,titles t where ta.title_id = t.title_id and t.title_id = @t_id; select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a delete from #temp where au_id = @a select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a end else print "the book does not have exactly 2 authors" exec sen_proce ’PS2091’

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:

create proc pro asgoto aa:print "dgs"-------------------------------------------------------------------------------------------------

21-January-2002:

E-R Diagram: Entity: The entity is an object about information can be recorded..

Page 149: Query

149

Query - Page #19

For example, the employee and dept entity has some relationship between them...

The are 3 different types of relationship....

1. One to One2. One to Many3. Many to Many

{Chen notation}

[Entity] [Relation] [Entity]Employee---------- Works In ----------------Dept|[Rect] [Diamond] [Rect]||-------has --------Address [Diamond] [Rect]

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] andone to many[right to left] realationship comes either side,Take a one to many relationship...)

Employee(Optional-entity) Dept ( Optional-entity)eid did did dname(Attributes) (Attributes)e1 d1 d1e2 d1 d2e3 d2 d3e4 d2 (one dept can have zero or many employees)e5 null (employee has not been assigned to zero or one dept)

Cardinality: no of occurences of field value in dependant entity...

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...)

2.emp(1,M) one employee has one or many address.. address(1,1) one address has only one employee.. emp has existence dependent with address (address can not be created before emp so we change to Address has existence dependent with 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..)

Example:(one to many relationship) ( contains two Tables) [Rect] [Diamond] [Rect] Professor -------------- Advises -----------Student [Entity](0,N) [Entity](1,1)

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]

Example:(one to one relationship) ( contains only one table)

[Rect] [Diamond] [Rect] Professor -------------- is allotted -----------Room [Entity](0,1) [Entity](0,1)

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 ]

Example:(Many to Many relationship) ( contains 3 tables)

[Rect] [Diamond rounded square] [Rect] Theater -------------- is shown ---------------- Films [Composite Entity](1,N) [Composite Entity](1,N)

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 ]

Page 150: Query

150

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...

Theatre (entity) Films (entity) TheatreFilm (Associative Entity) or Junction Table ------------------------------------------------------------------------------------------ tid (pk) fid (pk) tid tname fname fid no_seats hero composite primary key(tid,fid) location heroine

Example:(Many to Many relationship) ( contains three tables)

[Rect] [Diamond rounded square] [Rect] Authors -------------- Writes ------------------ titles [Composite Entity](1,N) [Composite Entity](1,N)

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 qurey...

Any database desin normally will not go beyond the third normal form....

First Normal from: Drive the table using E-R Diagrams... (*) Any table should have atomic values(Every field should record atomic information)

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 record...and take to consideration the table should not have more null value fields.

Example:

eid pid did nohrs dhead-------------------------- e1 p1 is 20 boris e2 p1 is 20 boris e3 p2 net 30 peter e4 p2 net 30 sampry e1 p2 is 30 Andrew

* Primary key should be identified [ composite primary key(eid,pid) ] ---------------------------------------------------------------------------------------------------------

Second Normal Form:

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 id 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 entrily on the primary key and put it separate table along with the field on which the non key attribute is dependent on...

so we take off did from the above table

eid did ---------

Page 151: Query

151

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 eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

---------------------------------------------------------------------------------------------------------Third Normal Form: All the non key attributes should be dependent only on the primary key

eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only thedid which is not a primary key of the table....

Take the dhead along with it is dependent....

did dhead-------------- IS boris NET peter

----------------------------------------------------------------------------------------------------------

Database is a collection of data with controlled redundancy.....

*************************************************************************************************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 deleteany enty in the master table,which is refered by in the child table...The SQL server maintainsrestrictions automatically...The cascade deletions is opposite of these restrictions....

Syntax:

Create trigger trigger_name on table for operation as SQL Statements....

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 aftertrigger,The SQL could not support Before Triggers.....

Trigger can not accept parameters.....

Page 152: Query

152

Query - Page #22

Book Magazine----------------------------Bid MagidBname MnameAuthor price

Transaction--------------TidCard_idbook_idissue_datereturn_date--------------------------------------------------------------------------------------------------Implementing primary key constraint:-

Create trigger tri on tempfor insert asdeclare @icount intselect @icount=count(*) from temp,insertedwhere temp pk = insert pkif @icount >1begin print ’Duplicate Record’ rollbackendelse print ’Successfully on inserting the record’

inserted--->trigger test table (or) magic table-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on empfor insert asif not exists(select * from dept,inserted wheredept.did=inserted.did)begin print "Integrity violation" rollback;endelse print "successfull insertion into the table"

emp inserted----------------------------------------------------e1 boris d1 d1 HRDe2 becker d2 d2 SYSe3 sapeg d3

-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on trans_member for insert asif not exists (select * from books,inserted where book.book_id =inserted.book_id)begin if not exists (select * from magazines inserted where magizines.mag_id = inserted.book_id) begin print ’Ref integrity violation’ rollback end else print ’Successfully inserted into the table’endelse print ’Successfully inserted into the table’

Page 153: Query

153

Query - Page #23

-------------------------------------------------------------------------------------------------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:-

Create trigger dtrion publishersfor deleteasdelete from titles where titles.pub_id = deleted.pub_id

publisher table-->Trigger Table

The value from Trigger table is moved into Trigger Test Table (Deleted Table) -------------------------------------------------------------------------------------------------Implementing Restriction on deletion:-

Create trigger dtrion publishersfor deleteasif exists( select * from titles,deleted where titles.pub_id=deleted.pub_id)begin print ’Attempt to create orphan Records’ rollbackend

------------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables?????

Hits provided:declare @i intselect @i=Object_id(’publishers’)

if exists(select * from sysobjects where id=@i) insert back_up select * from deleted

------------------------------------------------------------------------------------------------

31-JAN-2002:

customers invoice products----------------------------------------------cid oid pidcname cid pname pid qoh (quantity in hand) qty price

create trigger trion invoicefor insertasupdate products set qoh=qoh-inserted.qty from products,insertedwhere products.pid=inserted.pid

checking the availability of products:---------------------------------------

select @iqty = inserted.qty from insertedselect @qty = products.qty from inserted,productswhere inserted.pid=products.pidif(@qty<@iqty)begin print "invalid transaction" rollback returnend

Page 154: Query

154

Query - Page #24

-------------------------------------------------------------------------------------------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 invoicefor updateif update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback returnendif not exists (select * from products,insertedwhere inserted.productid=products.proudctidbegin print ’Fk violation on products’ rollback returnend--------------------------------------------------------------------------------------------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..........

The cursor contains following five ’jargons’

1....Declare2....Open3....Fetch4....Close5....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

// The scroll keyword is used to move the cursor up and down...declare cur cursor scroll for select c_id,title,author,publisher from sen_catlog

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;

Note: When closing the cursor, it destroies the result set.....-------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Page 155: Query

155

Query - Page #25

Note: It destroies the cursor [ like dropping tables ] -------------------------------------------------------------------------------------------------

Example with procedure:-

create procedure sen_cur_pro asdeclare cur cursor scrollforselect * from sen_catlogopen curfetch next from curwhile(@@fetch_status=0)begin fetch next from curendclose curdeallocate cur

exec sen_cur_pro;

Note: @@fetch_status is system defined global variable which is automatically set to 0 whichindicates for successful fetch...------------------------------------------------------------------------------------------------1-02-2002:

Application of Cursors:

Create procedure sen_cpro asdeclare @tid varchar(20),@title varchar(20),@price floatdeclare cur cursor scrollforselect title_id,title,price from titlesopen curfetch next from cur into @tid,@title,@pricewhile(@@fetch_status=0)begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@priceendclose curdeallocate cur

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??????

create procedure sen_publisher_books asset nocount ondeclare @pid varchar(20),@pname varchar(20)declare @tid varchar(20),@title varchar(20),@price floatdeclare @n intdeclare cur cursor scrollforselect pub_id,pub_name from publishersopen curfetch next from cur into @pid,@pnamewhile(@@fetch_status=0)begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid

Page 156: Query

156

Query - Page #26

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,@pnameendclose curdeallocate cur exec sen_publisher_books --------------------------------------------------------------------------------------------------------------2-Feb-2002:

Indexing: It is a sorting process to reduce the searching process time....

Syntax:

Create { nonClustered } index index_nameon table_name(field_name)

Default is Clustered indexing................-------------------------------------------------------------------------------------------------NonClustered:

create nonclustered index emp_enoon emp(eno)

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 orit 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:

create clustered index emp_enoon emp(eno)

The table itself will be sorted on a field name

-----------------------------------------------------------------------------------------------Note: The clustered index points the page...but the nonclustered index points the exact match ofrecord...

1...The Clusterd index is efficiant for duplicte records ( Foreign key)2...The nonClustered index is efficient for unique records (primary key), for the primary key creation the SQL server creates Clusterd index, it is our responsiblity to give nonClusterd index when creating the primary key......------------------------------------------------------------------------------------------------Note: One Clustered index is allowed for a table, but as many nonClustered index is allowed for a table------------------------------------------------------------------------------------------------

Page 157: Query

157

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 keeptrack of so many members and transactions,which are currently maintained in registers. The chieflibrarian approaches you to seek help for designing a computerized system. All members in thelibrary are given two member cards and one book is leased for each card. The membership fee foreach member is Rs 500. One time payment,refundable on relinquishing of the cards.Both books andmegazines are leased to the members.A book lent to a member can be with him for 15 days at mostand an extension of another 15 days is given to the member for that particular book if that bookis brought for renewal on the 15 th day after it is lent.The same member is not allowed to havethe book for another 15 days after it is returned.Magazines are lent only for 4 days and noextension is allowed and there is no restriction for lending the magazine to the same member,as isthe 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 particularmagazine 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 bookthat is there in the library. One copy of each book is designated as reference and it is not lentto 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);

Create Table sen_books( b_id varchar(10) constraint sb_pk primary key, c_id varchar(10) constraint sb_fk1 references sen_catlog(c_id), status varchar(10));

Create Table sen_member( m_id varchar(10) constraint sm_pk primary key, mname varchar(20) not null, address varchar(20),);

Create Table sen_cards( card_id varchar(10) constraint sen_cpk2 primary key, m_id varchar(10) constraint sen_cfk3 references sen_member(m_id));

Create Table sen_transaction( trans_id varchar(10) constraint sen_ctpk1 primary key, b_id varchar(10) constraint sen_ctfk1 references sen_books(b_id), card_id varchar(10) constraint sen_ctfk2 references sen_cards(card_id), tdate datetime not null, rdate datetime, ex_bit bit,);

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);

Page 158: Query

158

Query - Page #2

select * from sen_catlog;

insert into sen_books values (’B001’,’CB001’,’issue’);insert into sen_books values (’B002’,’CB001’,’issue’);insert into sen_books values (’B003’,’CB001’,’reference’);insert into sen_books values (’B004’,’CB002’,’issue’);insert into sen_books values (’B005’,’CB002’,’issue’);insert into sen_books values (’B006’,’CB002’,’Reference’);insert into sen_books values (’B007’,’CB003’,’issue’);insert into sen_books values (’B008’,’CB003’,’Reference’);

select * from sen_books;

insert into sen_member values(’M001’,’senthil’,’Drive square,London’);insert into sen_member values(’M002’,’Ashiwarya’,’West valley,sidney’);insert into sen_member values(’M003’,’kumar’,’Eiffle Tower, Paris’);

select * from sen_member;

insert into sen_cards values(’C001’,’M001’);insert into sen_cards values(’C002’,’M001’);insert into sen_cards values(’C003’,’M002’);insert into sen_cards values(’C004’,’M002’);insert into sen_cards values(’C005’,’M003’);

select * from sen_cards;

insert into sen_transaction values (’T001’,’B001’,’C001’,’12-10-2000’,null,null);insert into sen_transaction values (’T002’,’B002’,’C002’,’11-11-2000’,’11-25-2000’,null);insert into sen_transaction values (’T003’,’B004’,’C004’,’10-10-2000’,’10-25-2000’,1);insert into sen_transaction values (’T004’,’B004’,’C004’,’09-27-2000’,’10-10-2000’,0);insert into sen_transaction values (’T006’,’B002’,’C003’,’01-28-2000’,null,0);insert into sen_transaction values (’T007’,’B004’,’C002’,’01-28-2000’,’02-10-2000’,0);insert into sen_transaction values (’T008’,’B005’,’C005’,’01-28-2000’,null,0);

select * from sen_catlog;select * from sen_books;select * from sen_member;select * from sen_cards;select * from sen_transaction;

set nocount on --------------------------------------------------------------------------------------------------------------1. For each book you will have to generate the members to whom copies of it have been lent....

create procedure sen_books_issue as declare @n int declare @i int declare @b varchar(10) declare @c varchar(10) declare @t_title varchar(20) declare @t_bid varchar(10) declare @t_name varchar(20) declare @t_card varchar(20) select @n=count(b_id) from sen_transaction where rdate is null; if @n=0 print ’No books found’ else begin select b_id,card_id into #temp from sen_transaction where rdate is null 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

Page 159: Query

159

Query - Page #3

end end

exec sen_books_issue --------------------------------------------------------------------------------------------------------------2.Generate a report which displays all the books. You will have to include all the relevant information in the report

create procedure sen_books_details asdeclare @c varchar(10)declare @n intdeclare @i int select c_id into #temp from sen_catlog; select @n=count(c_id) from #temp if(@n=0) print ’No books in the catlog’ else begin select @i=1 while(@i<=@n) begin select top 1 @c=c_id from #temp select @c,title,author,publisher,price from sen_catlog where c_id=@c select b_id,status from sen_books where c_id=@c delete from #temp where c_id=@c; set @i = @i+1 end end

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...

Create procedure sen_book_delevered(@ddate datetime) asdeclare @n int declare @i intdeclare @b varchar(10)declare @c varchar(10)declare @r datetimedeclare @t_title varchar(20)declare @t_bid varchar(10)declare @t_name varchar(20)declare @t_card varchar(20)declare @message varchar(20)

select @n=count(b_id)from sen_transaction where tdate=@ddateif(@n=0) print ’No one book has been delivered on that day’else begin select b_id,card_id,rdate into #temp from sen_transaction where tdate=@ddate select @i = 1 while(@i<=@n) begin select top 1 @b=b_id,@c=card_id,@r=rdate 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

if(@r is null) set @message=’Not Returned’ else set @message=’Returned’ print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid + " " + @message end end 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

Page 160: Query

160

Query - Page #4

been over and has not yet been returned....

declare @dday datetime SELECT @dday=DATEADD(day, -15, getdate()) print @dday

Create procedure sen_overdue_books(@date datetime) asdeclare @n int declare @i intdeclare @b varchar(10)declare @c varchar(10)declare @t_title varchar(20)declare @t_bid varchar(10)declare @t_name varchar(20)declare @t_card varchar(20)declare @message varchar(20)declare @dday datetime

select @dday=DATEADD(day,-15,@date) select @n=count(b_id)from sen_transaction where rdate is null and tdate<@ddayif(@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 exec sen_overdue_books @date=’2000-02-25’

-------------------------------------------------------------------------------------------------

Page 161: Query

Query - Page #1

------------------SQL NOTE -------------------------------------------------------------- Author : E Senthil -----------------------------------------------------------------------------------------

// Create A Table with out primary key

CREATE TABLE sen_emp ( empno int, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int );

************************************************************************************************// Set Primary key with ALTER TABLE COMMAND

ALTER TABLE sen_emp ALTER COLUMN empno int not null; ALTER TABLE sen_emp ADD CONSTRAINT __PK PRIMARY KEY (empno);

// Before Adding PRIMARY KEY CONSTRAINT TO A COLUMN, // make sure it should not accept null values **********************************************************************************************// Create A Table with a Primary key

create table sen_dept ( dept_no int constraint _pk primary key, dname char(20), location char(20) );

********************************************************************************************* // Set Referencial Integrity [ Joining two tables ]

Alter table sen_emp Add constraint _fk foreign key(dept_no)references sen_dept(dept_no);

*********************************************************************************************// Create a table with primary key and foreign key

CREATE TABLE sen_emp ( empno int CONSTRAINT PK PRIMARY KEY, first_name varchar(20), second_name varchar(20), salary numeric(8,2), manager_no int, hire_date datetime, dept_no int CONSTRAINT FK FOREIGN KEY REFERENCES sen_dept(dept_no) );

***********************************************************************************************// Droping a Constraint

ALTER TABLE sen_emp DROP CONSTRAINT __PK;

*************************************************************************************************// Droping a Column in a Table

ALTER TABLE sen_emp DROP COLUMN empno;

***********************************************************************************************// Create a Table with default value

CREATE TABLE _TEMP ( empno int,

Page 162: Query

Query - Page #2

ename varchar(20), city varchar(20) default ’cbe’);

// Add a Default value to a column

ALTER TABLE _TEMP ADD default ’sen’ for ename;

//Drop the Default constraint from a column

ALTER TABLE _TEMP DROP CONSTRAINT DF___TEMP__CITY__6C6E1476 ***********************************************************************************************// Creating Check Constraint for a column

ALTER TABLE _TEMP with [nocheck] ADD CONSTRAINT CKEMPNO CHECK( EMPNO>100 );

*****************************************************************************************// Disabling Check constraint

ALTER TABLE _temp NOCHECK CONSTRAINT CKEMPNO;

// RE-Enabling Check constraint

ALTER TABLE _temp CHECK CONSTRAINT CKEMPNO;

******************************************************************************************// Create a new table and copy only some particular fields of another Table

select empno,second_name,salary into temp_sen_emp from sen_emp;

******************************************************************************************//Create A Table and copy the data from another Table

Create Table vinod ( name varchar(20) );

insert into vinod select second_name from sen_emp;

******************************************************************************************

select * from authors;

select * from authors where au_lname like ’[^a-r]%’;select * from authors where au_lname like ’[a-r]%’;select * from authors where au_lname like ’_[a-r]%’;

select * from sen_emp where second_name like ’[^a-r]%’ or second_name like ’G%’

select * from sen_emp;

insert into sen_emp (empno,second_name) values (1500,’gallifer’);

*********************************************************************************************Grouping:

select sum(salary) from sen_emp;

select * from sen_emp;

select sum(salary) from sen_emp group by dept_no;

select sum(price) from titles group by type;

select sum(price) from titles;

select * from titles order by type;

select * from titles;

select sum(price) from titles group by type;

Page 163: Query

Query - Page #3

select sum(price) from titles;

select sum(price) as total_salary from titles;

select sum(price) "Total_salary" from titles;

select * from sen_emp;

select dept_no,sum(salary)’Total Salary’ from sen_emp group by dept_no order by dept_no;

select type, sum(type) from titles;

select sum(salary) from sen_emp order by dept_no group by dept_no; // Error

______________________________________________________________________________________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) from titles group by type,pub_id;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id order by type;

select type,pub_id,sum(price) "Sum of Salary" from titles group by type,pub_id order by type asc,pub_id desc;

sp_help titles

select type,sum(price) from titles group by type;

select type,pub_id from titles;

select type,pub_id,sum(price) from titles group by type,pub_id

******************************************************************************************// Select keywords SELECT FROM [WHERE] [GROUP BY] [HAVING] [ORDER BY] [COMPUTE BY] [COMPUTE]******************************************************************************************

SELECT TYPE,PUB_ID,SUM(PRICE) "TOTAL PRICE"FROM TITLESGROUP BY TYPE,PUB_ID;

SELECT *FROM TITLESORDER BY TYPE DESC;

//////////////////////////////////////////////////////////////////////////////////////////select type,sum(price)from titlesgroup by typeorder 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 titlesgroup by typeorder by title_id; // Error

select type,title_id,sum(price)from titlesgroup by type,title_idorder by title_id;

select * from titles;

Page 164: Query

Query - Page #4

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:-----------------

select type,sum(price) from titles group by type; Result set Business 1100 Computer 700 Novel 800

Compute By class:

select type,sum(price) from titles compute by type; // error

select type,price from titlesorder by type compute sum(price) by type; Rule: 1.Whenever we use compute By class, it must to use order by class. 2.The field which appear in compute by class is must appear in order by class 3.Whatever field in the aggregate funtion, which is also in the select list.

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 itselfable to generate Work Table...So the Compute by class relay order by class...

select type,pricefrom titlesorder by pub_idcompute 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 ofprice by Type...’

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type;

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by pub_id; // Error

Reason: Work Table

Type pub_id Price--------------------------Business p1 200Business p1 200Business p2 300Computer p2 400

Page 165: Query

Query - Page #5

Computer p2 200Novel p1 200Novel p1 240Novel p2 450

In above work table, The pub_id is clubed according to the Typenot clubed alone...That is why it will flash error...

select type,pub_id,pricefrom titlesorder by type,pub_idcompute sum(price) by type,pub_id;

select type,pub_id,title_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id,title_id;

select type,pub_id,pricefrom titlesorder by type,pub_id,title_idcompute sum(price) by type,pub_id;****************************************************

Afternoon:21-dec-2001

select type,pub_id from titles;

1...select distinct type,pub_id from titles;

2...select type,pub_id from titles group by type,pub_id;

Query 1 and 2 give the same result

select type,pub_id from titlesgroup by type,pub_id;

select distinct type,pub_id from titles;

// In the above query.. The Distinct applies both type and pub_id columns..We can not make to applyfor a particular column. It will apply all the columns in the select list

For Ex

Business p1 200Business p1 400Business p1 300Computer p2 500Computer p2 700

The Result is

Business p1 200Computer p2 500

/////////////////////////////////////////////////select type,sum(price),avg(price)from titlesgroup by price; // Error

Reason: The field name in group by clause which is not used in aggregate function in select list

Page 166: Query

Query - Page #6

//////////////////////////////////////////////////////////

Having: Having clause should have group by class...but when using group by class it is optionalto use Having clause.

It affects the result of the Group By Class......

Work Table -----> Internal Result Set -----> Output

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...

Both 1 and 2 are gives same result......

Query 2 Work Table:

Olny Business Records are present

But Query 1 Work Table: All types of Records like Business,Computer and Novel and then take Business Records are Filtered

///////////////////////////////////////////////////////////////////////////////

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

// It would not work Reasons: 1. The left hand side of the where class shoul be column name... 2. Here The Group by class run after the where class...but where class we used aggregate functions...This aggregate function will not use group by class..

select type,sum(price)from titleswhere sum(price) > 1000group by type; // Error Rule 1 and 2

select type,sum(price)from titleswhere 1000<sum(price)group by type; // Error Rule 2

/////////////////////////////////////////////////////////////////////////////////////////////////

December-26-2001

Joins:

select * from authors,publishers; // It does the cartisean product of two tables....

Page 167: Query

Query - Page #7

if the select statement contains more table in from clause without where clause, it is calledcross joining which is never used...

select * from authors,publisherswhere authors.city = publishers.city;

Joins are evaluated just like Nested Loops....

for(i=0;i<=10;i++) One Table for(j=0;j<=5;j++) Another Table if(i==j) Where clause condition { }

select authors.au_id,authors.au_lname,authors.phone,publishers.pub_id,publishers.pub_name,publishers.cityfrom authors,publishers where authors.city = publishers.city;

select authors.*,pub_id,pub_name from authors,publisherswhere 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, publishers p where authors.city=p.city;

select p.*,au_id,au_lnamefrom authors a, publishers pwhere a.city = p.city and a.au_lname like ’c%’

select p.*,au_id,au_lnamefrom authors a, publishers pwhere au_lname like ’c%’ and a.city = p.city

Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select * from authors; select * from publishers; select * from titles; select * from titleauthor;

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:.................

Page 168: Query

Query - Page #8

Explanation:

Title: Authors

au_id au_lname ----------- ----------------------------a1 lockleya2 peter

Table: Publisher

pub_id pub_name ------ -----------p1 samyp2 golgotiap3 samba

Table: Titles

title_id pub_id -------- --------t1 p1t2 p2t3 p3

Table: TitleAuthor

au_id title_id ----------- -------- a1 t1a1 t2a2 t1a2 t3

Virtual Tables:

[Authors] [TitleAuthor]aid aname au_id title_ida1 lockey a1 t1a1 lockey a1 t2

[authors] [titleAuthor] [titles]aid aname aid title_id title_id pub_ida1 lockey a1 t1 t1 p1a1 lockey a1 t2 t2 p2

[authors] [titleAuthor] [ titles ] [ publisher]aid aname aid title_id title_id pub_id pub_id pub_name a1 lockey a1 t1 t1 p1 p1 sams a1 lockey a1 t2 t2 p2 p2 golgotia

FAQ:

1. How the joins are works???

Ans: It works as Nested Loops

2.What is the Query Optimizer? Ans: The Query optimizer find out which join will be evaluated first and run the query in the optimized way....

3. How many Virtual Table created for N conditions??

Page 169: Query

Query - Page #9

Ans: (N-1) Virtual Tables are created for N tables

Cross Checking:

select * from authors where au_lname like ’Loc%’;select * from titleauthor where au_id = ’486-29-1786’; select * from titles where title_id=’PC9999’ or title_id=’PS7777’; select * from publishers where pub_id =’1389’ or pub_id=’0736’;

////////////////////////////////////////////////////////////////////////////////////////////////

Renaming the Tables

sp_rename <OldTable> <NewTable>

////////////////////////////////////////////////////////////////////////////////////////////////

Taking a Copy of the Table:

Create Table vinod_temp( eno int identity(1,1), ename varchar(20), dept_id int);

insert into vinod_temp(ename,dept_id) select ename,dept_id from sen_temp;////////////////////////////////////////////////////////////////////////////////////////////////

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

Result set would be A1A6A2A3

select a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays duplicate Records

Page 170: Query

Query - Page #10

select state,count(*) from authorsgroup by statehaving count(*)>1 // We should not use group by function in the self joining situations

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city; // It displays distinct records but it dispalys one author lives in the city

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered...

select distinct a.au_id,a.cityfrom authors a, authors bwhere a.city = b.city and a.au_id <> b.au_id order by a.city; // It displays the perfect result Note: The condition [a.au_id <> b.au_id] eliminates checking the records with itself.....

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Create Table patdat( patno varchar(20) not null, name varchar(20) not null, address varchar(20));

Create Table patadm( patno varchar(20) not null, admno varchar(20) not null, addate datetime, constraint sen_pk2 primary key(patno,admno), constraint fk foreign key(patno) references patdat1(patno));

Create Table operdat( patno varchar(20), admno varchar(20), opno int, opdate datetime, type varchar(20)

constraint sen_pk2 primary key(patno,admno,opno), constraint sen_fk foreign key(patno) references patdat(patno), constraint fk1 foreign key(admno) references patadm1(admno) );

Note: constaint fk1 could not be created.... ’We can not refer the part of the primary key(composite key) in another Table’

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Question: Find the author id who has written more than one book??? select distinct ta1.au_id from titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id;

Question: Find the title_id which has been written by more than one author?

select distinct ta1.title_id from titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id;

Question: Find the author Names who has written more than one book???

Page 171: Query

Query - Page #11

select distinct a.au_lname,a.au_fname from authors a,titleauthor ta1,titleauthor ta2 where ta1.au_id = ta2.au_id and ta1.title_id <> ta2.title_id and ta1.au_id = a.au_id;

Question: Find the titles which has been written by more than one author? select distinct t.title from titles t,titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id and ta1.title_id = t.title_id;

/////////////////////////////////////////////////////////////////////////////////////////////////Jan 02 2002:

Outer join: emp e1 boris HRDe2 becker HRDe3 peter SYSe4 Anderw SYSe5 Lafer null

dep

HRD Human ResSYS SystemsPER personalNET network

emp

enoenamed_id

dept

ddiddname

Display the emp details along with dept id??

select emp.* d.did from emp e,dept dwhere e.did=d.did

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYS

select emp.*,d.did from e,dept dwhere e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax)

REsult Sete1 boris HRDe2 becker HRDe3 peter SYSe4 Andrew SYSe5 lafer

select emp.*,d.did from e,dept dwhere e.did =* d.did; // Display the matching records and addition to all

Page 172: Query

Query - Page #12

unmatching records form dept (SQL Server Syntax)

select * from employee inner join dept on e.deptid=d.detptid (ANSI Syntax)

The above two query gives the same result..

////////////////////////////////////////////////////////////////////////////////////////////

Full outer join: select employee.eno,employee.name,d.did from employee full outer join dept on employee.did=dept.did (ANSI Syntax) [ Where <filter condition> ]

///////////////////////////////////////////////////////////////////////////////////////////////

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;

select * from titles where price = (select max(price) from titles);**************************************************************************************************

Jan-04-2002:

Exists: select cname from customers where exists ( select cid from orders where customers.id=orders.id);

Exists has equal meaning of =Any

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 becausethe join inside the subquery it does not make correlated subquery.]

2.The field in the join is from the outer query table... [Either the right or left side of the join should include the field in the outer query]

The execution of the correlated sub query is like join...

Example: select cname from customers where exists ( select cid from orders where customers.id=orders.id); 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...

It(Exist) is Intersection of the values in the different table..

But simple query Not Exist is equal to Difference

select cname from customers where cid in ( select * from orders ); // Error . We can not compare one field with many fields.

Page 173: Query

Query - Page #13

select cname from customers where exists ( select * from orders where customers.id=orders.id); // It would not give any error because the inner query will give only boolean values.... --------------------------------------------------------------------------------------------------------

7-01-2002:

select distinct a.au_fname from authors a, authors bwhere a.state = b.state and a.au_id <> b.au_id;

Any self join can be carried out through correlated sub query.

select a.au_fnamefrom authors awhere 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 outer table.

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 executed...If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct clause in the correlated sub query.

What is difference between self join and correlated sub query??Ans: The self join continues until all the records matched but the correlated sub query becomes true, it would not go further.

------------------------------------------------------------------------------------------------------------------Union:

It gives common and uncommon things in the two query....

select * into sen_temp_table from authors where state = ’LA’; select * from authors union select * from sen_temp_table; // It will not give the duplicates of the records 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 type needed select price,title from titles union all select title_id,au_id from titleauthor; // Error data type mismatach,If the implicit conversion possible it will work

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 order by au_id; // Allowed 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:

Find total purchase for each customer??????????

Ans:drop vicreate view v_sample asselect 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

select max(tprice) from v_sample

Page 174: Query

Query - Page #14

Find which customer purchased more????

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 UserGrant All Table_name to UserRevoke select|update|insert|delete on Table_name from UserRevoke All Table_name from User

select * from syspermissions;sp_pkeys sen_traveller; View: The View is the Projection of the base tables...

Syntax: Create View view_name as select statement

Create view sen_view_empdatasselect eid,ename,did,dname from emp,deptwhere emp.did = dept.did;

Grant select on v_empdat to sa

Step 1:create view sen_view_v1 asselect * 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;

select * from authors;

select * from titles;

*************************************************************************************************

16-January-2002:

The View can include on only "select" statement.

Ex:

create view v1 as select.....

We can use delete,insert,update and select on views. Create view v2 asselect 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

To make work the above statement....

create view v2 asselect pub_id,sum(price) as "Total" from titles group by pub_id (or)create view v2(publishers_id,price) asselect pub_id,sum(price) as "Total" from titles group by pub_id

Page 175: Query

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 table emp( empno varchar(20) not null, emp_name varchar(20) not null, salary float not null, dept_id varchar(20) not null, phone varchar(20) not null);

create view v1 as select emp_no,emp_name,dept_id,phone from emp; // It would not work...

create view v1 asselect * form emp; // It will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olnyit 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...

Views using joins: 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...

////////////////////////////////////////////////////////////////////////////////////////////////

create view v_emp asselect * from emp where dept_id = ’HRD’;

select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS table and 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....

select * from emp where sal>2500 and dept_id=’HRD’;

Update v_emp set dept_id=’SYS’ where dept_id=’PER’; // It does nothing, because it is interpretedas below....

Update emp set dept_id=’SYS’ where dept_id=’PER’ and dept_id=’HRD’; // It true never....

With Check option: create view v_emp as select * from emp where dept_id=’HRD’ with check option

insert v_emp values(’e1001’,’boris’,’HRD’,2000); // It works fine

insert v_emp values(’e1001’,’boris’,’SYS’2000); // It would not work, because the view hasbeen created by with check option condition. It allow only the where clause condition is match, itmeans that we can insert only ’HRD’ type......

/////////////////////////////////////////////////////////////////////////////////////////////////

Question: Find which type sales is greater???

We can not write in single select statement....

create view sen_v1 as

Page 176: Query

Query - Page #16

select type,sum(price)as "Total_sales" from titles group by type

select type,max(Total_sales) from sen_v1 group by type,Total_sales having Total_sales= (select max(Total_sales) from sen_v1)

select type from sen_vl where Total_sales =(select max(Total_sales) from sen_v1)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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. One procedure can have 1024 parameters.

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...

create procedure procedure_name[(parameters)] [ ]--->optional as sql statements;

create procedure pro as select * from authors,publishers where authors.city = publishers.city;

create procedure pro as select * from emp; // In this statement,While creating procedure, it checks only the syntax errors it will not check the existence of the objets. In other words the object need not be existence while creating procedures but view the objects has to exist.

create procedure pro as select sal from emp; // In this statement, it checks the existence of the object,if it is, itchecks the existence of the column, if it is, the procudure will be created...if the column doesnot exist,it will give error....If there is non existence of the object,it will not check the existence of the column,the procedure will be created....

Either existence of object or non-existence of the object,the procedure will be created....

The created procedure have an entry in sysobjects table.....The statements are used in procedure will be stored in syscomments table. To execute the procedure...

Exec pro // while creating procudure, it checks only the syntax, while executing, the compilationprocess is done..

select object_id (’demo’); // we can get the table id what the sql server maintains...

create procedure pro(parameters) with recompileas sql statements; // It will be recompiled for every execution of this procedure.....

//////////////////////////////////////////////////////////////////////////////////////////////what is Query plan????

The query plan is nothing but the path of the execution in the sql statements...

Exec pro;

step 1: the procedure is compiled step 2: creates query plan,this query plan is stord in procedure cache it is like obj file step 3: it executes the obj file and gives the output....

The step 1 and step 2 will be executed at the first execution of the procedure..if u executethe procedure another time, it will no go for compilation process,it just checks the procedure

Page 177: Query

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:

Create procedure sen_sample_procedure(@param varchar(20)) as -- sen_sample_procedure(@param varchar(20) = ’psychology’)// default parameter -- sen_sample_procedure(@param varchar(20) = ’psychology’,@price=20.0) // Overridding default parameters declare @price float

select @price = sum(price) from titles group by type having type = @param;

if(@price <=100) return 1; if(@price>100 and @price<=200) return 2; if(@price >200) return 3;

-------------------------------------

declare @ret int

exec @ret=sen_sample_procedure ’psychology’ --exec @ret=sen_sample_procedure default,50 // Overridding default parameters --exec @ret=sen_sample_procedure @price=50,@param=’business’ // Explicit passing values if @ret = 1 begin select "Return 1"; end if @ret = 2 begin select "Return 2"; end

if @ret = 3 begin select "Return 3"; end

Note: The TSQL does not contain for loop,arrays..... goto,else,break are there

&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

declare @value int,@expr int select @value = case @ex when 1 then only one value when 2 then only one value when 3 then only one value

Note: To assign to value to variable select @ret = 1; (or) set @ret = 1;

Example:

SELECT ’Price Category’ = CASE WHEN price IS NULL THEN ’Not yet priced’ WHEN price < 10 THEN ’Very Reasonable Title’ WHEN price >= 10 and price < 20 THEN ’Coffee Table Title’ ELSE ’Expensive book!’

END,title AS ’Shortened Title’ FROM titles

Example

Page 178: Query

Query - Page #18

declare @ret int set @ret = 1 select @ret =

case(@ret) when 1 then 10 when 2 then 20 when 3 then 30

end select @ret /////////////////////////////////////////////////////////////////////////////////////////////////

19-01-2002:

Output Parameters:

Question: Write the procedure to find the city and state of the given publishers????

create procedure sen_pro(@pub_name varchar(20), @city varchar(20) output, @state varchar(20) output) as select @state=state,@city=city from publishers where pub_name like @pub_name;

create procedure sen_callpro(@param varchar(20)) as declare @rstate varchar(20); declare @rcity varchar(20); exec sen_pro @param,@city=@rcity output,@state=@rstate output; select "pub state " + @rstate; select "pub city " + @rcity;

exec sen_callpro "New Moon Books";------------------------------------------------------------------------------------------------

Question: Write a procedure to check the given title_id has been written 2 authors, if so print the 2 author names

Create procedure sen_proce(@t_id varchar(20)) as declare @a varchar(20) if exists(select ta.title_id from titleauthor ta,titles t where ta.title_id=t.title_id and t.title_id = @t_id group by ta.title_id having count(*) = 2) begin select ta.au_id into #temp from titleauthor ta,titles t where ta.title_id = t.title_id and t.title_id = @t_id; select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a delete from #temp where au_id = @a select top 1 @a = au_id from #temp select au_fname from authors where au_id = @a end else print "the book does not have exactly 2 authors" exec sen_proce ’PS2091’

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:

create proc pro asgoto aa:print "dgs"-------------------------------------------------------------------------------------------------

21-January-2002:

E-R Diagram: Entity: The entity is an object about information can be recorded..

Page 179: Query

Query - Page #19

For example, the employee and dept entity has some relationship between them...

The are 3 different types of relationship....

1. One to One2. One to Many3. Many to Many

{Chen notation}

[Entity] [Relation] [Entity]Employee---------- Works In ----------------Dept|[Rect] [Diamond] [Rect]||-------has --------Address [Diamond] [Rect]

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] andone to many[right to left] realationship comes either side,Take a one to many relationship...)

Employee(Optional-entity) Dept ( Optional-entity)eid did did dname(Attributes) (Attributes)e1 d1 d1e2 d1 d2e3 d2 d3e4 d2 (one dept can have zero or many employees)e5 null (employee has not been assigned to zero or one dept)

Cardinality: no of occurences of field value in dependant entity...

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...)

2.emp(1,M) one employee has one or many address.. address(1,1) one address has only one employee.. emp has existence dependent with address (address can not be created before emp so we change to Address has existence dependent with 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..)

Example:(one to many relationship) ( contains two Tables) [Rect] [Diamond] [Rect] Professor -------------- Advises -----------Student [Entity](0,N) [Entity](1,1)

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]

Example:(one to one relationship) ( contains only one table)

[Rect] [Diamond] [Rect] Professor -------------- is allotted -----------Room [Entity](0,1) [Entity](0,1)

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 ]

Example:(Many to Many relationship) ( contains 3 tables)

[Rect] [Diamond rounded square] [Rect] Theater -------------- is shown ---------------- Films [Composite Entity](1,N) [Composite Entity](1,N)

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 ]

Page 180: Query

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...

Theatre (entity) Films (entity) TheatreFilm (Associative Entity) or Junction Table ------------------------------------------------------------------------------------------ tid (pk) fid (pk) tid tname fname fid no_seats hero composite primary key(tid,fid) location heroine

Example:(Many to Many relationship) ( contains three tables)

[Rect] [Diamond rounded square] [Rect] Authors -------------- Writes ------------------ titles [Composite Entity](1,N) [Composite Entity](1,N)

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 qurey...

Any database desin normally will not go beyond the third normal form....

First Normal from: Drive the table using E-R Diagrams... (*) Any table should have atomic values(Every field should record atomic information)

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 record...and take to consideration the table should not have more null value fields.

Example:

eid pid did nohrs dhead-------------------------- e1 p1 is 20 boris e2 p1 is 20 boris e3 p2 net 30 peter e4 p2 net 30 sampry e1 p2 is 30 Andrew

* Primary key should be identified [ composite primary key(eid,pid) ] ---------------------------------------------------------------------------------------------------------

Second Normal Form:

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 id 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 entrily on the primary key and put it separate table along with the field on which the non key attribute is dependent on...

so we take off did from the above table

eid did ---------

Page 181: Query

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 eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

---------------------------------------------------------------------------------------------------------Third Normal Form: All the non key attributes should be dependent only on the primary key

eid did dhead---------------- e1 IS boris e2 IS boris e3 NET peter 24 NET

In the above table, the dhead is not dependent on the primary key (eid). the dhead only dependent only thedid which is not a primary key of the table....

Take the dhead along with it is dependent....

did dhead-------------- IS boris NET peter

----------------------------------------------------------------------------------------------------------

Database is a collection of data with controlled redundancy.....

*************************************************************************************************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 deleteany enty in the master table,which is refered by in the child table...The SQL server maintainsrestrictions automatically...The cascade deletions is opposite of these restrictions....

Syntax:

Create trigger trigger_name on table for operation as SQL Statements....

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 aftertrigger,The SQL could not support Before Triggers.....

Trigger can not accept parameters.....

Page 182: Query

Query - Page #22

Book Magazine----------------------------Bid MagidBname MnameAuthor price

Transaction--------------TidCard_idbook_idissue_datereturn_date--------------------------------------------------------------------------------------------------Implementing primary key constraint:-

Create trigger tri on tempfor insert asdeclare @icount intselect @icount=count(*) from temp,insertedwhere temp pk = insert pkif @icount >1begin print ’Duplicate Record’ rollbackendelse print ’Successfully on inserting the record’

inserted--->trigger test table (or) magic table-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on empfor insert asif not exists(select * from dept,inserted wheredept.did=inserted.did)begin print "Integrity violation" rollback;endelse print "successfull insertion into the table"

emp inserted----------------------------------------------------e1 boris d1 d1 HRDe2 becker d2 d2 SYSe3 sapeg d3

-------------------------------------------------------------------------------------------------Implementing foreign key constraint:-

create trigger tri on trans_member for insert asif not exists (select * from books,inserted where book.book_id =inserted.book_id)begin if not exists (select * from magazines inserted where magizines.mag_id = inserted.book_id) begin print ’Ref integrity violation’ rollback end else print ’Successfully inserted into the table’endelse print ’Successfully inserted into the table’

Page 183: Query

Query - Page #23

-------------------------------------------------------------------------------------------------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:-

Create trigger dtrion publishersfor deleteasdelete from titles where titles.pub_id = deleted.pub_id

publisher table-->Trigger Table

The value from Trigger table is moved into Trigger Test Table (Deleted Table) -------------------------------------------------------------------------------------------------Implementing Restriction on deletion:-

Create trigger dtrion publishersfor deleteasif exists( select * from titles,deleted where titles.pub_id=deleted.pub_id)begin print ’Attempt to create orphan Records’ rollbackend

------------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables?????

Hits provided:declare @i intselect @i=Object_id(’publishers’)

if exists(select * from sysobjects where id=@i) insert back_up select * from deleted

------------------------------------------------------------------------------------------------

31-JAN-2002:

customers invoice products----------------------------------------------cid oid pidcname cid pname pid qoh (quantity in hand) qty price

create trigger trion invoicefor insertasupdate products set qoh=qoh-inserted.qty from products,insertedwhere products.pid=inserted.pid

checking the availability of products:---------------------------------------

select @iqty = inserted.qty from insertedselect @qty = products.qty from inserted,productswhere inserted.pid=products.pidif(@qty<@iqty)begin print "invalid transaction" rollback returnend

Page 184: Query

Query - Page #24

-------------------------------------------------------------------------------------------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 invoicefor updateif update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback returnendif not exists (select * from products,insertedwhere inserted.productid=products.proudctidbegin print ’Fk violation on products’ rollback returnend--------------------------------------------------------------------------------------------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..........

The cursor contains following five ’jargons’

1....Declare2....Open3....Fetch4....Close5....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

// The scroll keyword is used to move the cursor up and down...declare cur cursor scroll for select c_id,title,author,publisher from sen_catlog

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;

Note: When closing the cursor, it destroies the result set.....-------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Page 185: Query

Query - Page #25

Note: It destroies the cursor [ like dropping tables ] -------------------------------------------------------------------------------------------------

Example with procedure:-

create procedure sen_cur_pro asdeclare cur cursor scrollforselect * from sen_catlogopen curfetch next from curwhile(@@fetch_status=0)begin fetch next from curendclose curdeallocate cur

exec sen_cur_pro;

Note: @@fetch_status is system defined global variable which is automatically set to 0 whichindicates for successful fetch...------------------------------------------------------------------------------------------------1-02-2002:

Application of Cursors:

Create procedure sen_cpro asdeclare @tid varchar(20),@title varchar(20),@price floatdeclare cur cursor scrollforselect title_id,title,price from titlesopen curfetch next from cur into @tid,@title,@pricewhile(@@fetch_status=0)begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@priceendclose curdeallocate cur

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??????

create procedure sen_publisher_books asset nocount ondeclare @pid varchar(20),@pname varchar(20)declare @tid varchar(20),@title varchar(20),@price floatdeclare @n intdeclare cur cursor scrollforselect pub_id,pub_name from publishersopen curfetch next from cur into @pid,@pnamewhile(@@fetch_status=0)begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid

Page 186: Query

Query - Page #26

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,@pnameendclose curdeallocate cur exec sen_publisher_books --------------------------------------------------------------------------------------------------------------2-Feb-2002:

Indexing: It is a sorting process to reduce the searching process time....

Syntax:

Create { nonClustered } index index_nameon table_name(field_name)

Default is Clustered indexing................-------------------------------------------------------------------------------------------------NonClustered:

create nonclustered index emp_enoon emp(eno)

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 orit 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:

create clustered index emp_enoon emp(eno)

The table itself will be sorted on a field name

-----------------------------------------------------------------------------------------------Note: The clustered index points the page...but the nonclustered index points the exact match ofrecord...

1...The Clusterd index is efficiant for duplicte records ( Foreign key)2...The nonClustered index is efficient for unique records (primary key), for the primary key creation the SQL server creates Clusterd index, it is our responsiblity to give nonClusterd index when creating the primary key......------------------------------------------------------------------------------------------------Note: One Clustered index is allowed for a table, but as many nonClustered index is allowed for a table------------------------------------------------------------------------------------------------

Page 187: Query

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 keeptrack of so many members and transactions,which are currently maintained in registers. The chieflibrarian approaches you to seek help for designing a computerized system. All members in thelibrary are given two member cards and one book is leased for each card. The membership fee foreach member is Rs 500. One time payment,refundable on relinquishing of the cards.Both books andmegazines are leased to the members.A book lent to a member can be with him for 15 days at mostand an extension of another 15 days is given to the member for that particular book if that bookis brought for renewal on the 15 th day after it is lent.The same member is not allowed to havethe book for another 15 days after it is returned.Magazines are lent only for 4 days and noextension is allowed and there is no restriction for lending the magazine to the same member,as isthe 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 particularmagazine 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 bookthat is there in the library. One copy of each book is designated as reference and it is not lentto 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);

Create Table sen_books( b_id varchar(10) constraint sb_pk primary key, c_id varchar(10) constraint sb_fk1 references sen_catlog(c_id), status varchar(10));

Create Table sen_member( m_id varchar(10) constraint sm_pk primary key, mname varchar(20) not null, address varchar(20),);

Create Table sen_cards( card_id varchar(10) constraint sen_cpk2 primary key, m_id varchar(10) constraint sen_cfk3 references sen_member(m_id));

Create Table sen_transaction( trans_id varchar(10) constraint sen_ctpk1 primary key, b_id varchar(10) constraint sen_ctfk1 references sen_books(b_id), card_id varchar(10) constraint sen_ctfk2 references sen_cards(card_id), tdate datetime not null, rdate datetime, ex_bit bit,);

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);

Page 188: Query

Query - Page #2

select * from sen_catlog;

insert into sen_books values (’B001’,’CB001’,’issue’);insert into sen_books values (’B002’,’CB001’,’issue’);insert into sen_books values (’B003’,’CB001’,’reference’);insert into sen_books values (’B004’,’CB002’,’issue’);insert into sen_books values (’B005’,’CB002’,’issue’);insert into sen_books values (’B006’,’CB002’,’Reference’);insert into sen_books values (’B007’,’CB003’,’issue’);insert into sen_books values (’B008’,’CB003’,’Reference’);

select * from sen_books;

insert into sen_member values(’M001’,’senthil’,’Drive square,London’);insert into sen_member values(’M002’,’Ashiwarya’,’West valley,sidney’);insert into sen_member values(’M003’,’kumar’,’Eiffle Tower, Paris’);

select * from sen_member;

insert into sen_cards values(’C001’,’M001’);insert into sen_cards values(’C002’,’M001’);insert into sen_cards values(’C003’,’M002’);insert into sen_cards values(’C004’,’M002’);insert into sen_cards values(’C005’,’M003’);

select * from sen_cards;

insert into sen_transaction values (’T001’,’B001’,’C001’,’12-10-2000’,null,null);insert into sen_transaction values (’T002’,’B002’,’C002’,’11-11-2000’,’11-25-2000’,null);insert into sen_transaction values (’T003’,’B004’,’C004’,’10-10-2000’,’10-25-2000’,1);insert into sen_transaction values (’T004’,’B004’,’C004’,’09-27-2000’,’10-10-2000’,0);insert into sen_transaction values (’T006’,’B002’,’C003’,’01-28-2000’,null,0);insert into sen_transaction values (’T007’,’B004’,’C002’,’01-28-2000’,’02-10-2000’,0);insert into sen_transaction values (’T008’,’B005’,’C005’,’01-28-2000’,null,0);

select * from sen_catlog;select * from sen_books;select * from sen_member;select * from sen_cards;select * from sen_transaction;

set nocount on --------------------------------------------------------------------------------------------------------------1. For each book you will have to generate the members to whom copies of it have been lent....

create procedure sen_books_issue as declare @n int declare @i int declare @b varchar(10) declare @c varchar(10) declare @t_title varchar(20) declare @t_bid varchar(10) declare @t_name varchar(20) declare @t_card varchar(20) select @n=count(b_id) from sen_transaction where rdate is null; if @n=0 print ’No books found’ else begin select b_id,card_id into #temp from sen_transaction where rdate is null 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

Page 189: Query

Query - Page #3

end end

exec sen_books_issue --------------------------------------------------------------------------------------------------------------2.Generate a report which displays all the books. You will have to include all the relevant information in the report

create procedure sen_books_details asdeclare @c varchar(10)declare @n intdeclare @i int select c_id into #temp from sen_catlog; select @n=count(c_id) from #temp if(@n=0) print ’No books in the catlog’ else begin select @i=1 while(@i<=@n) begin select top 1 @c=c_id from #temp select @c,title,author,publisher,price from sen_catlog where c_id=@c select b_id,status from sen_books where c_id=@c delete from #temp where c_id=@c; set @i = @i+1 end end

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...

Create procedure sen_book_delevered(@ddate datetime) asdeclare @n int declare @i intdeclare @b varchar(10)declare @c varchar(10)declare @r datetimedeclare @t_title varchar(20)declare @t_bid varchar(10)declare @t_name varchar(20)declare @t_card varchar(20)declare @message varchar(20)

select @n=count(b_id)from sen_transaction where tdate=@ddateif(@n=0) print ’No one book has been delivered on that day’else begin select b_id,card_id,rdate into #temp from sen_transaction where tdate=@ddate select @i = 1 while(@i<=@n) begin select top 1 @b=b_id,@c=card_id,@r=rdate 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

if(@r is null) set @message=’Not Returned’ else set @message=’Returned’ print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid + " " + @message end end 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

Page 190: Query

Query - Page #4

been over and has not yet been returned....

declare @dday datetime SELECT @dday=DATEADD(day, -15, getdate()) print @dday

Create procedure sen_overdue_books(@date datetime) asdeclare @n int declare @i intdeclare @b varchar(10)declare @c varchar(10)declare @t_title varchar(20)declare @t_bid varchar(10)declare @t_name varchar(20)declare @t_card varchar(20)declare @message varchar(20)declare @dday datetime

select @dday=DATEADD(day,-15,@date) select @n=count(b_id)from sen_transaction where rdate is null and tdate<@ddayif(@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 exec sen_overdue_books @date=’2000-02-25’

-------------------------------------------------------------------------------------------------

Page 191: Query

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 keeptrack of so many members and transactions,which are currently maintained in registers. The chieflibrarian approaches you to seek help for designing a computerized system. All members in thelibrary are given two member cards and one book is leased for each card. The membership fee foreach member is Rs 500. One time payment,refundable on relinquishing of the cards.Both books andmegazines are leased to the members.A book lent to a member can be with him for 15 days at mostand an extension of another 15 days is given to the member for that particular book if that bookis brought for renewal on the 15 th day after it is lent.The same member is not allowed to havethe book for another 15 days after it is returned.Magazines are lent only for 4 days and noextension is allowed and there is no restriction for lending the magazine to the same member,as isthe 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 particularmagazine 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 bookthat is there in the library. One copy of each book is designated as reference and it is not lentto 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);

Create Table sen_books( b_id varchar(10) constraint sb_pk primary key, c_id varchar(10) constraint sb_fk1 references sen_catlog(c_id), status varchar(10));

Create Table sen_member( m_id varchar(10) constraint sm_pk primary key, mname varchar(20) not null, address varchar(20),);

Create Table sen_cards( card_id varchar(10) constraint sen_cpk2 primary key, m_id varchar(10) constraint sen_cfk3 references sen_member(m_id));

Create Table sen_transaction( trans_id varchar(10) constraint sen_ctpk1 primary key, b_id varchar(10) constraint sen_ctfk1 references sen_books(b_id), card_id varchar(10) constraint sen_ctfk2 references sen_cards(card_id), tdate datetime not null, rdate datetime, ex_bit bit,);

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);

Page 192: Query

Query - Page #2

select * from sen_catlog;

insert into sen_books values (’B001’,’CB001’,’issue’);insert into sen_books values (’B002’,’CB001’,’issue’);insert into sen_books values (’B003’,’CB001’,’reference’);insert into sen_books values (’B004’,’CB002’,’issue’);insert into sen_books values (’B005’,’CB002’,’issue’);insert into sen_books values (’B006’,’CB002’,’Reference’);insert into sen_books values (’B007’,’CB003’,’issue’);insert into sen_books values (’B008’,’CB003’,’Reference’);

select * from sen_books;

insert into sen_member values(’M001’,’senthil’,’Drive square,London’);insert into sen_member values(’M002’,’Ashiwarya’,’West valley,sidney’);insert into sen_member values(’M003’,’kumar’,’Eiffle Tower, Paris’);

select * from sen_member;

insert into sen_cards values(’C001’,’M001’);insert into sen_cards values(’C002’,’M001’);insert into sen_cards values(’C003’,’M002’);insert into sen_cards values(’C004’,’M002’);insert into sen_cards values(’C005’,’M003’);

select * from sen_cards;

insert into sen_transaction values (’T001’,’B001’,’C001’,’12-10-2000’,null,null);insert into sen_transaction values (’T002’,’B002’,’C002’,’11-11-2000’,’11-25-2000’,null);insert into sen_transaction values (’T003’,’B004’,’C004’,’10-10-2000’,’10-25-2000’,1);insert into sen_transaction values (’T004’,’B004’,’C004’,’09-27-2000’,’10-10-2000’,0);insert into sen_transaction values (’T006’,’B002’,’C003’,’01-28-2000’,null,0);insert into sen_transaction values (’T007’,’B004’,’C002’,’01-28-2000’,’02-10-2000’,0);insert into sen_transaction values (’T008’,’B005’,’C005’,’01-28-2000’,null,0);

select * from sen_catlog;select * from sen_books;select * from sen_member;select * from sen_cards;select * from sen_transaction;

set nocount on --------------------------------------------------------------------------------------------------------------1. For each book you will have to generate the members to whom copies of it have been lent....

create procedure sen_books_issue as declare @n int declare @i int declare @b varchar(10) declare @c varchar(10) declare @t_title varchar(20) declare @t_bid varchar(10) declare @t_name varchar(20) declare @t_card varchar(20) select @n=count(b_id) from sen_transaction where rdate is null; if @n=0 print ’No books found’ else begin select b_id,card_id into #temp from sen_transaction where rdate is null 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

Page 193: Query

Query - Page #3

end end

exec sen_books_issue --------------------------------------------------------------------------------------------------------------2.Generate a report which displays all the books. You will have to include all the relevant information in the report

create procedure sen_books_details asdeclare @c varchar(10)declare @n intdeclare @i int select c_id into #temp from sen_catlog; select @n=count(c_id) from #temp if(@n=0) print ’No books in the catlog’ else begin select @i=1 while(@i<=@n) begin select top 1 @c=c_id from #temp select @c,title,author,publisher,price from sen_catlog where c_id=@c select b_id,status from sen_books where c_id=@c delete from #temp where c_id=@c; set @i = @i+1 end end

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...

Create procedure sen_book_delevered(@ddate datetime) asdeclare @n int declare @i intdeclare @b varchar(10)declare @c varchar(10)declare @r datetimedeclare @t_title varchar(20)declare @t_bid varchar(10)declare @t_name varchar(20)declare @t_card varchar(20)declare @message varchar(20)

select @n=count(b_id)from sen_transaction where tdate=@ddateif(@n=0) print ’No one book has been delivered on that day’else begin select b_id,card_id,rdate into #temp from sen_transaction where tdate=@ddate select @i = 1 while(@i<=@n) begin select top 1 @b=b_id,@c=card_id,@r=rdate 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

if(@r is null) set @message=’Not Returned’ else set @message=’Returned’ print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid + " " + @message end end 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

Page 194: Query

Query - Page #4

been over and has not yet been returned....

declare @dday datetime SELECT @dday=DATEADD(day, -15, getdate()) print @dday

Create procedure sen_overdue_books(@date datetime) asdeclare @n int declare @i intdeclare @b varchar(10)declare @c varchar(10)declare @t_title varchar(20)declare @t_bid varchar(10)declare @t_name varchar(20)declare @t_card varchar(20)declare @message varchar(20)declare @dday datetime

select @dday=DATEADD(day,-15,@date) select @n=count(b_id)from sen_transaction where rdate is null and tdate<@ddayif(@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 exec sen_overdue_books @date=’2000-02-25’

-------------------------------------------------------------------------------------------------

Page 195: Query

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;

2.) Summarise the total sales for each publisher

select pub_id,sum(ytd_sales) from titles group by pub_id;

3.) For an annual report, display the publisher_id, title_id,price and total_sales while showing the average price and total sales for each publisher .

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.

select title,datename(mm,pubdate) from titles;

5.)Display the names of books whose prices are greater than $20 and lesser than $25 select title,price from titles where price>20 and price<25;

6.)Display the total_sales made in each category , category wise

select type,sum(ytd_sales) 'Total Sales' from titles group by type;

7.)Display the numeric part of every title_id select substring(title_id,3,4) 'Numeric Part Of Title Id' from titles; 8.)Calculate the average price of different types of cooking books

select type,avg(price) 'Average Price' from titles group by type having type like '%cook%';

(or)

select type,avg(price) 'Average Price' from titles where type like '%cook%' group by type;

9.)Find out how many stores have placed orders

select count(distinct(stor_id)) from sales;

10.)Find out the average advance paid for a psychology book select avg(advance)'Avg Advance Paid for Psychology Book' from titles group by type having type = 'psychology';

(or)

select avg(advance) 'Total Sales'

Page 196: Query

Query - Page #2

from titles where type = ’psychology’;

11.) Find out the average advance and sum of total_sales for each type of book

select type,avg(advance) ’Avg Advance’ , sum(ytd_sales) ’Total Sales’ from titles group by type;

12.) Find the name and title of the most expensive book select type,price from titles where price = ( select max(price) from titles ); 13.)List all the books where advance is null

select * from titles where advance is null;

14.)How many authors have written more than one book?

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)

select au_fname from authors where au_id in ( select au_id from titleauthor group by au_id having count(au_id)>1);

Page 197: Query

Query - Page #1

---------------------------------------------------------------------------------------------

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:

create table sen_vehicles ( vech_num varchar(15), type varchar(20), mileage tinyint, model int, company_name varchar(20) ); /* 2. Alter the table to set vech_num as the primary key */

Ans:

Alter table sen_vehicles Alter column vech_num varchar(20) not null; Alter table sen_vehicles Add constraint sen_pk primary key (vech_num);

/* 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: Alter table sen_vehicles Add contractor_id varchar(20) constraint fk foreign key references 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 'fk'.

/* 4. Create a table named contractors and have the fields contractor_id,contractor_name, address, phone and city */

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: Alter table sen_contractor add default 'cbe' for city;

Insert into sen_contractor values('C100','Senthil','3 Zip Drive',26255,default);

select * from sen_contractor;

Delete sen_contractor where phone=0428826255;

/* 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: Alter table sen_contractor Add constraint sen_ck check(datalength(phone)>=6);

If some values are not matching the check constraint in the phone field already,

Page 198: Query

Query - Page #2

it will flash the error.......

we have to use the following syntax......‘ Alter table sen_contractor with nocheck Add constraint sen_ck check(datalength(phone)>=6);

Insert into sen_contractor values(111,’Senthil’,’3 Zip Drive’,142567,default);

/* 7. Add a constraint to check that the phone number entered is unique */

Ans: Alter table sen_contractor Add constraint sen_pchk unique(phone);

/* 8. Change the datatype of the field contractor id to integer */

Ans: Alter table sen_contractor Alter column contractor_id int;

/* 9. Insert some records into the table */

Ans: Insert into sen_contractor values(123,’senthil’,’2nd street’,123456,’T.gode’);

/* 10. Change the datatype of the contractor_id field to identity */

Ans: // Alter table sen_contractor contractor_id ::= int Identity(1,1);

Create table sen_temp ( eno int identity(1,1), ename varchar(20), dept_id int );

/* 11. Insert some records and see how the value for the identity column is generated */

Ans: Insert into sen_temp values(’senthil’,10);

/* 12. Insert your own value for the identity column */

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.

Rules for Identity column: 1. When set identity_insert <TableName> on flag is true, we can insert our own values

set identity_insert sen_temp on;

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.

2.Provide column names explictily in insert command Insert into sen_temp(eno,ename,dept_id) values (100,’senthil’,20);

To Trurn-off this future.... set identity_insert <TableName> off; set identity_insert sen_temp off;

/* 13. Delete one record from the middle of the table and insert another record to see the

Page 199: Query

Query - Page #3

effect of the insert */

Ans:

select * from sen_temp;

Delete sen_temp where eno=1;

Insert into sen_temp values (’senthil’,20);

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'.

Alter table sen_contractor Add constraint sen_pkc primary key(contractor_id);

Error : Cannot define PRIMARY KEY constraint on nullable column in table 'sen_contractor'. Alter table sen_contractor Alter column contractor_id int not null; Alter table sen_contractor Add constraint sen_pkc primary key(contractor_id);

/* 15. Create a table to include driver details have driver_id as the primary key.Include other necessary fields. */

Ans:

Create table sen_driver ( driver_id int constraint senck primary key, dname varchar(20), Address varchar(20) ); /* 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 );

Alter Table sen_vehicle_allot Alter column driver_id int not null

Alter Table sen_vehicle_allot Alter column vech_num int not null

Alter table sen_vehicle_allot Add constraint senckd1 primary key ( driver_id,vech_num);

Another Method....

Create Table sen_vehicle_allot ( driver_id int, vech_num int, adate datetime, constraint senckd1 primary key (driver_id,vech_num); );

Note: The composite primary key can be made up of upto 16 fields....

Page 200: Query

Query - Page #4

/* 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 Insert into sen_vehicle_allot values(100,200,’10/10/2001’); Error: Violation of PRIMARY KEY constraint ’senckd1’. Cannot insert duplicate key in object ’sen_vehicle_allot’.The statement has been terminated.

Insert into sen_vehicle_allot values(200,200,’10/10/2001’);

//////////////////////////////////////////////////////////////////////////////////////////////////

Page 201: Query

Query - Page #1

----------------------------------------------------------------------------------------------

PRACTICE - 3----------------------------------------------------------------------------------------------

Page 202: Query

Query - Page #1

----------------------------------------------------------------------------------------------

PRACTICE - 3----------------------------------------------------------------------------------------------

1. Create the following table definitions :

Sailors (sid : char , sname : char , rating : integer , age : integer)

Boats ( bid : char , bname : char , color : char)

Reserves (sid : char , bid : char , days : date)

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 );

Create Table sen_boats ( bid varchar(20) constraint _sen_bpk primary key, bname varchar(20), color varchar(10) );

Create Table sen_Reserves ( sid varchar(10), bid varchar(20), days datetime, constraint sen_rfk1 foreign key(sid) references sen_sailors(sid), constraint sen_rfk2 foreign key(bid) references sen_boats(bid) );

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’); select sname from sen_sailors where sid in (select sid from sen_reserves where sid in (select bid from sen_boats where color=’red’) or sid in (select bid from sen_boats where color=’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 color like ’Green’)) and sid in(select sid from sen_reserves where bid in(select bid from sen_boats where color like ’Red’)) 3.) Find the names of sailors who have reserved a red boat.

Ans:

Page 203: Query

Query - Page #2

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 = ’red’;

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’));

5.) Find the sailor with the highest rating.

Ans: select sname from sen_sailors where rating=(select max(rating) from sen_sailors); 6.) Find the names of sailors who are older than the oldest sailor with a rating of 10.

Ans:

select sname from sen_sailors where age= ( select max(age) from sen_sailors group by rating having rating=10);

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’); select r.bid,count(r.sid) No_of_reservation from sen_boats b,sen_reserves r group by r.bid,b.bid,b.color having r.bid = b.bid and b.color=’red’;

9.) Find the sid of all sailors who have a rating of 10 or have reserved boat number 106.

Ans: select sname from sen_sailors where rating=10 or sid in ( select sid from sen_reserves where bid=’b106’); 10.) Find the names of sailors who have reserved boat number 103.

Ans: select s.sname from sen_sailors s,sen_reserves r where r.bid=’b103’ and r.sid = s.sid;

*************************************************************************************************

Page 204: Query

Query - Page #1

----------------------------------------------------------------------------------------------

PRACTICE - 5----------------------------------------------------------------------------------------------

Create Table sen_airmodels( model_id varchar(5) constraint sen_am_pk primary key, model_name varchar(20), cspeed integer, type varchar(3));

Create Table sen_flights( flight_no varchar(5), model_id varchar(5), start varchar(2), dest varchar(2), distance int, arrives numeric(5,2), departs numeric(5,2), constraint sen_fpk primary key(flight_no,model_id), constraint sen_ffk foreign key(model_id) references sen_airmodels(model_id));

Create Table sen_emp( eid varchar(5) constraint sen_epk primary key, ename varchar(20), salary int);

Create Table sen_certified( eid varchar(5), model_id varchar(5), constraint sen_cpk1 primary key(eid,model_id), constraint sen_cfk1 foreign key(eid) references sen_emp(eid), constraint sen_cfk2 foreign key(model_id) references sen_airmodels(model_id));................................................................................................sen_airmodels:model_id model_name cspeed type -------- -------------------- ----------- ---- A001 Boeing 900 TORA002 Sopwithcamel 500 VTLA003 Spitfire 700 VTLA004 Harrier 800 TORA005 Hawkers 900 TORA006 Stealth 600 VTL.................................................................................................sen_certified:eid model_id ----- -------- P001 A001P001 A002P001 A003P002 A002P002 A005P003 A003P004 A004P005 A001P005 A005.................................................................................................sen_flights:flight_no model_id start dest distance arrives departs --------- -------- ----- ---- ----------- ------- ------- FL001 A001 NY CA 3000 13.30 14.00FL001 A002 LA CA 3000 14.30 15.30FL001 A003 LA NY 3000 14.00 15.15

Page 205: Query

Query - Page #2

FL001 A004 LA ME 3000 8.30 9.30FL001 A005 NJ ME 3000 7.30 8.30FL002 A001 NY CA 2000 12.00 12.30FL002 A002 SA CA 2000 16.30 17.30FL002 A003 LA NY 3000 15.00 15.45.................................................................................................sen_emp:eid ename salary ----- -------------------- ----------- e007 Joeph 20000e008 Abraham 8000P001 Sam 10000P002 David 15000P003 Stepen 16000P004 Raj 12000P005 Thomas 12000P006 George 3000..................................................................................................

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.

select c.model_id,c.eid,a.cspeed from sen_certified c,sen_airmodels a where c.eid in ( select eid from sen_certified group by eid having count(eid)>2) and c.model_id = a.model_id;

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.

select c.eid,e.salary from sen_certified c,sen_emp e where c.model_id in ( select model_id from sen_airmodels where cspeed>700 ) and c.eid = e.eid; 4. Find the names of pilots certified for some Boeing aircraft.

select e.ename from sen_certified c,sen_emp e where c.model_id in ( select model_id from sen_airmodels where model_name = ’Boeing’) and c.eid = e.eid;

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.

select c.eid,c.model_id,f.flight_no,f.start,f.dest from sen_certified c,sen_flights f where c.eid in ( select eid from sen_emp where salary > 15000 and eid like ’P%’ ) and c.model_id = f.model_id;

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.

select ename from sen_emp where eid in ( select c.eid from sen_certified c,sen_airmodels a where c.eid in ( select eid from sen_certified where model_id in ( select model_id from sen_airmodels where cspeed > 800 and model_name !=’Boeing’ ) ) and c.model_id = a.model_id and a.model_name !=’Boeing’ ) and eid not in ( select c.eid from sen_certified c,sen_airmodels a where c.eid in ( select eid from sen_certified where model_id in ( select model_id from sen_airmodels where cspeed > 800 and model_name !=’Boeing’ ) ) and c.model_id = a.model_id and a.model_name =’Boeing’);

(or)

select eid from sen_emp where eid in (select c.eid from sen_certified c where exists ( select a.model_id from sen_airmodels a where a.cspeed>800 and a.model_name =’Boeing’ and a.model_id=c.model_id)) and eid not in (select c.eid from sen_certified c where exists (select a.model_id from sen_airmodels a where a.cspeed>800 and a.model_name !=’Boeing’ and a.model_id=c.model_id))

Page 206: Query

Query - Page #3

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.

select ename from sen_emp where eid in (select c.eid from sen_certified c,sen_airmodels a where c.eid in (select eid from sen_certified where model_id in (select model_id from sen_airmodels where model_name=’Boeing’)) and c.model_id=a.model_id and type !=’VTL’) and eid not in (select c.eid from sen_certified c,sen_airmodels a where c.eid in (select eid from sen_certified where model_id in (select model_id from sen_airmodels where model_name=’Boeing’)) and c.model_id=a.model_id and type =’VTL’);

(or)

select eid from sen_emp where eid in (select c.eid from sen_certified c where exists ( select a.model_id from sen_airmodels a where model_name=’Boeing’ and a.model_id=c.model_id)) and eid in (select c.eid from sen_certified c where exists ( select a.model_id from sen_airmodels a where type !=’VTL’ and model_name!=’Boeing’ and a.model_id=c.model_id))

8. Compute the total salary of a pilot and the average salary of all employees excluding pilots.

select sum(e1.salary)/2 ’Total Sal for Pilots’,avg(e2.salary)’Avg sal for emp’ select * from sen_emp e1, sen_emp e2 where e1.eid like ’P%’ and e2.eid like ’e%’;

output:

eid ename salary eid ename salary ----- -------------------- ----------- ----- -------------------- ----------- P001 Sam 10000 e007 Joeph 20000P002 David 15000 e007 Joeph 20000P003 Stepen 16000 e007 Joeph 20000P004 Raj 12000 e007 Joeph 20000P005 Thomas 12000 e007 Joeph 20000P006 George 3000 e007 Joeph 20000P001 Sam 10000 e008 Abraham 8000P002 David 15000 e008 Abraham 8000P003 Stepen 16000 e008 Abraham 8000P004 Raj 12000 e008 Abraham 8000P005 Thomas 12000 e008 Abraham 8000P006 George 3000 e008 Abraham 8000

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

select ename,salary from sen_emp where salary > (select avg(salary) from sen_emp where eid like ’P%’) and eid like ’e%’;

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.

select flight_no,model_id from sen_flights where (start=’LA’ and dest=’CA’) or ( start=’LA’ and dest=’NY’); select flight_no,model_id,start,dest from sen_flights where flight_no in ( select flight_no from sen_flights where start=’LA’ and dest=’CA’) and flight_no in (select flight_no from sen_flights where start=’LA’ and dest=’NY’) and ((start=’LA’ and dest=’CA’) or ( start=’LA’ and dest=’NY’));

select flight_no,model_id from sen_flights

Page 207: Query

Query - Page #4

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’)) *************************************************************************************************

Page 208: Query

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 au_lname,au_fname from authors where city = (select city from publishers where pub_name=’Algodata Infosystems’);

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: select title from titles where price> (select min(price) from titles where type=’trad_cook’ )

4.Find the names of publishers who have published business books.

Ans: select pub_name from publishers where pub_id in (select pub_id from titles where type=’business’);

select distinct p.pub_name from publishers p,titles t where p.pub_id = t.pub_id and t.type=’business’;

5.Find the names of authors who have written atleast one "Popular_comp" book type.

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=’popular_comp’));

select a.au_lname,a.au_fname from titleauthor ta,titles t,authors a where t.type=’popular_comp’ and t.title_id=ta.title_id and ta.au_id = a.au_id;

6.Find the states of the whose book is published by the pub_id 0877

Ans:

select distinct state from authors where au_id in (select au_id from titleauthor where title_id in (select title_id from titles where pub_id=’0877’));

select distinct a.state from titles t,titleauthor ta,authors a where t.pub_id=’0877’ and t.title_id = ta.title_id and ta.au_id = a.au_id;

7.Find the books that received an advance larger than the advance amount paid by "Algodata systems"

Ans:

select title from titles where advance >

Page 209: Query

Query - Page #2

(select max(advance) from titles where pub_id in (select pub_id from publishers where pub_name=’Algodata Infosystems’));

8.Find the names of the authors who live in a city in which no publisher is located.

Ans: select au_lname,au_fname from authors a where not exists (select city from publishers p where a.city=p.city)

select au_lname,au_fname from authors a where city not in (select city from publishers p where a.city=p.city)

select distinct a.au_lname,a.au_fname from authors a,publishers p where a.city != p.city; // It is not correct

9. Find the titles of books published by any publisher located in a city that begins with the letter ’B’.

Ans:

select title from titles where pub_id in (select pub_id from publishers where city like ’B%’);

select t.title from titles t,publishers p where t.pub_id = p.pub_id and p.city like ’B%’;

10. Double the price of all books published by "New Moon Books".

Ans:

select title_id,title,price,2*price ’Double the Price’ from titles where pub_id = (select pub_id from publishers where pub_name =’New Moon Books’);

select t.title_id,t.title,t.price,2*t.price ’Doubled Price’ from titles t,publishers p where t.pub_id = p.pub_id and p.pub_name = ’New Moon Books’;

11. Find the titles and author names of books published by more than one publisher

Ans:

select pub_name from publishers where pub_id in (select pub_id from titles where title_id in (select ta1.title_id from titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id)); select pub_name from publishers where pub_id in (select pub_id from titles where title_id in (select title_id from titles t where t.title_id in (select ta.title_id from titleauthor ta where t.title_id=ta.title_id group by ta.title_id having count(*)>=2))) --and t.pub_id=p.pub_id // No need of comparing pub_id

select distinct p.pub_name from publishers p,titles t,titleauthor ta1,titleauthor ta2 where ta1.title_id = ta2.title_id and ta1.au_id <> ta2.au_id and ta1.title_id = t.title_id and t.pub_id = p.pub_id; 12. Find the books which have price greater than the average price of all books of its type

Ans: select title,pub_id from titles t where price > (select avg(price) from titles t1 group by type having t1.type=t.type)

***************************************************************************************************

Page 210: Query

Query - Page #1

----------------------------------------------------------------------------------------------

Test I Date: 9-01-2002----------------------------------------------------------------------------------------------

Page 211: Query

Query - Page #1

----------------------------------------------------------------------------------------------

Test II ----------------------------------------------------------------------------------------------

Specification:

Note: 1) No table level constraints should be defined and all integrity constraints have to beenforced using triggers. 2) Reports are to be generated using cursors.

Software Requiremet Specification:

A movie production company needs to record information about movies that they produce includingall 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 thedetails.

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.

’Integrity constraints that have to be enforced:’ 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.

’Business logics to be implemented:’ 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 ---------- ---------- --------

Page 212: Query

Query - Page #2

---------- -------- ---------- -------- ---------- --------

2) Display a report of total collections for each theatre datewise

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

-------------------------------------------------------------------------------------------------

Create Table sen_movie( m_id varchar(20), m_name varchar(20), d_id varchar(20), s_id varchar(20)); Create Table sen_director( d_id varchar(20), d_name varchar(20),);

Create Table sen_actor( a_id varchar(20), a_name varchar(20));

Create Table sen_acting( m_id varchar(20), a_id varchar(20), p_amt float, ins_id int);

Create Table sen_installment( ins_id int, amt float);

Create Table sen_studio( s_id varchar(20), s_name varchar(20), loc varchar(20));

Create Table sen_theatre( t_id varchar(20), t_name varchar(20), loc varchar(20));

Create Table sen_screening( t_id varchar(20), m_id varchar(20), sdate datetime);

Create Table sen_collection

Page 213: Query

Query - Page #3

( t_id varchar(20), tdate datetime, amt float)

-------------------------------------------------------------------------------------------------Director---Movie [One to Many]Movie---Actor [Many to Many] so Acting table is usedMovie---studio [one to many]Movie--Theatre [Many to Many] so screening table is usedCollection table is used for calculating day to day collections of theatere no need ofconsidering films is running in the theatreInstallment table is used to store the installment amounts for an actor-------------------------------------------------------------------------------------------------

Triggers:

//// Primary key Trigger for Sen_movie Table //////

Create trigger sen_movie_insert on sen_moviefor insert asdeclare @n intselect @n=count(*) from inserted,sen_movie where inserted.m_id=sen_movie.m_idif(@n>1)begin print "Primary key violation:Duplicate m_id not allowed" rollbackend

insert into sen_movie values (’M001’,’KdalFlowers’,’D001’,’S001’);insert into sen_movie values (’M002’,’Dhil’,’D001’,’S002’);insert into sen_movie values (’M003’,’New Kings’,’D002’,’S001’);

select * from sen_movie

------------------------------------------------------------------------------------------------//// Update Trigger for Sen_movie Table //////create trigger sen_movie_update on sen_moviefor update asif(update(m_id))begin print ’coud not updated,primary key are not allowed to update’ rollback returnend

update sen_movie set m_id=’M005’ where m_id=’M003’

------------------------------------------------------------------------------------------------insert into sen_director values(’D001’,’BalaChandar’); insert into sen_director values(’D002’,’BharathiRaja’);

select * from sen_director

------------------------------------------------------------------------------------------------

//// Primary key Trigger for Sen_Actor Table //////

Create trigger sen_actor_insert on sen_actorfor insert asdeclare @n intselect @n=count(*) from inserted,sen_actor where inserted.a_id=sen_actor.a_idif(@n>1)begin print "Primary key violation:Duplicate a_id not allowed"

Page 214: Query

Query - Page #4

rollbackend

insert into sen_actor values(’A001’,’Kamal’);insert into sen_actor values(’A002’,’Ajith’);insert into sen_actor values(’A003’,’Senthil’);

select * from sen_actor;------------------------------------------------------------------------------------------------//// Update Trigger for Sen_actor Table //////create trigger sen_actor_update on sen_actorfor update asif(update(a_id))begin print ’coud not updated,primary key are not allowed to update’ rollback returnend

update sen_actor set a_id=’A005’ where a_id=’A001’

------------------------------------------------------------------------------------------------// Foreign key Trigger for sen_acting Table

create trigger sen_acting_inserton sen_actingfor insertasdeclare @n intselect @n=count(*) from sen_acting a,inserted i where i.m_id=a.m_id and i.a_id=a.a_idif(@n>1)begin print ’Primary key violation:Duplicate m_id and a_id combination not allowed’ rollback returnendelsebegin if not exists (select * from inserted i,sen_actor a where i.a_id=a.a_id) begin print ’invalid actor: a_id not found’ rollback return end else begin if not exists (select * from inserted i,sen_movie m where i.m_id=m.m_id) begin print ’invalid movie:m_id not found’ rollback return end else print ’Successfully inserted’ endend

insert into sen_acting values (’M001’,’A001’,50000,1);insert into sen_acting values (’M001’,’A003’,75000,2);insert into sen_acting values (’M002’,’A002’,65000,3);insert into sen_acting values (’M003’,’A003’,60000,4);

select * from sen_acting

delete from sen_acting;-------------------------------------------------------------------------------------------------

insert into sen_studio values(’S001’,’Sakthi’,’Tambaram’);insert into sen_studio values(’S002’,’New Moon’,’Gindy’);

select * from sen_studio;

Page 215: Query

Query - Page #5

------------------------------------------------------------------------------------------------

insert into sen_theatre values (’T001’,’Sarasvathi’,’Peruma palaya’);insert into sen_theatre values (’T002’,’Kathikeyan’,’Tiruchengode’);insert into sen_theatre values (’T003’,’Tirumalai’,’Peruma palaya’);insert into sen_theatre values (’T004’,’Gokul’,’Tiruchengode’);

select * from sen_theatre

-------------------------------------------------------------------------------------------------

insert into sen_screening values (’T001’,’M001’,’01-15-2002’);insert into sen_screening values (’T001’,’M002’,’01-25-2002’);insert into sen_screening values (’T002’,’M001’,’01-15-2002’);insert into sen_screening values (’T002’,’M003’,’01-30-2002’);insert into sen_screening values (’T003’,’M002’,’01-15-2002’);insert into sen_screening values (’T003’,’M001’,’01-20-2002’);insert into sen_screening values (’T004’,’M001’,’01-01-2002’);

select * from sen_screening-------------------------------------------------------------------------------------------------

insert into sen_collection values (’T001’,’01-15-2002’,12500);insert into sen_collection values (’T001’,’01-16-2002’,14600);insert into sen_collection values (’T001’,’01-17-2002’,18500);insert into sen_collection values (’T001’,’01-19-2002’,15000);insert into sen_collection values (’T001’,’01-20-2002’,12000);insert into sen_collection values (’T001’,’01-25-2002’,12500);insert into sen_collection values (’T001’,’01-26-2002’,20000);insert into sen_collection values (’T002’,’01-15-2002’,7800);insert into sen_collection values (’T002’,’01-16-2002’,9560);insert into sen_collection values (’T002’,’01-17-2002’,11500);insert into sen_collection values (’T003’,’01-15-2002’,4500);insert into sen_collection values (’T003’,’01-16-2002’,6700);insert into sen_collection values (’T003’,’01-17-2002’,3500);insert into sen_collection values (’T004’,’01-15-2002’,22500);insert into sen_collection values (’T004’,’01-16-2002’,27800);

select * from sen_collection ------------------------------------------------------------------------------------------------// Cascade Deletion Trigger...for Sen_Theatre Table.......

Create trigger sen_theatre_deleteon sen_theatrefor deleteasdeclare @i varchar(20)select @i=t_id from deleteddelete from sen_collection where t_id = @i

delete from sen_theatre where t_id=’T001’;------------------------------------------------------------------------------------------------// Trigger for Installment Checking...................................

create trigger sen_installment_inserton sen_installmentfor insertasdeclare @n intdeclare @pamt floatdeclare @amt floatselect @n=count(*) from sen_installment inst ,inserted i where inst.ins_id=i.ins_id

if(@n>3)begin print ’Invalid installment : Only 3 installment is allowed....’ rollback returnend

if(@n=0)begin select @pamt=act.p_amt from sen_acting act,inserted i where act.ins_id=i.ins_id

Page 216: Query

Query - Page #6

select @amt=amt from inserted if(@amt>@pamt) begin print ’Error:Advance amount is greater than the promise amount’ rollback return endend

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 endend insert into sen_installment values(1,45000);insert into sen_installment values(1,2000);insert into sen_installment values(1,3000);insert into sen_installment values(1,45000); // Errorinsert into sen_installment values(2,50000);insert into sen_installment values(2,25000);insert into sen_installment values(2,25000); // Error amount exceeds the promise amountinsert into sen_installment values(3,60000);insert into sen_installment values(3,5000); insert into sen_installment values(4,20000);insert into sen_installment values(4,2000); insert into sen_installment values(4,20000);

select * from sen_installment--------------------------------------------------------------------------------------------------select * from sen_installmentselect * from sen_actingselect * from sen_movie;select * from sen_director;select * from sen_actor;select * from sen_acting;select * from sen_studio;select * from sen_screening;select * from sen_theatre;select * from sen_collection;select * from sen_installment-------------------------------------------------------------------------------------------------*************************************************************************************************************************************’REPORTS’*****************************************************************************************************************************************************-------------------------------------------------------------------------------------------------create procedure movie_payment asset nocount ondeclare @mid varchar(20),@mname varchar(20)declare @aid varchar(20),@aname varchar(20),@pamount floatdeclare @i varchar(20)declare @total floatselect @total=0print "Movie Name "+"Actor Name "+"Promise Amount"print "------------------------------------------------------------------------------"declare mcur cursor scrollforselect m_id,m_name from sen_movieopen mcurfetch next from mcur into @mid,@mnamewhile(@@fetch_status=0)begin print @mname declare acur cursor scroll for select act.a_id,a.a_name,act.p_amt from sen_acting act,sen_actor a where act.m_id=@mid and a.a_id=act.a_id open acur

Page 217: Query

Query - Page #7

fetch next from acur into @i,@aname,@pamount while(@@fetch_status=0) begin print " " + @aname + " " + convert(varchar,@pamount) fetch next from acur into @i,@aname,@pamount select @total = @total + @pamount end print "----------------------------------------------------------------------" print " Total=" + convert(varchar,@total) print "----------------------------------------------------------------------" select @total=0 close acur deallocate acurfetch next from mcur into @mid,@mnameendclose mcurdeallocate mcur

exec movie_payment drop procedure movie_payment-------------------------------------------------------------------------------------------------create procedure theatre_amount asset nocount ondeclare @tid varchar(20),@tname varchar(20)declare @collection floatdeclare @ddate datetimedeclare @total floatselect @total=0print "TheatreName "+"Date "+"Amount"print "----------------------------------------------------------------"declare tcur cursor scrollforselect distinct c.t_id,t.t_name from sen_collection c,sen_theatre twhere t.t_id=c.t_idopen tcurfetch next from tcur into @tid,@tnamewhile(@@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,@collection) 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=0fetch next from tcur into @tid,@tnameendclose tcurdeallocate tcur

exec theatre_amount

drop procedure theatre_amount ------------------------------------------------------------------------------------------------create procedure sen_movie_details asset nocount ondeclare @mid varchar(20),@mname varchar(20)declare @sname varchar(20),@location varchar(20)declare @tname varchar(20)declare @sdate datetimedeclare @sid varchar(20)

Page 218: Query

Query - Page #8

print "MovieName "+"Studio "+"Location "+"TheatreName "+"ReleaseDate"print "-----------------------------------------------------------------------------------"declare mcur cursor scrollforselect m.m_id,m.m_name,s.s_name,s.loc from sen_movie m,sen_studio swhere s.s_id=m.s_idopen mcur

fetch next from mcur into @mid,@mname,@sname,@locationwhile(@@fetch_status=0)begin print @mname +" "+@sname+" "+@location

declare acur cursor scroll for select distinct t.t_name,scr.sdate from sen_movie m,sen_theatre t,sen_screening scr where scr.m_id=@mid and t.t_id=scr.t_id open acur fetch next from acur into @tname,@sdate while(@@fetch_status=0) begin print " " +@tname + " " + convert(char,@sdate) fetch next from acur into @tname,@sdate end close acur deallocate acur print "-----------------------------------------------------------------------------------"fetch next from mcur into @mid,@mname,@sname,@locationend

close mcurdeallocate mcur

exec sen_movie_details

drop procedure sen_movie_details-------------------------------------------------------------------------------------------------select * from sen_actingselect * from sen_movie;select * from sen_director;select * from sen_actor;select * from sen_studio;select * from sen_screening;select * from sen_theatre;select * from sen_collection;select * from sen_installment

Page 219: Query

Query - Page #1

----------------------------------------------------------------------------------------------

Test III ----------------------------------------------------------------------------------------------

-- Two Wheeler Service Station-----------------------------Project Specification :

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.

Identify the entities and draw an E-R Diagram

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) );

Create Table sen_maintenance( m_id varchar(10) constraint sm_pk primary key, m_name varchar(20) );

Create Table sen_service_cost( v_id varchar(10) constraint sc_fk1 foreign key references sen_vehicle(v_id), m_id varchar(10) constraint sc_fk2 foreign key references sen_maintenance(m_id), cost float, constraint sc_pk primary key(v_id,m_id));

Create Table sen_servicing(

Page 220: Query

Query - Page #2

s_id varchar(10) constraint ss_pk primary key, j_id varchar(10) constraint ss_fk1 foreign key references sen_job_card(j_id), l_id varchar(10) constraint ss_fk2 foreign key references sen_labour(l_id), m_id varchar(10) constraint ss_fk3 foreign key references sen_maintenance(m_id), sdate datetime);

Create Table sen_replacement( s_id varchar(10) constraint sr_fk1 foreign key references sen_servicing(s_id), t_id varchar(10) constraint sr_fk2 foreign key references sen_stores(t_id), constraint sr_pk1 primary key(s_id,t_id));

-- 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));

Create Clustered index sen_labour_indexon sen_labour(sup_id)------------------------------------------------------------------------------------------

Create Table sen_stores( t_id varchar(10) constraint sst_pk primary key, tnmae varchar(30) not null, qih int, uprice float);

Create Table sen_job_card( j_id varchar(10) constraint sj_pk primary key, reg_no varchar(20) not null, v_id varchar(10) constraint sj_fk1 foreign key references sen_vehicle(v_id), lcharge float, -- labour charge kran int, -- kilometer ran sup_id varchar(10) constraint sj_fk2 foreign key references sen_labour(l_id), total_cost numeric(8,2), in_date datetime not null, exp_date datetime not null, d_date datetime, ready bit, cus_name varchar(20), phone varchar(20));------------------------------------------------------------------------------------------------create trigger sen_job_card_inserton sen_job_cardfor insert asdeclare @jid varchar(10)select @jid = j_id from insertedupdate sen_job_card set lcharge=0,total_cost=0 where j_id= @jid-------------------------------------------------------------------------------------------------create trigger sen_servicing_inserton sen_servicing for insertasdeclare @lid varchar(10)declare @jid varchar(10)declare @amount float

select @lid = l_id,@jid=j_id from inserted

if(@lid in (select l_id from sen_labour where sup_id =(select sup_id from sen_job_card where j_id=@jid)))begin

Page 221: Query

Query - Page #3

select @amount = sc.cost from sen_service_cost sc,sen_servicing s,sen_job_card c,inserted i where i.j_id=c.j_id and c.v_id = sc.v_id and i.m_id = sc.m_id update sen_job_card set lcharge= lcharge + @amount,total_cost=total_cost + @amount where j_id=@jid

endelsebegin print ’Invalid Labourd id under Supervisior id’ rollbackend----------------------------------------------------------------------------------------------------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)

insert into sen_labour values(’L001’,’Ravikumar’,’Salem’,’SP01’)insert into sen_labour values(’L002’,’Anjala’,’Tiruchengode’,’SP01’)insert into sen_labour values(’L003’,’Sudamani’,’Rasipuram’,’SP01’)insert into sen_labour values(’L004’,’Munian’,’Rasipuram’,’SP01’)insert into sen_labour values(’L005’,’Kurupan’,’kokkarayanpetti’,’SP01’)

insert into sen_labour values(’L006’,’Karuvayan’,’Salem’,’SP02’)insert into sen_labour values(’L007’,’Vellian’,’Tiruchengode’,’SP02’)insert into sen_labour values(’L008’,’Suppan’,’vellore’,’SP02’)insert into sen_labour values(’L009’,’Pandian’,’perumapalayam’,’SP02’)insert into sen_labour values(’L010’,’Murugan’,’Salem’,’SP02’)-------------------------------------------------------------------------------------------------insert into sen_stores values(’T001’,’GearBox’,12,1200)insert into sen_stores values(’T002’,’Alpa LightSet’,15,450)insert into sen_stores values(’T003’,’Engine Oil’,15,120)insert into sen_stores values(’T004’,’Silencer’,16,240)--------------------------------------------------------------------------------------------------insert into sen_job_card(j_id,reg_no,v_id,kran,sup_id,in_date,exp_date,ready,cus_name,phone)values(’J001’,’TN34-2725’,’V003’,1200,’SP02’,’03/26/2002’,’03/30/2002’,0,’Sukumar’,’04288-50255’)update sen_job_card set ready=1,d_date=null where j_id=’J001’

insert into sen_job_card(j_id,reg_no,v_id,kran,sup_id,in_date,exp_date,ready,cus_name,phone)values(’J002’,’TN28-0728’,’V001’,3000,’SP01’,’03/26/2002’,’03/26/2002’,0,’Nithiya’,’91427-4321’)

insert into sen_job_card(j_id,reg_no,v_id,kran,sup_id,in_date,exp_date,ready,cus_name,phone)values(’J003’,’TN32-1782’,’V004’,1245,’SP01’,’03/26/2002’,’03/26/2002’,0,’Elaiyappan’,’04288-226255’)

insert into sen_job_card(j_id,reg_no,v_id,kran,sup_id,in_date,exp_date,ready,cus_name,phone)values(’J004’,’TN47-9921’,’V003’,4303,’SP02’,’03/26/2002’,’03/26/2002’,0,’Ramesh’,’04287-61993’)

insert into sen_job_card(j_id,reg_no,v_id,kran,sup_id,in_date,exp_date,ready,cus_name,phone)values(’J005’,’TN28-3210’,’V002’,4303,’SP02’,’03/27/2002’,’03/27/2002’,0,’Santhosh’,’04245-54993’)------------------------------------------------------------------------------------------------insert into sen_servicing values(’S001’,’J001’,’L006’,’M001’,’03/26/2002’)insert into sen_servicing values(’S002’,’J001’,’L008’,’M003’,’03/26/2002’)

insert into sen_servicing values(’S003’,’J002’,’L001’,’M001’,’03/26/2002’)

insert into sen_servicing values(’S004’,’J003’,’L005’,’M001’,’03/26/2002’)insert into sen_servicing values(’S005’,’J003’,’L004’,’M002’,’03/26/2002’)insert into sen_servicing values(’S006’,’J003’,’L003’,’M003’,’03/26/2002’)

Page 222: Query

Query - Page #4

insert into sen_servicing values(’S007’,’J004’,’L006’,’M001’,’03/26/2002’)insert into sen_servicing values(’S008’,’J004’,’L007’,’M003’,’03/26/2002’)insert into sen_servicing values(’S009’,’J004’,’L008’,’M002’,’03/26/2002’)

insert into sen_servicing values(’S010’,’J005’,’L006’,’M001’,’03/27/2002’)insert into sen_servicing values(’S011’,’J005’,’L007’,’M002’,’03/27/2002’)

insert into sen_servicing values(’S012’,’J006’,’L005’,’M001’,’03/28/2002’)insert into sen_servicing values(’S013’,’J006’,’L004’,’M002’,’03/28/2002’)-------------------------------------------------------------------------------------------------insert into sen_replacement values(’S001’,’T003’)insert into sen_replacement values(’S002’,’T002’)

insert into sen_replacement values(’S004’,’T003’)insert into sen_replacement values(’S005’,’T004’)

insert into sen_replacement values(’S008’,’T004’)insert into sen_replacement values(’S011’,’T001’)-------------------------------------------------------------------------------------------------select * from sen_vehicleselect * from sen_maintenance

select * from sen_service_costselect * from sen_servicingselect * from sen_replacementselect * from sen_labourselect * from sen_storesselect * from sen_job_card

delete from sen_vehicle where v_id=’V005’ or v_id=’V006’---------------------------------------------------------------------------------------------------1.) You are required to display the total number of different types of vehicles that have come in for servicing on a particular dayAns:create procedure sen_service_come_particular_day(@cday datetime)asif(exists (select v.v_name ’Vehicle Type’,count(v.v_id) ’Nos’ from sen_vehicle v,sen_job_card c where c.v_id=v.v_id and c.in_date = @cday group by v.v_name ))begin select v.v_name ’Vehicle Type’,count(v.v_id) ’Nos’ from sen_vehicle v,sen_job_card c where c.v_id=v.v_id and c.in_date = @cday group by v.v_nameendelseprint ’No Records on that date’

exec sen_service_come_particular_day ’03/26/2002’--------------------------------------------------------------------------------------------------2.) At the end of each month you have to generate a report of the total number of vehicles of all types that a particular labourer has serviced. The same information has to be presented for all the supervisors who supervise the service of vehicles. The report should have the employee name, vehicle type and the total vehicles that he has serviced of that particular type.

Ans:create procedure sen_labour_report(@lid varchar(10),@date datetime)asset nocount onprint ’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 vwhere 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 andmonth(sdate)=month(@date) and year(sdate)=year(@date)group by l.lname,v.v_name

select l.lname ’Supervisior Name’, v.v_name ’Vehicle Type’,count(v.v_id) ’Nos’from sen_job_card c,sen_labour l,sen_vehicle vwhere c.sup_id=l.l_id and c.v_id=v.v_id andmonth(c.in_date)=month(@date) and year(c.in_date)=year(@date)group by l.lname,v.v_name

Page 223: Query

Query - Page #5

exec sen_labour_report ’L007’,’03/26/2002’---------------------------------------------------------------------------------------------------3.) On any date the details of Job Cards that have been raised have to be made availableAns:create procedure sen_job_card_details(@cdate datetime)asif(exists (select c.reg_no ’Reg No’,v.v_name ’Vehicle Type’,l.lname ’Supervisior Name’,left(convert(varchar,c.exp_date),11) ’Expected Delivery Date’ from sen_job_card c,sen_vehicle v,sen_labour l where c.v_id=v.v_id and c.sup_id=l.l_id and c.in_date=@cdate))begin select c.reg_no ’Reg No’,v.v_name ’Vehicle Type’,l.lname ’Supervisior Name’,left(convert(varchar,c.exp_date),11) ’Expected Delivery Date’ from sen_job_card c,sen_vehicle v,sen_labour l where c.v_id=v.v_id and c.sup_id=l.l_id and c.in_date=@cdateendelse print ’No job cards for that day’

exec sen_job_card_details ’03/27/2002’---------------------------------------------------------------------------------------------------4.) On any day a report of the vehicles that have come in for servicing on the previous day and have not been delivered to the customers has to be made availableAns:create procedure sen_previousday_not_delivered(@cdate datetime)asif(exists( select * from sen_job_card where in_date=convert(datetime,@cdate)-1 and d_date is null))beginselect distinct c.reg_no ’Reg No’,v.v_name ’Vehicle Type’,l.lname ’Supervisior Name’,status = case ready when 0 then ’Not Serviced’ when 1 then ’Serviced’ endfrom sen_job_card c,sen_vehicle v,sen_labour lwhere c.sup_id=l.l_id and c.v_id=v.v_id and c.in_date=convert(datetime,@cdate)-1 and c.d_date is nullendelse print ’No Vehicles are bending those came previous day’

exec sen_previousday_not_delivered ’03/27/2002’-----------------------------------------------------------------------------------------------------5.) For any vehicle the details of parts replaced/repaired have to be shown as a report to the customer along with the cost of the part(if replaced) and labour cost(if repaired/ replaced)Ans:create procedure sen_vehicle_service_details(@j_id varchar(10))asdeclare @reg_no varchar(20)declare @vid varchar(10)declare @vname varchar(20)declare @ltcost numeric(8,2)declare @tcost numeric(8,2)set nocount on

select @reg_no=reg_no,@vid=v_id from sen_job_card where j_id=@j_idselect @vname=v_name from sen_vehicle where v_id=@vid

print ’Reg-No : ’ + @reg_no + ’ Vehicle Type : ’ + @vname

print ’----------------------------------------------------------------------’print ’Labour Changes Summary’print ’----------------------------------------------------------------------’ select distinct m.m_name ’Maintenance Type’,sc.cost ’Labour Charge’ from sen_job_card c,sen_maintenance m,sen_service_cost sc,sen_servicing swhere 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

select @ltcost=sum(sc.cost)from sen_job_card c,sen_maintenance m,sen_service_cost sc,sen_servicing swhere 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 ’-----------------------------------------------------------------------’

Page 224: Query

Query - Page #6

select s.tnmae ’Tool Name’,s.uprice ’Price’from sen_stores s,sen_servicing ss,sen_replacement rwhere ss.j_id=@j_id and ss.s_id=r.s_id and r.t_id = s.t_id

print ’-----------------------------------------------------------------------’select @tcost=total_cost from sen_job_card where j_id=@j_idprint ’ Total Amount ’ + convert(varchar,@tcost)print ’-----------------------------------------------------------------------’

exec sen_vehicle_service_details ’J006’------------------------------------------------------------------------------------------------6.) At the end of all days a report has to be generated of the vehicles that have been promised for delivery on that day but could not be deliveredAns: create procedure sen_bending_promised_vehicle(@date datetime) as if(exists (select * from sen_job_card where exp_date-@date<=-1)) begin select c.reg_no ’Reg No’,v.v_name ’Vehicle Type’,left(convert(varchar,c.exp_date),11) ’Expected Delivery Date’ from sen_job_card c,sen_vehicle v where c.v_id = v.v_id and c.ready=0 and exp_date-@date <= -1 end else print ’No Bending vehicles’

exec sen_bending_promised_vehicle ’03/31/2002’------------------------------------------------------------------------------------------------7.) Display the details of the common maintenance types of all the vehiclesAns:

select v.v_name ’Vehicle Type’,m.m_name ’Maintenance Type’ from sen_vehicle v,sen_maintenance m,sen_service_cost c where v.v_id=c.v_id and c.m_id=m.m_id group by v.v_name,m.m_name

select m.m_name ’Maintenance Type’ from sen_vehicle v,sen_maintenance m,sen_service_cost c where v.v_id=c.v_id and c.m_id=m.m_id group by m.m_name having count(*)=4 ------------------------------------------------------------------------------------------------- 8.) Write a trigger that will update the QOH of the parts once a part is procured from the store for fitting into the vehicle(and) 9.) For each record that is inserted into the transaction table for each job card, a trigger has to fire, to keep a running total of the cost that has been incurred for that particular service. This detail has to be displayed on each insertAns:create trigger sen_replacement_inserton sen_replacementfor insertasdeclare @qty intdeclare @tid varchar(10)declare @price floatdeclare @jid varchar(10)declare @total numeric(8,2)select @qty=qih from inserted i,sen_stores s where s.t_id=i.t_id

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) + ’/.’endelsebegin print ’Unavailable qty in hand’ rollbackendinsert into sen_replacement values(’S012’,’T003’)

Page 225: Query

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 typeAns:create procedure sen_total_revenue(@date datetime)asdeclare @ltotal numeric(8,2)declare @ttotal numeric(8,2)declare @rev numeric(8,2)set nocount onprint ’Month ’ + convert(varchar,month(@date)) + ’ Year ’ + convert(varchar,year(@date))print ’----------------------------------------------------------------------’print ’Labour Charge Summary’print ’----------------------------------------------------------------------’

select distinct m.m_name ’Labour Type’,sum(sc.cost) ’Total Cost’ from sen_job_card c,sen_maintenance m,sen_service_cost sc,sen_servicing swhere 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 andmonth(c.in_date)= month(@date) andyear(c.in_date) = year(@date)group by m.m_name

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 swhere 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 andmonth(c.in_date)= month(@date) andyear(c.in_date) = year(@date)

select st.tnmae ’Tool Name’,sum(st.uprice)’Total Price’ from sen_job_card c,sen_servicing s,sen_replacement r,sen_stores stwhere c.j_id=s.j_id and s.s_id = r.s_id and r.t_id = st.t_id andmonth(s.sdate)=month(@date) and year(s.sdate)=year(@date)group by st.tnmae

select @ttotal = sum(st.uprice) from sen_job_card c,sen_servicing s,sen_replacement r,sen_stores stwhere c.j_id=s.j_id and s.s_id = r.s_id and r.t_id = st.t_id andmonth(s.sdate)=month(@date) and year(s.sdate)=year(@date)

print ’---------------------------------------------------------------------’print ’ Total Labour Charge is Rs ’ + convert(varchar,@ltotal) + ’/.’print ’ Total Tools Sale is Rs ’ + convert(varchar,@ttotal) + ’/.’select @rev=@ltotal+@ttotalprint ’ Total Revenue is Rs ’ + convert(varchar,@rev) + ’/.’print ’---------------------------------------------------------------------’

exec sen_total_revenue ’03/26/2002’--------------------------------------------------------------------------------------------------

Create Table sen_login( user_name varchar(20) constraint sen_login_pk primary key, uname varchar(30), password varchar(15) not null);

insert into sen_login values(’sen’,’Senthil’,’sen’);

select * from sen_login

delete sen_login where user_name=’senthil’

select * from sen_vehicleselect * from sen_maintenance

select * from sen_service_cost

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

Page 226: Query

Query - Page #8

where c.v_id = v.v_id and c.m_id=m.m_id

select * from sen_labour where sup_id is null

update sen_labour set sup_id=null where l_id=’SP02’

Page 227: Query

Query - Page #1

----------------------------------------------------------------------------------------------

Test IV ----------------------------------------------------------------------------------------------

create table sen_applicant( app_no varchar(10) constraint sen_app primary key, name varchar(20) not null, city varchar(10), address varchar(30))

insert into sen_applicant values(’A100’,’Senthil’,’Salem’,’T.gode’)insert into sen_applicant values(’A101’,’kum’,’Salem’,’T.gode’)insert into sen_applicant values(’A102’,’aravind’,’Salem’,’T.gode’)insert into sen_applicant values(’A103’,’rajesh’,’Salem’,’T.gode’)

create table sen_registeration( reg_no varchar(10) constraint sen_reg_pk4 primary key, app_no varchar(10), cid varchar(10) constraint sen_reg_fk references sen_course(cid), date datetime)

drop table sen_registeration

insert into sen_registeration values(’R100’,’A100’,’C100’,getdate())insert into sen_registeration values(’R102’,’A101’,’C100’,getdate())insert into sen_registeration values(’R101’,’A100’,’C101’,getdate())

create table sen_course( cid varchar(10) constraint sen_reg_pk primary key, cname varchar(20) not null, pre_req varchar(20), fee float, pid varchar(10) constraint sen_course_fk references sen_professor(pid))

insert into sen_course values(’C100’,’JAVA’,’BE’,120,’P100’)insert into sen_course values(’C101’,’C’,’BE’,500,’P101’)

create table sen_student( aid varchar (10) primary key, sid varchar(10) constraint sen_stu_uni unique, name varchar(20) not null, cid varchar(10) constraint sen_stu_fk references sen_course(cid), doj datetime)

insert into sen_student values(’AA100’,’A100’,’Senthil’,’C100’,getdate()) insert into sen_student values(’AA101’,’A101’,’kum’,’C100’,getdate())

create table sen_professor( pid varchar(10) primary key, name varchar(20) not null, city varchar(10), state varchar(20), phone varchar(15), dob datetime)

insert into sen_professor values(’P100’,’Suppan’,’Salme’,’sfsf’,’2424’,getdate()) insert into sen_professor values(’P101’,’Karuvayan’,’Salme’,’sfsf’,’2424’,getdate()) insert into sen_professor values(’P102’,’munion’,’bombauy’,’sfsf’,’2424’,getdate())

Page 228: Query

Query - Page #2

insert into sen_professor values(’P103’,’Vellian’,’Salme’,’sfsf’,’2424’,getdate())

select p1.name,p2.name from sen_professor p1,sen_professor p2 where p1.pid < p2.pid and p1.city=p2.city

create table sen_report( aid varchar(10) primary key, mark float,)

insert into sen_report values(’AA100’,80)insert into sen_report values(’AA101’,40)

select s.sid,s.name,c.cname from sen_student s,sen_course c where s.aid in( select aid from sen_report where grade=’First’) and s.cid=c.cid

create table sen_student( aid varchar (10) primary key, sid varchar(10) constraint sen_stu_uni unique, name varchar(20) not null, cid varchar(10) constraint sen_stu_fk references sen_course(cid), doj datetime)

insert into sen_student values(’AA100’,’A100’,’Senthil’,’C100’,getdate()) insert into sen_student values(’AA101’,’A101’,’kum’,’C100’,getdate())

create table sen_bill( bill_no varchar(10) primary key, date datetime, cid varchar(10), sid varchar(10), fine float)

insert into sen_bill values(’B100’,getdate(),’C100’,’A100’,null)insert into sen_bill values(’B101’,getdate(),’C101’,’A100’,20)insert into sen_bill values(’B102’,getdate(),’C100’,’A101’,null)

select sid,name from sen_student where sid not in ( select sid from sen_student where sid in ( select sid from sen_bill where fine is not null)) and sid in ( select sid from sen_student where sid in ( select sid from sen_bill where fine is null))

select sid from sen_student where sid not in ( select sid from sen_student where sid in ( select sid from sen_bill where fine is not null))

select b.cid,sum(c.fee) from sen_course c,sen_bill b where b.cid=c.cid group by b.cid select * from sen_applicant

select app_no,name from sen_applicant where app_no in( select app_no from sen_registeration group by app_no having count(*) >1)

select * from sen_registerationselect * from sen_student

select s.reg_no,s.app_no,s.cid from sen_registeration s where not exists ( select st.* from sen_student st where st.sid=s.app_no and st.cid=s.cid)

Page 229: Query

Query - Page #3

Page 230: Query

Query - Page #1

----------------------------------------------------------------------------------------------

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:-

1.) Insert: Primary key(c_id) Checking... 2.) Update: Ensure the primary key(c_id) should not be altered... 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:-

1.) Insert: Primary key(p_id) Checking... 2.) Update: Ensure the primary key(p_id) should not be altered... 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:-

1.) Insert: Primary key(o_id) Checking... Foreign key(c_id) checking in the customers table Foreign key(p_id) checking in the products table check the availability of the qty in the products table and store the current quantity in hand 2.) Update: Ensure the primary key(o_id) should not be altered... The updated qty will be taken an effect in respected entry of the products table -------------------------------------------------------------------------------------------------------------- create Table sen_customers( c_id int, cname varchar(20), address varchar(40));

create Table sen_products( p_id int, pname varchar(20), qty_hand int);

create Table sen_invoice( o_id int, c_id int, p_id int, qty int, idate datetime

Page 231: Query

Query - Page #2

);

select * from sen_invoiceselect * from sen_productsselect * from sen_customers--------------------------------------------------------------------------------------------------Create trigger sen_customers_insert on sen_customersfor insert asdeclare @n intselect @n=count(*) from inserted,sen_customers where inserted.c_id=sen_customers.c_idif(@n>1)begin print "Primary key violation:Duplicate c_id not allowed" rollbackend

insert into sen_customers values (101,’Ashiwarya’,’3 Sidney square end,Sidney’);----------------------------------------------------------------------------------------------------Create trigger sen_customers_update on sen_customersfor update asif(update(c_id))begin print ’Primary key c_id not allowed to change’ rollbackend

update sen_customers set c_id=101,cname=’kumarn’ where c_id=101-------------------------------------------------------------------------------------------------------------Create trigger sen_customers_delete on sen_customersfor delete asdeclare @n intdeclare @i intselect @i=c_id from deletedselect @n=count(*) from sen_invoice i,deleted d where i.c_id=d.c_idif(@n<>0)begin print ’Could not be deleted, c_id exists in the products table’ rollbackend

delete sen_customers where c_id=101;--------------------------------------------------------------------------------------------------------------Create trigger sen_products_insert on sen_productsfor insert asdeclare @n intselect @n=count(*) from inserted,sen_products where inserted.p_id=sen_products.p_idif(@n>1)begin print "Primary key violation:Duplicate p_id not allowed" rollbackend

insert into sen_products values(202,’Dream Flower’,25);-------------------------------------------------------------------------------------------------------------create trigger sen_products_update on sen_productsfor update asif(update(p_id))begin print ’Primary key p_id not allowed to change’ rollbackend

Page 232: Query

Query - Page #3

update sen_products set p_id=202 where p_id=205;-------------------------------------------------------------------------------------------------------------Create trigger sen_products_delete on sen_productsfor delete asdeclare @n intdeclare @i intselect @i=p_id from deletedselect @n=count(*) from sen_invoice i,deleted d where i.p_id=d.p_idif(@n<>0)begin print ’Could not be deleted, p_id exists in the products table’ rollbackend

delete sen_products where p_id=201;-------------------------------------------------------------------------------------------------------------create trigger sen_invoice_inserton sen_invoicefor insertasdeclare @n intdeclare @c intdeclare @i intselect @n=count(*) from sen_invoice inv,inserted i where inv.o_id=i.o_idif(@n>1)begin print ’Primary key violation:Duplicate o_id not allowed’ rollback returnendelsebegin if not exists (select * from inserted i,sen_customers c where i.c_id=c.c_id) begin print ’invalid customer: c_id not found’ rollback return end else begin if not exists (select * from inserted i,sen_products p where i.p_id=p.p_id) begin print ’invalid product:p_id not found’ rollback return end else begin select @c=(p.qty_hand-i.qty) from sen_products p,inserted i where i.p_id=p.p_id if(@c<0) begin print ’could not be inserted,qty exceeds the qty in hand’ rollback return end else begin select @i=p_id from inserted update sen_products set qty_hand =@c where p_id=@i print ’qty in hand updated successfully’ end end end end

insert into sen_invoice values(5,100,200,5,getdate());-------------------------------------------------------------------------------------------------------------create trigger sen_invoice_update on sen_invoicefor update asdeclare @old_qty int

Page 233: Query

Query - Page #4

declare @new_qty intdeclare @i intdeclare @c intif(update(o_id) or update(c_id) or update(p_id))begin print ’coud not updated,olny qty and date allowed to change’ rollback returnendelsebegin select @old_qty=qty,@i=p_id from deleted update sen_products set qty_hand=(qty_hand + @old_qty) where p_id=@i select @new_qty=qty from inserted select @c=(p.qty_hand-@new_qty) from sen_products p,inserted i where p.p_id=i.p_id if(@c<0) begin print ’could not be updated,qty exceeds the qty in hand’ rollback return end else begin select @i=p_id from inserted update sen_products set qty_hand =@c where p_id=@i print ’qty in hand updated successfully’ endend

update sen_invoice set qty=1 where o_id=1-----------------------------------------------------------------------------------------------------------

select * from sen_invoiceselect * from sen_productsselect * from sen_customers

Page 234: Query

Query - Page #1

----------------------------------------------------------------------------------------------

FLIGHT EXAMPLE----------------------------------------------------------------------------------------------

create table flight_master( f_num varchar(10) constraint fn_pkey primary key, route varchar(50), day_opt varchar(30), air_type varchar(15), arr_time varchar(30), dep_time varchar(30), f_class_seats int, f_class_fare float, b_class_seats int, b_class_fare float, e_class_seats int, e_class_fare float);

create table test_trans( f_num varchar(10) constraint ff_fkey foreign key (f_num) references flight_master( f_num), pnr int, pname varchar(20), age int, sex varchar(10), address varchar(30), date_of_travel datetime, class varchar(20), status varchar(20))

insert into flight_master values(’SA101’,’Singapore-to-Manila’,’16’,’B707’,’14:25’,’23:00’,5,6500.00,3,5200.00,3,4700.00)insert into flight_master values(’SA102’,’Singapore-to-Manila’,’16’,’A310’,’14:25’,’23:00’,5,6500.00,3,5200.00,3,4700.00)insert into flight_master values(’SA103’,’Singapore-to-Muscat’,’25’,’B707’,’15:25’,’24:00’,100,6500.00,150,5200.00,150,4700.00)insert into flight_master values(’SA104’,’Singapore-to-Dubai’,’34’,’A310’,’16:25’,’20:00’,100,6500.00,150,5200.00,150,4700.00)insert into flight_master values(’SA105’,’Singapore-to-KulaLumpur’,’17’,’A310’,’10:25’,’04:00’,100,6500.00,150,5200.00,150,4700.00)insert into flight_master values(’SA106’,’Singapore-to-Jakarta’,’26’,’B707’,’12:25’,’14:00’,100,6500.00,150,5200.00,150,4700.00)***************************************************************************** Reservation Procedure*************************************************************************************************

create procedure sen_reservation( @f_num varchar(10), @date varchar(20), @class varchar(20), @name varchar(20), @age int, @sex varchar(10), @address varchar(30), @wstatus int) as

declare @rec_num int declare @day_num intdeclare @c1 intdeclare @c2 intdeclare @day_opt varchar(20)declare @pnr_no intdeclare @flag int

select @flag=0

select @day_opt = day_opt from flight_master where f_num=@f_num

select @day_num = datepart(dw,@date);

select @c1= substring(@day_opt,1,1)

Page 235: Query

Query - Page #2

select @c2= substring(@day_opt,2,2) if(@day_num=@c1 or @day_num=@c2) -- day check if begin select @rec_num=count(*) from test_trans where f_num=@f_num and date_of_travel=@date and class=@class-- First class coding if(@class=’First’)-- first class if begin if(@rec_num<5) -- seat checking if begin select @pnr_no=max(pnr) from test_trans

if(@pnr_no is null) -- pnr checking if begin select @pnr_no = 101 end else begin select @pnr_no = @pnr_no + 1 end

insert into test_trans values(@f_num,@pnr_no,@name,@age,@sex,@address,@date,@class,’Confirmed’) select @flag=1 select ’Fsucess’+convert(varchar,@pnr_no)

end -- seat check if end else begin -- first class waiting code

if(@rec_num<7 and @wstatus=1) begin select @pnr_no=max(pnr) from test_trans select @pnr_no = @pnr_no + 1 insert into test_trans values(@f_num,@pnr_no,@name,@age,@sex,@address,@date,@class,’Waiting’) select @flag=1 select ’FWsucess’+convert(varchar,@pnr_no) end end -- first class waiting code end end -- first class if end

-- Economy class coding if(@class=’Economy’)-- economy class if begin if(@rec_num<3) -- economy seat checking if begin select @pnr_no=max(pnr) from test_trans

if(@pnr_no is null) -- pnr checking if begin select @pnr_no = 100 end else begin select @pnr_no = @pnr_no + 1 end

insert into test_trans values(@f_num,@pnr_no,@name,@age,@sex,@address,@date,@class,’Confirmed’) select @flag=1 select ’Esucess’+convert(varchar,@pnr_no)

end -- economy seat check if end else begin -- Economy class waiting code if(@rec_num<5 and @wstatus=1) begin select @pnr_no=max(pnr) from test_trans select @pnr_no = @pnr_no + 1 insert into test_trans values(@f_num,@pnr_no,@name,@age,@sex,@address,@date,@class,’Waiting’) select @flag=1 select ’EWsucess’+convert(varchar,@pnr_no) end end -- Economy class waiting code end end -- econnomy class if end

Page 236: Query

Query - Page #3

-- Business class coding if(@class=’Business’)-- Business class if begin if(@rec_num<3) -- Business seat checking if begin select @pnr_no=max(pnr) from test_trans

if(@pnr_no is null) -- pnr checking if begin select @pnr_no = 100 end else begin select @pnr_no = @pnr_no + 1 end

insert into test_trans values(@f_num,@pnr_no,@name,@age,@sex,@address,@date,@class,’Confirmed’) select @flag=1 select ’Bsucess’+convert(varchar,@pnr_no)

end --Business seat check if end else begin -- Business class waiting code if(@rec_num<5 and @wstatus=1) begin select @pnr_no=max(pnr) from test_trans select @pnr_no = @pnr_no + 1 insert into test_trans values(@f_num,@pnr_no,@name,@age,@sex,@address,@date,@class,’Waiting’) select @flag=1 select ’BWsucess’+convert(varchar,@pnr_no) end end -- Business class waiting code end end -- Business class if end

if(@flag=0) begin select "housefull" end

end -- day check if else begin select ’wrongdate’ end

******************************************************************************************** Cancellation Procedure*****************************************************************************create procedure sen_cancellation(@pnr int,@cdate varchar(20))as

declare @datediff intdeclare @class varchar(20)declare @amt floatdeclare @minpnr intdeclare @waiting varchar(20)

select @datediff=datediff(day,date_of_travel,@cdate) from test_trans where pnr=@pnrselect @class = class from test_trans where pnr=@pnrselect @waiting= status from test_trans where pnr=@pnr

select @amt=case @class when ’First’ then 6500 when ’Business’ then 5200 when ’Economy’ then 4700end

if(@datediff=0) -- if he cancel the same date begin select (@amt*(90.0/100.0)) delete test_trans where pnr=@pnr

Page 237: Query

Query - Page #4

select @minpnr = min(pnr) from test_trans where class=@class and status=’Waiting’

if(@minpnr !=0 and @waiting !=’Waiting’) begin update test_trans set status=’Confirmed’ from test_trans where pnr=@minpnr end end -- same date if end if(@datediff>0) -- more than one day begin select (@amt*(80.0/100.0)) delete test_trans where pnr=@pnr select @minpnr = min(pnr) from test_trans where class=@class and status=’Waiting’ if(@minpnr !=0 and @waiting !=’Waiting’) begin update test_trans set status=’Confirmed’ from test_trans where pnr=@minpnr end end -- more than one day if end

if(@datediff is null) -- if the pnr no not exists in the database begin select ’invalidpnr’ end

*****************************************************************************

exec sen_reservation ’SA101’,’3/17/2002’,’Business’,’Senthil’,23,’Male’,’T.gode’,1

exec sen_cancellation 100,’3/18/2002’

drop procedure sen_cancellationdrop procedure sen_reservation

select * from test_transdelete test_trans

select f_class_seats,b_class_seats,e_class_seats from flight_master where f_num=’SA101’

select count(*) from test_trans where f_num=’SA101’ and class=’First’

select ’senthil’+convert(varchar,10)

select * from flight_master

Page 238: Query

Query - Page #1

----------------------------------------------------------------------------------------------

BANK CPP PROGRAM----------------------------------------------------------------------------------------------

// Computerized Bank

#include<iostream.h>#include<conio.h>#include<fstream.h>#include<string.h>#include<dos.h>#include<stdlib.h>

static int A_no=1000;

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();

};

class Tlist : public Transaction{ private:

Tlist *head,*prev,*cur,*temp; public:

void Load_Transaction_Records(); float Make_Transaction(int); void List_Transaction(int,float); void List_Daily_Transaction(char *); void List_Monthly_Transaction(char *); float Modify_Transaction(int,char *,char *,char *); float Delete_Transaction(int,char *,char *,char *); void Store_Transaction_Records();

};/////////////////////////////////////////////////////////////////////////////// Alist Class member function definitionsvoid Alist :: Load_Account_Records(){ ifstream ifile("Accounts.dat",ios::binary | ios :: in | ios :: nocreate );

Page 239: Query

Query - Page #2

head = prev = cur = temp = NULL;

// static int A_no = 1000;

if(!ifile.fail()) // If the file exist { ifile.seekg(0,ios::end); // Move file pointer to end

int Total_Records = ifile.tellg()/sizeof(Alist);

ifile.seekg(0,ios::beg); // Move the File Pointer to beginning

if(Total_Records == 0) { A_no= 1000; return; }

Alist A;

for(int i=1;i<=Total_Records;i++) {

ifile.read((char *)&A,sizeof(Alist));

cur = (Alist *) new Account;

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;

}// End of IF loop

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

Page 240: Query

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; }

temp = (Alist *) temp->link; } return(balance);}//////////////////////////////////////////////////////////////////////////////void Alist :: Modify_Account(int a_no){ temp = head;

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; }

temp = (Alist *) temp->link; }}/////////////////////////////////////////////////////////////////////////////void Alist :: Delete_Account(int a_no){ temp = head;

Alist *p = head;

while(temp!=NULL)

Page 241: Query

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 = (Alist *) temp->link; }}/////////////////////////////////////////////////////////////////////////////void Alist :: Store_Account_Records(){ ofstream ofile("Accounts.dat",ios::binary | ios :: out);

temp = head;

while(temp != NULL) { ofile.write((char *)temp,sizeof(Alist)); temp = (Alist *) temp->link; } ofile.close();}

/////////////////////////////////////////////////////////////////////////////// Transaction Class Member Functionsvoid Tlist :: Load_Transaction_Records(){ ifstream ifile("Transaction.dat",ios::binary | ios :: in | ios :: nocreate );

head = prev = cur = temp = NULL;

if(!ifile.fail()) // If the file exist { ifile.seekg(0,ios::end); // Move file pointer to end

int Total_Records = ifile.tellg()/sizeof(Tlist);

ifile.seekg(0,ios::beg); // Move the File Pointer to beginning

Tlist T;

for(int i=1;i<=Total_Records;i++) {

ifile.read((char *)&T,sizeof(Tlist));

cur = (Tlist *) new Transaction;

if(i==1) {

Page 242: Query

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

}// End of IF 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;

Page 243: Query

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;}

}

temp = (Tlist *) temp->link; }

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; } }

temp = (Tlist *) temp->link; }

cout<<"-----------------------------------------------------------"<<endl;

cout<<"Total "<<total_deposit<<" "<<total_withdraw <<" Net Balance"<<(total_deposit - total_withdraw)<<endl;

cout<<"-----------------------------------------------------------"<<endl;

}////////////////////////////////////////////////////////////////////////////float Tlist :: Delete_Transaction(int a_no,char *mode,char *date,char *type){ temp = head;

Page 244: Query

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 Functionvoid main(){ clrscr();

int choice,acc_no;

char today[15],mode[15],type[15];

char next = ’y’;

Alist A;

A.Load_Account_Records(); // Load all Records to Linked List

Tlist T;

T.Load_Transaction_Records(); // Load All Transaction Records to Linked List

while(next==’y’) { cout<<"1.Open New Account "<<endl;

Page 245: Query

Query - Page #8

cout<<"2.Make A Transaction "<<endl; cout<<"3.List All Accounts "<<endl; cout<<"4.List A Account "<<endl; cout<<"5.List Daily Transactions "<<endl; cout<<"6.Modify A Account "<<endl; cout<<"7.Delete A Account "<<endl; cout<<"8.Delete A Transaction "<<endl; cout<<"9.Exit "<<endl; cout<<"Enter Your Choice : "; cin>>choice;

switch(choice) { case 1 : A.Open_Account(); break;

case 2 : cout<<"Enter Account Number : "; cin>>acc_no; A.Update_Balance(acc_no,(float)(T.Make_Transaction(acc_no)));// cout<<T.Make_Transaction(acc_no)<<endl;// getch(); break;

case 3 : A.List_all_Accounts(); getch(); break;

case 4 : cout<<"Enter Account Number : "; cin>>acc_no; int balance = A.List_Account(acc_no);

T.List_Transaction(acc_no,balance); getch(); break;

case 5 : cout<<"Enter the Date : "; cin>>today; T.List_Daily_Transaction(today); getch(); break;

case 6 : cout<<"Enter Account No : "; cin>>acc_no; A.Modify_Account(acc_no); break;

case 7 : cout<<"Enter Account No : "; cin>>acc_no; A.Delete_Account(acc_no);

int return_something;

jump: return_something = T.Delete_Transaction(acc_no,"DAll"," "," ");

if(return_something !=0) goto jump; break;

case 8 : cout<<"Enter Account No : "; cin>>acc_no; cout<<"Enter Mode : "; cin>>mode; cout<<"Enter Date : "; cin>>today; cout<<"Enter Type : "; cin>>type;

A.Update_Balance(acc_no,(T.Delete_Transaction(acc_no,mode, today,type)));

break;

case 9 : next = ’n’; break; }

clrscr();

}

Page 246: Query

Query - Page #9

A.Store_Account_Records(); T.Store_Transaction_Records();

}

/////////////////////////////////////////////////////////////////////////////

Page 247: Query

Query - Page #1

----------------------------------------------------------------------------------------------

LIBRARY CPP PROGRAM----------------------------------------------------------------------------------------------

// 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;};

struct Book *Bhead,*Bprev,*Bcur,*Btemp;struct Member *Mhead,*Mprev,*Mcur,*Mtemp;struct Issue_Register *IRhead,*IRprev,*IRcur,*IRtemp;

int B_no = 100;int M_no = 500;

////////////////////////////////////////////////////////////////////////////// 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();

Page 248: Query

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 definitionvoid Load_Books_Records(){ ifstream iBfile("Books.dat",ios::binary | ios :: in | ios :: nocreate );

Bhead = Bprev = Bcur = Btemp = NULL;

if(!iBfile.fail()) // If the file exist { iBfile.seekg(0,ios::end); // Move file pointer to end

int Total_Records = iBfile.tellg()/sizeof(Book);

iBfile.seekg(0,ios::beg); // Move the File Pointer to beginning

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));

Bcur = new 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;

}// End of IF loop

iBfile.close();

}////////////////////////////////////////////////////////////////////////////// Load Members Records Function definitionvoid Load_Members_Records(){ ifstream iMfile("Members.dat",ios::binary | ios :: in | ios :: nocreate );

Mhead = Mprev = Mcur = Mtemp = NULL;

if(!iMfile.fail()) // If the file exist {

Page 249: Query

Query - Page #3

iMfile.seekg(0,ios::end); // Move file pointer to end

int Total_Records = iMfile.tellg()/sizeof(Member);

iMfile.seekg(0,ios::beg); // Move the File Pointer to beginning

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));

Mcur = new 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;

}// End of IF loop

iMfile.close();

}////////////////////////////////////////////////////////////////////////////// Load Issue_Register Function definitionvoid Load_Issue_Register_Records(){ ifstream iIRfile("IRegister.dat",ios::binary | ios :: in | ios :: nocreate );

IRhead = IRprev = IRcur = IRtemp = NULL;

if(!iIRfile.fail()) // If the file exist { iIRfile.seekg(0,ios::end); // Move file pointer to end

int Total_Records = iIRfile.tellg()/sizeof(Issue_Register);

iIRfile.seekg(0,ios::beg); // Move the File Pointer to beginning

if(Total_Records == 0) { return; }

struct Issue_Register IR;

for(int i=1;i<=Total_Records;i++) {

iIRfile.read((char *)&IR,sizeof(Issue_Register));

IRcur = new Issue_Register;

if(i==1) {

Page 250: Query

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

}// End of IF loop

iIRfile.close();

}////////////////////////////////////////////////////////////////////////////// Add Book function definitionvoid 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 definitionvoid List_A_Book(){

Btemp = Bhead;

int a_no;

cout<<"Enter Book Accession No : "; cin>>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;

Page 251: Query

Query - Page #5

cout<<"Purchase Date : "<<Btemp->purchase_date<<endl; cout<<"Price : "<<Btemp->price<<endl; break; }

Btemp = Btemp->link; }

if(Btemp==NULL) cout<<"Book Not Found!!"<<endl;

}///////////////////////////////////////////////////////////////////////////// Delete Book Functionvoid Delete_Book(){ Btemp = Bhead;

Book *p = Bhead;

int a_no;

cout<<"Enter Accession No : "; cin>>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 definitionvoid 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; */

cout<<setw(10)<< Btemp->accession_no<<" "<<setw(-13)<<Btemp->title <<" "<<setw(-20)<<Btemp->author<<" "<<setw(-13) <<Btemp->publisher<<endl;

Btemp = Btemp->link; }

cout<<"-----------------------------------------------------------------"<<endl;}/////////////////////////////////////////////////////////////////////////////////// Add Member function definition

Page 252: Query

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 definitionvoid List_A_Member(){

Mtemp = Mhead;

int m_no;

cout<<"Enter Membership No : "; cin>>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;

Page 253: Query

Query - Page #7

cout<<"Caution Dep : "<<Mtemp->caution_deposit<<endl; break; }

Mtemp = Mtemp->link; }

if(Mtemp==NULL) cout<<"Member Not Found!!"<<endl;

}///////////////////////////////////////////////////////////////////////////// Delete Member Functionvoid Delete_Member(){ Mtemp = Mhead;

Member *p = Mhead;

int m_no;

cout<<"Enter Membership No : "; cin>>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 definitionvoid 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 detailsvoid Book_Issue(){ int a_no,m_no;

cout<<"Accession No : "; cin>>a_no;

Page 254: Query

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 = new Issue_Register; IRcur->link = NULL;

IRcur->accession_no = a_no; IRcur->membership_no = m_no;

cout<<"Return Date : "; cin>>IRcur->return_date;

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 {

Page 255: Query

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 definitionvoid 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 definitionvoid List_Overdue_Books(){ char today[20];

cout<<"Enter Date : "; cin>>today;

IRtemp = IRhead;

Page 256: Query

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 Functionvoid 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 Functionvoid 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 Functionvoid 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()

Page 257: Query

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;

case 2 : Delete_Book(); break;

case 3 : List_A_Book(); getch(); break;

case 4 : List_All_Books(); getch(); break;

case 5 : Add_Member(); break;

case 6 : Delete_Member(); break;

case 7 : List_A_Member(); getch(); break;

case 8 : List_All_Members(); getch(); break;

case 9 : Book_Issue(); break;

case 10: Book_Return(); break;

case 11: Book_Issue_Details(); getch(); break;

case 12: List_Overdue_Books(); getch(); break;

case 13: ch=’n’; break;

} // end of switch st

clrscr();

} // end of while loop

Store_Books_Records(); Store_Members_Records(); Store_Issue_Register_Records();

}

Page 258: Query

Query - Page #12

////////////////////////////////////////////////////////////////////////////

Page 259: Query

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"); } */

/* Returning every array’s base address int (*fun2())[3]; int (*q)[3]; q = fun2();

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;}

Page 260: Query

Query - Page #1

#include<stdio.h>

void main(){ char names[][5] = { {"Sabit"},

{"Dee"}, {"Kumar"} };

char *names1[3] = { {"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;

printf("\nStatic Array Coping"); printf("\n%s",*p); printf("\n%s",p[0]); printf("\n%s",&(**p)); printf("\n%s",*++p);

q = &names;

printf("\nStatic Array Address coping"); printf("\n%s",**q); printf("\n%s",&(***q)); printf("\n%s",*((*q+1)));

m = names1;

printf("\nDynamic Array Coping"); printf("\n%s",*m); printf("\n%s",*++m); printf("\n%s",&(**m));

n = &names1;

printf("\nDynamic Array Address coping"); printf("\n%s",**n); printf("\n%s",*(*n+1));

}