Query

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Query as PDF for free.

More details

  • Words: 63,691
  • Pages: 260
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;

1

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;

2

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 d 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 TITLES GROUP BY TYPE,PUB_ID; SELECT * FROM TITLES ORDER BY TYPE DESC; ////////////////////////////////////////////////////////////////////////////////////////// select type,sum(price) from titles group by type order by title_id; When ever use an order by class along with group by class the order by class should have only those filels which are present in the group by class. ///////////////////////////////////////////////////////////////////////////////////////////// select type,title_id,sum(price) from titles group by type order by title_id; // Error select type,title_id,sum(price) from titles group by type,title_id order by title_id; select * from titles; select sum(price) from titles ; select sum(price) from titles

order by titles

3

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 titles order 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 itself able to generate Work Table...So the Compute by class relay order by class... select type,price from titles order by pub_id compute sum(price) by type; // Error Reason: The work table is built based on pub_id...In that work Table,we can’t find the sum of price by Type...’ select type,pub_id,price from titles order by type,pub_id compute sum(price) by type; select type,pub_id,price from titles order by type,pub_id compute sum(price) by pub_id; // Error Reason: Work Table Type pub_id Price -------------------------Business p1 200 Business p1 200 Business p2 300 Computer p2 400 Computer p2 200 Novel p1 200 Novel p1 240 Novel p2 450

4

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

Query -

Page #5

select type,pub_id,price from titles order by type,pub_id compute sum(price) by type,pub_id; select type,pub_id,title_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id,title_id; select type,pub_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id; **************************************************** Afternoon:21-dec-2001 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 titles group 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 apply for a particular column. It will apply all the columns in the select list For Ex Business Business Business Computer Computer

p1 p1 p1 p2 p2

200 400 300 500 700

The Result is Business Computer

p1 p2

200 500

///////////////////////////////////////////////// select type,sum(price),avg(price) from titles group by price; // Error Reason: The field name in group by clause which is not used in aggregate function in select list ////////////////////////////////////////////////////////// Having:

5

Having clause should have group by class...but when using group by class it is optional to use Having clause.

Query -

Page #6

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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 // 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select type,sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 ///////////////////////////////////////////////////////////////////////////////////////////////// December-26-2001 Joins: 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 called cross joining which is never used... 6

select * from authors,publishers

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

// authors.* displays all fields in the Authors Table

Natural join: The redundat field names are eliminated in the Result

set

join Equi Join : The Redundat field names are present in the result set. Table Alias: select p.*,au_id,au_lname from authors, publishers p where authors.city=p.city; select p.*,au_id,au_lname from authors a, publishers p where a.city = p.city and a.au_lname like ’c%’ select p.*,au_id,au_lname from authors a, publishers p where au_lname like ’c%’ and a.city = p.city Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select select select select

* * * *

from from from from

authors; publishers; titles; 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

7

Query -

Page #8

a2

peter

Table: Publisher pub_id -----p1 p2 p3

pub_name ----------samy golgotia samba

Table: Titles title_id -------t1 t2 t3

pub_id -------p1 p2 p3

Table: TitleAuthor au_id title_id ----------- -------a1 t1 a1 t2 a2 t1 a2 t3 Virtual Tables: [Authors] aid aname a1 lockey a1 lockey

[TitleAuthor] au_id title_id a1 t1 a1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[titles] title_id t1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[ titles ] [ publisher] title_id pub_id pub_id pub_name t1 p1 p1 sams t2 p2 p2 golgotia

pub_id p1 p2

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:

8

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

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 //////////////////////////////////////////////////////////////////////////////////////////////// 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 A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

au_id A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

Result set would be A1 A6 A2 A3 select a.au_id,a.city from authors a, authors b where a.city = b.city;

// It displays duplicate Records

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

Query -

Page #10

select distinct a.au_id,a.city from authors a, authors b where a.city = b.city; // It displays distinct records but it dispalys one author lives in the city select distinct a.au_id,a.city from authors a, authors b where a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered... select distinct a.au_id,a.city from authors a, authors b where 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 10 ta1.title_id <> ta2.title_id and ta1.au_id = a.au_id;

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 e2 e3 e4 e5

boris becker peter Anderw Lafer

HRD HRD SYS SYS null

dep HRD SYS PER NET

Human Res Systems personal network

emp eno ename d_id dept ddid dname Display the emp details along with dept id?? select emp.* d.did from emp e,dept d where e.did=d.did REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS select emp.*,d.did from e,dept d where e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax) REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS e5 lafer select emp.*,d.did from e,dept d where 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) 11

The above two query gives the same result.. ////////////////////////////////////////////////////////////////////////////////////////////

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 ] /////////////////////////////////////////////////////////////////////////////////////////////// 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 because the 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 q 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 12 because the inner query will give only boolean values.... --------------------------------------------------------------------------------------------------------

Query -

Page #13

7-01-2002: select distinct a.au_fname from authors a, authors b where 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_fname from authors a where exists ( select b.au_id from authors b where a.state = b.state and a.au_id <> b.au_id ); // This is correlated sub query 1.It has join. 2.The left or right side field name is oute The correlated sub query executed for every outer table row...but simple sub query executed only once...

It takes one record from the outer condition for that row all the rows of the inner codition will be exec If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct the correlated sub query.

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 wou 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; // if u want to include the duplicates use Union all keyword...

It will not give the duplicates of the re

select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ select price,title from titles union all select title_id,au_id from titleauthor; // Error

data type mis

Note: The order by statements can not be used in the individual query inside the union but group by and having is allowed. But order by allowed in the outside of the union . Example:

select title_id,title from titles union all select title_id,au_id from titleauthor o Note: The field name in the first select statement is allowed in the order by clause. we can not use group by clause in the order by place....

--------------------------------------------------------------------------------------------------------Self-Interest: Find total purchase for each customer?????????? Ans: drop vi create view v_sample as select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p where o.proid=p.pid group by o.cuid select max(tprice) from v_sample Find which customer purchased more???? 13 Ans: select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p where o.proid=p.pid group by o.cuid;

Query -

Page #14

--------------------------------------------------------------------------------------------------------11-01-2002: Syntax: Grant select|update|insert|delete on Table_name to User Grant All Table_name to User Revoke select|update|insert|delete on Table_name from User Revoke All Table_name from User 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_empdat as select eid,ename,did,dname from emp,dept where emp.did = dept.did; Grant select on v_empdat to sa Step 1: create view sen_view_v1 as select * from titles where title_id=’BU1111’ Step 2: select * from sen_view_v1; // The select statement inside the view will be executed.... delete sen_view_v1; 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 as select pub_id,sum(price) from titles group by pub_id; // The above statement would not work. Here the sum(price) is tried to derive a new column in the view To make work the above statement.... create select (or) create select

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

////////////////////////////////////////////////////////////////////////////////////////////// Rule: 1. We can not use order by,compute by,compute14in the selection list while creating views. 2. We can not use ’Select into’ on views. 3. We can use order by indirectly. //////////////////////////////////////////////////////////////////////////////////////////////

Query -

Page #15

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

not not not not not

null, null, null, null, null

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

will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olny it is possible insert,update,delete, If the view does not contain all not null columns, it is only readable veiw.We can not do insert,delete,update... Rule 2: If the select list in the view contains aggregate functions,the view is readable view... 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 as select * from emp where dept_id = ’HRD’; select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS find whether it is table or view...if it is view, it executes the select statement with where condition. And the statement looks like below.... 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 interpreted as 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 has been created by with check option condition. It allow only the where clause condition is match, it means that we can insert only ’HRD’ type...... ///////////////////////////////////////////////////////////////////////////////////////////////// Question: Find which type sales is greater??? We can not write in single select statement.... create view sen_v1 as select type,sum(price)as "Total_sales" from titles group by type select type,max(Total_sales) from sen_v1 15 max(Total_sales) from sen_v1) group by type,Total_sales having Total_sales= (select select type from sen_vl where Total_sales = (select max(Total_sales) from sen_v1)

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)] as sql statements;

[ ]--->optional

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, it checks the existence of the column, if it is, the procudure will be created...if the column does not 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 compilation process is done.. select object_id (’demo’); // we can get the table id what the sql server maintains... create procedure pro(parameters) with recompile as 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 execute the procedure another time, it will no go for compilation process,it just checks the procedure cache and execute suitable obj file....If the system is gone for shut down, the contents of the procedure cache will be deleted....Whatever changes made in table contents, it will re-complile. if the table is dropped,the procedure for the table will not be deleted... 16

////////////////////////////////////////////////////////////////////////////////////////////// 18-January-2002:

Query -

Page #17

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

17

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 as goto a a: 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 One 2. One to Many 3. Many to Many

18

Query -

Page #19

{Chen notation} [Entity] [Relation] Employee---------- Works In |[Rect] [Diamond] | |-------has --------Address [Diamond] [Rect]

[Entity] ----------------Dept [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] and one 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 d1 e2 d1 d2 e3 d2 d3 e4 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] Professor -------------[Entity](0,1)

[Diamond] [Rect] is allotted -----------Room [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) TheatreFilm19(Associative Entity) or Junction Table -----------------------------------------------------------------------------------------tid (pk) fid (pk) tid tname fname fid

Query no_seats location

Page #20 hero heroine

composite primary key(tid,fid)

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 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 informatio Atomic values: A field should record about the single attribute... For example: To store address,we have to put street,city,state,country as a separate field names. Then only possible to search the employees by city,state or country.....

(*) The field names shoud accept null values, if the no specefic info for that recor and take to consideration the table should not have more null value fields. Example: 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 may depend on other non key attributes...

primary key or all the non key attributes

In the above table, the department id is partially belonging to the primary key,which means that the emp itself only need to identify the department id and the project id is no longer needed...

*In order conform second normal form,we have take out the non key attribute which does not depend entril the primary key and put it separate table along with the field on which the non key attribute is depen so we take off did from the above table eid did --------e1 IS e2 IS e3 NET 24 NET

20

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

Query -

Page #21

pid nohrs ----------p1 20 p2 30 ( It is in third normal form,we can not split it again) The dehead is not related to eid or pid...it is related to did.....so put dhead following table 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 th did 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 delete any enty in the master table,which is refered by in the child table...The SQL server maintains restrictions automatically...The cascade deletions is opposite of these restrictions.... Syntax: 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 after trigger,The SQL could not support Before Triggers..... Trigger can not accept parameters..... Book Magazine ---------------------------Bid Magid Bname Mname Author price

21

Query -

Page #22

Transaction -------------Tid Card_id book_id issue_date return_date -------------------------------------------------------------------------------------------------Implementing primary key constraint:Create trigger tri on temp for insert as declare @icount int select @icount=count(*) from temp,inserted where temp pk = insert pk if @icount >1 begin print ’Duplicate Record’ rollback end else print ’Successfully on inserting the record’ inserted--->trigger test table (or) magic table ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on emp for insert as if not exists(select * from dept,inserted where dept.did=inserted.did) begin print "Integrity violation" rollback; end else print "successfull insertion into the table" emp inserted ---------------------------------------------------e1 boris d1 d1 HRD e2 becker d2 d2 SYS e3 sapeg d3 ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on trans_member for insert as if 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’ end else print ’Successfully inserted into the table’ ------------------------------------------------------------------------------------------------Note: While creating trigger,the object should be exist on which the trigger imposed...but it 22 does not check the body of the statements.... ------------------------------------------------------------------------------------------------Implementing Cascade Deletion:-

Query -

Page #23

Create trigger dtri on publishers for delete as delete 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 dtri on publishers for delete as if exists( select * from titles,deleted where titles.pub_id=deleted.pub_id) begin print ’Attempt to create orphan Records’ rollback end -----------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables????? Hits provided: declare @i int select @i=Object_id(’publishers’) if exists(select * from sysobjects where id=@i) insert back_up select * from deleted -----------------------------------------------------------------------------------------------31-JAN-2002: customers invoice products ---------------------------------------------cid oid pid cname cid pname pid qoh (quantity in hand) qty price create trigger tri on invoice for insert as update products set qoh=qoh-inserted.qty from products,inserted where products.pid=inserted.pid checking the availability of products: --------------------------------------select @iqty = inserted.qty from inserted select @qty = products.qty from inserted,products where inserted.pid=products.pid if(@qty<@iqty) begin print "invalid transaction" rollback return end ------------------------------------------------------------------------------------------Note: The rollback command will only work on triggers it will not work on procedures.... -------------------------------------------------------------------------------------------23 Note: Through the delete and update command will affect many rows.., the trigger will be executed for each row... --------------------------------------------------------------------------------------------create trigger tri

Query -

Page #24

on invoice for update if update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback return end if not exists (select * from products,inserted where inserted.productid=products.proudctid begin print ’Fk violation on products’ rollback return end -------------------------------------------------------------------------------------------Note: For update triggers, the inserted and deleted virutal table will be created.... deleted followed by inserted................... -------------------------------------------------------------------------------------------TSQL Cursors: The main application of cursors is ’report’ generation.......... The cursor contains following five ’jargons’ 1....Declare 2....Open 3....Fetch 4....Close 5....Deallocate A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’.. 1...Declare: Syntax: Declare cursorname cursor for select statement // 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

24

Query -

Page #25

declare cur cursor scroll for select * from sen_catlog open cur fetch next from cur while(@@fetch_status=0) begin fetch next from cur end close cur deallocate cur exec sen_cur_pro; Note: @@fetch_status is system defined global variable which is automatically set to 0 which indicates for successful fetch... -----------------------------------------------------------------------------------------------1-02-2002: Application of Cursors: Create procedure sen_cpro as declare @tid varchar(20),@title varchar(20),@price float declare cur cursor scroll for select title_id,title,price from titles open cur fetch next from cur into @tid,@title,@price while(@@fetch_status=0) begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@price end close cur deallocate 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 as set nocount on declare @pid varchar(20),@pname varchar(20) declare @tid varchar(20),@title varchar(20),@price float declare @n int declare cur cursor scroll for select pub_id,pub_name from publishers open cur fetch next from cur into @pid,@pname while(@@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) 25 begin print @tid + " " + @title + " " + convert(varchar,@price) fetch next from tcur into @tid,@title,@price end

Query -

Page #26 close tcur deallocate tcur

end print ’------------------------------------------------’ fetch next from cur into @pid,@pname end close cur deallocate cur

exec sen_publisher_books --------------------------------------------------------------------------------------------------------2-Feb-2002: Indexing: It is a sorting process to reduce the searching process time.... Syntax: Create { nonClustered } index index_name on table_name(field_name) Default is Clustered indexing................ ------------------------------------------------------------------------------------------------NonClustered: create nonclustered index emp_eno on 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 or it is feasible for going for table scan...... -------------------------------------------------------------------------------------------------Note: Primary key creates Clustered automaically but to make it nonClustered index is more feasible than Clustered index -------------------------------------------------------------------------------------------Clustered: create clustered index emp_eno on 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 of record... 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 ------------------------------------------------------------------------------------------------

26

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;

27

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;

28

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 d 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 TITLES GROUP BY TYPE,PUB_ID; SELECT * FROM TITLES ORDER BY TYPE DESC; ////////////////////////////////////////////////////////////////////////////////////////// select type,sum(price) from titles group by type order by title_id; When ever use an order by class along with group by class the order by class should have only those filels which are present in the group by class. ///////////////////////////////////////////////////////////////////////////////////////////// select type,title_id,sum(price) from titles group by type order by title_id; // Error select type,title_id,sum(price) from titles group by type,title_id order by title_id; select * from titles; select sum(price) from titles ; select sum(price) from titles

order by titles

29

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 titles order 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 itself able to generate Work Table...So the Compute by class relay order by class... select type,price from titles order by pub_id compute sum(price) by type; // Error Reason: The work table is built based on pub_id...In that work Table,we can’t find the sum of price by Type...’ select type,pub_id,price from titles order by type,pub_id compute sum(price) by type; select type,pub_id,price from titles order by type,pub_id compute sum(price) by pub_id; // Error Reason: Work Table Type pub_id Price -------------------------Business p1 200 Business p1 200 Business p2 300 Computer p2 400 Computer p2 200 Novel p1 200 Novel p1 240 Novel p2 450

30

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

Query -

Page #5

select type,pub_id,price from titles order by type,pub_id compute sum(price) by type,pub_id; select type,pub_id,title_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id,title_id; select type,pub_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id; **************************************************** Afternoon:21-dec-2001 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 titles group 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 apply for a particular column. It will apply all the columns in the select list For Ex Business Business Business Computer Computer

p1 p1 p1 p2 p2

200 400 300 500 700

The Result is Business Computer

p1 p2

200 500

///////////////////////////////////////////////// select type,sum(price),avg(price) from titles group by price; // Error Reason: The field name in group by clause which is not used in aggregate function in select list ////////////////////////////////////////////////////////// Having:

31

Having clause should have group by class...but when using group by class it is optional to use Having clause.

Query -

Page #6

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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 // 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select type,sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 ///////////////////////////////////////////////////////////////////////////////////////////////// December-26-2001 Joins: 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 called cross joining which is never used... 32

select * from authors,publishers

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

// authors.* displays all fields in the Authors Table

Natural join: The redundat field names are eliminated in the Result

set

join Equi Join : The Redundat field names are present in the result set. Table Alias: select p.*,au_id,au_lname from authors, publishers p where authors.city=p.city; select p.*,au_id,au_lname from authors a, publishers p where a.city = p.city and a.au_lname like ’c%’ select p.*,au_id,au_lname from authors a, publishers p where au_lname like ’c%’ and a.city = p.city Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select select select select

* * * *

from from from from

authors; publishers; titles; 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

33

Query -

Page #8

a2

peter

Table: Publisher pub_id -----p1 p2 p3

pub_name ----------samy golgotia samba

Table: Titles title_id -------t1 t2 t3

pub_id -------p1 p2 p3

Table: TitleAuthor au_id title_id ----------- -------a1 t1 a1 t2 a2 t1 a2 t3 Virtual Tables: [Authors] aid aname a1 lockey a1 lockey

[TitleAuthor] au_id title_id a1 t1 a1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[titles] title_id t1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[ titles ] [ publisher] title_id pub_id pub_id pub_name t1 p1 p1 sams t2 p2 p2 golgotia

pub_id p1 p2

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:

34

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

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 //////////////////////////////////////////////////////////////////////////////////////////////// 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 A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

au_id A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

Result set would be A1 A6 A2 A3 select a.au_id,a.city from authors a, authors b where a.city = b.city;

// It displays duplicate Records

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

Query -

Page #10

select distinct a.au_id,a.city from authors a, authors b where a.city = b.city; // It displays distinct records but it dispalys one author lives in the city select distinct a.au_id,a.city from authors a, authors b where a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered... select distinct a.au_id,a.city from authors a, authors b where 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 36 ta1.title_id <> ta2.title_id and ta1.au_id = a.au_id;

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 e2 e3 e4 e5

boris becker peter Anderw Lafer

HRD HRD SYS SYS null

dep HRD SYS PER NET

Human Res Systems personal network

emp eno ename d_id dept ddid dname Display the emp details along with dept id?? select emp.* d.did from emp e,dept d where e.did=d.did REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS select emp.*,d.did from e,dept d where e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax) REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS e5 lafer select emp.*,d.did from e,dept d where 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) 37

The above two query gives the same result.. ////////////////////////////////////////////////////////////////////////////////////////////

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 ] /////////////////////////////////////////////////////////////////////////////////////////////// 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 because the 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 q 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 38 because the inner query will give only boolean values.... --------------------------------------------------------------------------------------------------------

Query -

Page #13

7-01-2002: select distinct a.au_fname from authors a, authors b where 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_fname from authors a where exists ( select b.au_id from authors b where a.state = b.state and a.au_id <> b.au_id ); // This is correlated sub query 1.It has join. 2.The left or right side field name is oute The correlated sub query executed for every outer table row...but simple sub query executed only once...

It takes one record from the outer condition for that row all the rows of the inner codition will be exec If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct the correlated sub query.

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 wou 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; // if u want to include the duplicates use Union all keyword...

It will not give the duplicates of the re

select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ select price,title from titles union all select title_id,au_id from titleauthor; // Error

data type mis

Note: The order by statements can not be used in the individual query inside the union but group by and having is allowed. But order by allowed in the outside of the union . Example:

select title_id,title from titles union all select title_id,au_id from titleauthor o Note: The field name in the first select statement is allowed in the order by clause. we can not use group by clause in the order by place....

--------------------------------------------------------------------------------------------------------Self-Interest: Find total purchase for each customer?????????? Ans: drop vi create view v_sample as select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p where o.proid=p.pid group by o.cuid select max(tprice) from v_sample Find which customer purchased more???? 39 Ans: select sum(o.qty * p.price) ’Total Purchase’ from orders o, produ p where o.proid=p.pid group by o.cuid;

Query -

Page #14

--------------------------------------------------------------------------------------------------------11-01-2002: Syntax: Grant select|update|insert|delete on Table_name to User Grant All Table_name to User Revoke select|update|insert|delete on Table_name from User Revoke All Table_name from User 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_empdat as select eid,ename,did,dname from emp,dept where emp.did = dept.did; Grant select on v_empdat to sa Step 1: create view sen_view_v1 as select * from titles where title_id=’BU1111’ Step 2: select * from sen_view_v1; // The select statement inside the view will be executed.... delete sen_view_v1; 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 as select pub_id,sum(price) from titles group by pub_id; // The above statement would not work. Here the sum(price) is tried to derive a new column in the view To make work the above statement.... create select (or) create select

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

////////////////////////////////////////////////////////////////////////////////////////////// Rule: 1. We can not use order by,compute by,compute40in the selection list while creating views. 2. We can not use ’Select into’ on views. 3. We can use order by indirectly. //////////////////////////////////////////////////////////////////////////////////////////////

Query -

Page #15

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

not not not not not

null, null, null, null, null

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

will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olny it is possible insert,update,delete, If the view does not contain all not null columns, it is only readable veiw.We can not do insert,delete,update... Rule 2: If the select list in the view contains aggregate functions,the view is readable view... 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 as select * from emp where dept_id = ’HRD’; select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS find whether it is table or view...if it is view, it executes the select statement with where condition. And the statement looks like below.... 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 interpreted as 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 has been created by with check option condition. It allow only the where clause condition is match, it means that we can insert only ’HRD’ type...... ///////////////////////////////////////////////////////////////////////////////////////////////// Question: Find which type sales is greater??? We can not write in single select statement.... create view sen_v1 as select type,sum(price)as "Total_sales" from titles group by type select type,max(Total_sales) from sen_v1 41 max(Total_sales) from sen_v1) group by type,Total_sales having Total_sales= (select select type from sen_vl where Total_sales = (select max(Total_sales) from sen_v1)

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)] as sql statements;

[ ]--->optional

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, it checks the existence of the column, if it is, the procudure will be created...if the column does not 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 compilation process is done.. select object_id (’demo’); // we can get the table id what the sql server maintains... create procedure pro(parameters) with recompile as 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 execute the procedure another time, it will no go for compilation process,it just checks the procedure cache and execute suitable obj file....If the system is gone for shut down, the contents of the procedure cache will be deleted....Whatever changes made in table contents, it will re-complile. if the table is dropped,the procedure for the table will not be deleted... 42

////////////////////////////////////////////////////////////////////////////////////////////// 18-January-2002:

Query -

Page #17

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

43

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 as goto a a: 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 One 2. One to Many 3. Many to Many

44

Query -

Page #19

{Chen notation} [Entity] [Relation] Employee---------- Works In |[Rect] [Diamond] | |-------has --------Address [Diamond] [Rect]

[Entity] ----------------Dept [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] and one 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 d1 e2 d1 d2 e3 d2 d3 e4 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] Professor -------------[Entity](0,1)

[Diamond] [Rect] is allotted -----------Room [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) TheatreFilm45(Associative Entity) or Junction Table -----------------------------------------------------------------------------------------tid (pk) fid (pk) tid tname fname fid

Query no_seats location

Page #20 hero heroine

composite primary key(tid,fid)

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 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 informatio Atomic values: A field should record about the single attribute... For example: To store address,we have to put street,city,state,country as a separate field names. Then only possible to search the employees by city,state or country.....

(*) The field names shoud accept null values, if the no specefic info for that recor and take to consideration the table should not have more null value fields. Example: 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 may depend on other non key attributes...

primary key or all the non key attributes

In the above table, the department id is partially belonging to the primary key,which means that the emp itself only need to identify the department id and the project id is no longer needed...

*In order conform second normal form,we have take out the non key attribute which does not depend entril the primary key and put it separate table along with the field on which the non key attribute is depen so we take off did from the above table eid did --------e1 IS e2 IS e3 NET 24 NET

46

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

Query -

Page #21

pid nohrs ----------p1 20 p2 30 ( It is in third normal form,we can not split it again) The dehead is not related to eid or pid...it is related to did.....so put dhead following table 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 th did 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 delete any enty in the master table,which is refered by in the child table...The SQL server maintains restrictions automatically...The cascade deletions is opposite of these restrictions.... Syntax: 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 after trigger,The SQL could not support Before Triggers..... Trigger can not accept parameters..... Book Magazine ---------------------------Bid Magid Bname Mname Author price

47

Query -

Page #22

Transaction -------------Tid Card_id book_id issue_date return_date -------------------------------------------------------------------------------------------------Implementing primary key constraint:Create trigger tri on temp for insert as declare @icount int select @icount=count(*) from temp,inserted where temp pk = insert pk if @icount >1 begin print ’Duplicate Record’ rollback end else print ’Successfully on inserting the record’ inserted--->trigger test table (or) magic table ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on emp for insert as if not exists(select * from dept,inserted where dept.did=inserted.did) begin print "Integrity violation" rollback; end else print "successfull insertion into the table" emp inserted ---------------------------------------------------e1 boris d1 d1 HRD e2 becker d2 d2 SYS e3 sapeg d3 ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on trans_member for insert as if 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’ end else print ’Successfully inserted into the table’ ------------------------------------------------------------------------------------------------Note: While creating trigger,the object should be exist on which the trigger imposed...but it 48 does not check the body of the statements.... ------------------------------------------------------------------------------------------------Implementing Cascade Deletion:-

Query -

Page #23

Create trigger dtri on publishers for delete as delete 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 dtri on publishers for delete as if exists( select * from titles,deleted where titles.pub_id=deleted.pub_id) begin print ’Attempt to create orphan Records’ rollback end -----------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables????? Hits provided: declare @i int select @i=Object_id(’publishers’) if exists(select * from sysobjects where id=@i) insert back_up select * from deleted -----------------------------------------------------------------------------------------------31-JAN-2002: customers invoice products ---------------------------------------------cid oid pid cname cid pname pid qoh (quantity in hand) qty price create trigger tri on invoice for insert as update products set qoh=qoh-inserted.qty from products,inserted where products.pid=inserted.pid checking the availability of products: --------------------------------------select @iqty = inserted.qty from inserted select @qty = products.qty from inserted,products where inserted.pid=products.pid if(@qty<@iqty) begin print "invalid transaction" rollback return end ------------------------------------------------------------------------------------------Note: The rollback command will only work on triggers it will not work on procedures.... -------------------------------------------------------------------------------------------49 Note: Through the delete and update command will affect many rows.., the trigger will be executed for each row... --------------------------------------------------------------------------------------------create trigger tri

Query -

Page #24

on invoice for update if update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback return end if not exists (select * from products,inserted where inserted.productid=products.proudctid begin print ’Fk violation on products’ rollback return end -------------------------------------------------------------------------------------------Note: For update triggers, the inserted and deleted virutal table will be created.... deleted followed by inserted................... -------------------------------------------------------------------------------------------TSQL Cursors: The main application of cursors is ’report’ generation.......... The cursor contains following five ’jargons’ 1....Declare 2....Open 3....Fetch 4....Close 5....Deallocate A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’.. 1...Declare: Syntax: Declare cursorname cursor for select statement // 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

50

Query -

Page #25

declare cur cursor scroll for select * from sen_catlog open cur fetch next from cur while(@@fetch_status=0) begin fetch next from cur end close cur deallocate cur exec sen_cur_pro; Note: @@fetch_status is system defined global variable which is automatically set to 0 which indicates for successful fetch... -----------------------------------------------------------------------------------------------1-02-2002: Application of Cursors: Create procedure sen_cpro as declare @tid varchar(20),@title varchar(20),@price float declare cur cursor scroll for select title_id,title,price from titles open cur fetch next from cur into @tid,@title,@price while(@@fetch_status=0) begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@price end close cur deallocate 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 as set nocount on declare @pid varchar(20),@pname varchar(20) declare @tid varchar(20),@title varchar(20),@price float declare @n int declare cur cursor scroll for select pub_id,pub_name from publishers open cur fetch next from cur into @pid,@pname while(@@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) 51 begin print @tid + " " + @title + " " + convert(varchar,@price) fetch next from tcur into @tid,@title,@price end

Query -

Page #26 close tcur deallocate tcur

end print ’------------------------------------------------’ fetch next from cur into @pid,@pname end close cur deallocate cur

exec sen_publisher_books --------------------------------------------------------------------------------------------------------2-Feb-2002: Indexing: It is a sorting process to reduce the searching process time.... Syntax: Create { nonClustered } index index_name on table_name(field_name) Default is Clustered indexing................ ------------------------------------------------------------------------------------------------NonClustered: create nonclustered index emp_eno on 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 or it is feasible for going for table scan...... -------------------------------------------------------------------------------------------------Note: Primary key creates Clustered automaically but to make it nonClustered index is more feasible than Clustered index -------------------------------------------------------------------------------------------Clustered: create clustered index emp_eno on 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 of record... 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 ------------------------------------------------------------------------------------------------

52

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 53

CREATE TABLE _TEMP ( empno int,

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;

54

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 d 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 TITLES GROUP BY TYPE,PUB_ID; SELECT * FROM TITLES ORDER BY TYPE DESC; ////////////////////////////////////////////////////////////////////////////////////////// select type,sum(price) from titles group by type order by title_id; When ever use an order by class along with group by class the order by class should have only those filels which are present in the group by class. ///////////////////////////////////////////////////////////////////////////////////////////// select type,title_id,sum(price) from titles group by type order by title_id; // Error select type,title_id,sum(price) from titles group by type,title_id order by title_id; select * from titles;

55

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 titles order 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 itself able to generate Work Table...So the Compute by class relay order by class... select type,price from titles order by pub_id compute sum(price) by type; // Error Reason: The work table is built based on pub_id...In that work Table,we can’t find the sum of price by Type...’ select type,pub_id,price from titles order by type,pub_id compute sum(price) by type; select type,pub_id,price from titles order by type,pub_id compute sum(price) by pub_id; // Error Reason: Work Table Type pub_id Price -------------------------Business p1 200 Business p1 200 Business p2 300 Computer p2 400

56

Query -

Page #5

Computer Novel Novel Novel

p2 p1 p1 p2

200 200 240 450

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

select type,pub_id,price from titles order by type,pub_id compute sum(price) by type,pub_id; select type,pub_id,title_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id,title_id; select type,pub_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id; **************************************************** Afternoon:21-dec-2001 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 titles group 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 apply for a particular column. It will apply all the columns in the select list For Ex Business Business Business Computer Computer

p1 p1 p1 p2 p2

200 400 300 500 700

The Result is Business Computer

p1 p2

200 500

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

57

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

Query -

Page #6

////////////////////////////////////////////////////////// Having: Having clause should have group by class...but when using group by class it is optional to use Having clause. 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 // 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select type,sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 ///////////////////////////////////////////////////////////////////////////////////////////////// December-26-2001 Joins:

58

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

Query -

Page #7

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

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

// authors.* displays all fields in the Authors Table

Natural join: The redundat field names are eliminated in the Result

set

join Equi Join : The Redundat field names are present in the result set. Table Alias: select p.*,au_id,au_lname from authors, publishers p where authors.city=p.city; select p.*,au_id,au_lname from authors a, publishers p where a.city = p.city and a.au_lname like ’c%’ select p.*,au_id,au_lname from authors a, publishers p where au_lname like ’c%’ and a.city = p.city Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select select select select

* * * *

from from from from

authors; publishers; titles; 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: .................

59

Query -

Page #8

Explanation: Title: Authors au_id ----------a1 a2

au_lname ---------------------------lockley peter

Table: Publisher pub_id -----p1 p2 p3

pub_name ----------samy golgotia samba

Table: Titles title_id -------t1 t2 t3

pub_id -------p1 p2 p3

Table: TitleAuthor au_id title_id ----------- -------a1 t1 a1 t2 a2 t1 a2 t3 Virtual Tables: [Authors] aid aname a1 lockey a1 lockey

[TitleAuthor] au_id title_id a1 t1 a1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[titles] title_id t1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[ titles ] [ publisher] title_id pub_id pub_id pub_name t1 p1 p1 sams t2 p2 p2 golgotia

pub_id p1 p2

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 60 in the optimized way....

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

Query -

Page #9

Ans:

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

Cross Checking: select select select select

* * * *

from from from from

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

//////////////////////////////////////////////////////////////////////////////////////////////// Renaming the Tables sp_rename //////////////////////////////////////////////////////////////////////////////////////////////// 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 A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

au_id A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

Result set would be A1 A6 A2 A3 61

select a.au_id,a.city from authors a, authors b where a.city = b.city;

// It displays duplicate Records

Query -

Page #10

select state,count(*) from authors group by state having count(*)>1 // We should not use group by function in the self joining situations select distinct a.au_id,a.city from authors a, authors b where a.city = b.city; // It displays distinct records but it dispalys one author lives in the city select distinct a.au_id,a.city from authors a, authors b where a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered... select distinct a.au_id,a.city from authors a, authors b where 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 62 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???

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 e2 e3 e4 e5

boris becker peter Anderw Lafer

HRD HRD SYS SYS null

dep HRD SYS PER NET

Human Res Systems personal network

emp eno ename d_id dept ddid dname Display the emp details along with dept id?? select emp.* d.did from emp e,dept d where e.did=d.did REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS select emp.*,d.did from e,dept d where e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax) REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS e5 lafer

63

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

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 ] /////////////////////////////////////////////////////////////////////////////////////////////// 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 because the 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 q 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

64

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

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 b where 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_fname from authors a where exists ( select b.au_id from authors b where a.state = b.state and a.au_id <> b.au_id ); // This is correlated sub query 1.It has join. 2.The left or right side field name is oute The correlated sub query executed for every outer table row...but simple sub query executed only once...

It takes one record from the outer condition for that row all the rows of the inner codition will be exec If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct the correlated sub query.

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 wou 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; // if u want to include the duplicates use Union all keyword...

It will not give the duplicates of the re

select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ select price,title from titles union all select title_id,au_id from titleauthor; // Error

data type mis

Note: The order by statements can not be used in the individual query inside the union but group by and having is allowed. But order by allowed in the outside of the union . Example:

select title_id,title from titles union all select title_id,au_id from titleauthor o Note: The field name in the first select statement is allowed in the order by clause. we can not use group by clause in the order by place....

--------------------------------------------------------------------------------------------------------Self-Interest: Find total purchase for each customer?????????? Ans: drop vi create view v_sample as select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p 65 where o.proid=p.pid group by o.cuid select max(tprice) from v_sample

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 User Grant All Table_name to User Revoke select|update|insert|delete on Table_name from User Revoke 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_empdat as select eid,ename,did,dname from emp,dept where emp.did = dept.did; Grant select on v_empdat to sa Step 1: create view sen_view_v1 as select * from titles where title_id=’BU1111’ Step 2: select * from sen_view_v1; // The select statement inside the view will be executed.... delete sen_view_v1; 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 as select pub_id,sum(price) from titles group by pub_id; // The above statement would not work. Here the sum(price) is tried to derive a new column in the view To make work the above statement.... create select (or) create select

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

Query -

Page #15

////////////////////////////////////////////////////////////////////////////////////////////// Rule: 1. We can not use order by,compute by,compute in the selection list while creating views. 2. We can not use ’Select into’ on views. 3. We can use order by indirectly. ////////////////////////////////////////////////////////////////////////////////////////////// create table emp ( empno varchar(20) emp_name varchar(20) salary float dept_id varchar(20) phone varchar(20) );

not not not not not

null, null, null, null, null

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

will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olny it is possible insert,update,delete, If the view does not contain all not null columns, it is only readable veiw.We can not do insert,delete,update... Rule 2: If the select list in the view contains aggregate functions,the view is readable view... 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 as select * from emp where dept_id = ’HRD’; select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS find whether it is table or view...if it is view, it executes the select statement with where condition. And the statement looks like below.... 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 interpreted as 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 has been created by with check option condition. It allow only the where clause condition is match, it means that we can insert only ’HRD’ type...... ///////////////////////////////////////////////////////////////////////////////////////////////// Question: Find which type sales is greater??? We can not write in single select statement.... create view sen_v1 as

67

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)] as sql statements;

[ ]--->optional

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, it checks the existence of the column, if it is, the procudure will be created...if the column does not 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 compilation process is done.. select object_id (’demo’); // we can get the table id what the sql server maintains... create procedure pro(parameters) with recompile as 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 68 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 execute the procedure another time, it will no go for compilation process,it just checks the procedure

Query -

Page #17

cache and execute suitable obj file....If the system is gone for shut down, the contents of the procedure cache will be deleted....Whatever changes made in table contents, it will re-complile. if the table is dropped,the procedure for the table will not be deleted... ////////////////////////////////////////////////////////////////////////////////////////////// 18-January-2002:

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

Example

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 as goto a a: print "dgs" ------------------------------------------------------------------------------------------------21-January-2002: E-R Diagram: Entity:

70

The entity is an object about information can be recorded..

Query -

Page #19

For example, the employee and dept entity has some relationship between them... The are 3 different types of relationship.... 1. One to One 2. One to Many 3. Many to Many {Chen notation} [Entity] [Relation] Employee---------- Works In |[Rect] [Diamond] | |-------has --------Address [Diamond] [Rect]

[Entity] ----------------Dept [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] and one 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 d1 e2 d1 d2 e3 d2 d3 e4 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] Professor -------------[Entity](0,1)

[Diamond] [Rect] is allotted -----------Room [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) 71

one theatre can show many films [ one to Many left to rigth ] one film is shown in many theatres [ one to Many right to left ]

Query -

Page #20

The oracle and sql server can not support for many to many relationship....For these cases we have to split the relationship into two one to many relationship... 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 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 informatio Atomic values: A field should record about the single attribute... For example: To store address,we have to put street,city,state,country as a separate field names. Then only possible to search the employees by city,state or country.....

(*) The field names shoud accept null values, if the no specefic info for that recor and take to consideration the table should not have more null value fields. Example: 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 may depend on other non key attributes...

primary key or all the non key attributes

In the above table, the department id is partially belonging to the primary key,which means that the emp itself only need to identify the department id and the project id is no longer needed...

*In order conform second normal form,we have take out the non key attribute which does not depend entril the primary key and put it separate table along with the field on which the non key attribute is depen so we take off did from the above table eid did ---------

72

Query e1 e2 e3 24

Page #21 IS IS NET 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 th did 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 delete any enty in the master table,which is refered by in the child table...The SQL server maintains restrictions automatically...The cascade deletions is opposite of these restrictions.... Syntax: 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... 73 Trigger,Delete Trigger) These are all after only three types of triggers ( Insert Trigger,Update trigger,The SQL could not support Before Triggers..... Trigger can not accept parameters.....

Query -

Page #22

Book Magazine ---------------------------Bid Magid Bname Mname Author price Transaction -------------Tid Card_id book_id issue_date return_date -------------------------------------------------------------------------------------------------Implementing primary key constraint:Create trigger tri on temp for insert as declare @icount int select @icount=count(*) from temp,inserted where temp pk = insert pk if @icount >1 begin print ’Duplicate Record’ rollback end else print ’Successfully on inserting the record’ inserted--->trigger test table (or) magic table ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on emp for insert as if not exists(select * from dept,inserted where dept.did=inserted.did) begin print "Integrity violation" rollback; end else print "successfull insertion into the table" emp inserted ---------------------------------------------------e1 boris d1 d1 HRD e2 becker d2 d2 SYS e3 sapeg d3 ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on trans_member for insert as if 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’ 74 end else print ’Successfully inserted into the table’

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 dtri on publishers for delete as delete 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 dtri on publishers for delete as if exists( select * from titles,deleted where titles.pub_id=deleted.pub_id) begin print ’Attempt to create orphan Records’ rollback end -----------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables????? Hits provided: declare @i int select @i=Object_id(’publishers’) if exists(select * from sysobjects where id=@i) insert back_up select * from deleted -----------------------------------------------------------------------------------------------31-JAN-2002: customers invoice products ---------------------------------------------cid oid pid cname cid pname pid qoh (quantity in hand) qty price create trigger tri on invoice for insert as update products set qoh=qoh-inserted.qty from products,inserted where products.pid=inserted.pid checking the availability of products: --------------------------------------select @iqty = inserted.qty from inserted select @qty = products.qty from inserted,products where inserted.pid=products.pid if(@qty<@iqty) begin print "invalid transaction" rollback return end

75

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 invoice for update if update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback return end if not exists (select * from products,inserted where inserted.productid=products.proudctid begin print ’Fk violation on products’ rollback return end -------------------------------------------------------------------------------------------Note: For update triggers, the inserted and deleted virutal table will be created.... deleted followed by inserted................... -------------------------------------------------------------------------------------------TSQL Cursors: The main application of cursors is ’report’ generation.......... The cursor contains following five ’jargons’ 1....Declare 2....Open 3....Fetch 4....Close 5....Deallocate A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’.. 1...Declare: Syntax: Declare cursorname cursor for select statement // 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..... 76 ------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Query -

Page #25

Note: It destroies the cursor [ like dropping tables ] ------------------------------------------------------------------------------------------------Example with procedure:create procedure sen_cur_pro as declare cur cursor scroll for select * from sen_catlog open cur fetch next from cur while(@@fetch_status=0) begin fetch next from cur end close cur deallocate cur exec sen_cur_pro; Note: @@fetch_status is system defined global variable which is automatically set to 0 which indicates for successful fetch... -----------------------------------------------------------------------------------------------1-02-2002: Application of Cursors: Create procedure sen_cpro as declare @tid varchar(20),@title varchar(20),@price float declare cur cursor scroll for select title_id,title,price from titles open cur fetch next from cur into @tid,@title,@price while(@@fetch_status=0) begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@price end close cur deallocate 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 as set nocount on declare @pid varchar(20),@pname varchar(20) declare @tid varchar(20),@title varchar(20),@price float declare @n int declare cur cursor scroll for select pub_id,pub_name from publishers open cur fetch next from cur into @pid,@pname while(@@fetch_status=0) begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ 77 else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid

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,@pname end close cur deallocate cur

exec sen_publisher_books --------------------------------------------------------------------------------------------------------2-Feb-2002: Indexing: It is a sorting process to reduce the searching process time.... Syntax: Create { nonClustered } index index_name on table_name(field_name) Default is Clustered indexing................ ------------------------------------------------------------------------------------------------NonClustered: create nonclustered index emp_eno on 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 or it is feasible for going for table scan...... -------------------------------------------------------------------------------------------------Note: Primary key creates Clustered automaically but to make it nonClustered index is more feasible than Clustered index -------------------------------------------------------------------------------------------Clustered: create clustered index emp_eno on 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 of record... 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 ------------------------------------------------------------------------------------------------

78

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 79

CREATE TABLE _TEMP ( empno int,

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;

80

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 d 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 TITLES GROUP BY TYPE,PUB_ID; SELECT * FROM TITLES ORDER BY TYPE DESC; ////////////////////////////////////////////////////////////////////////////////////////// select type,sum(price) from titles group by type order by title_id; When ever use an order by class along with group by class the order by class should have only those filels which are present in the group by class. ///////////////////////////////////////////////////////////////////////////////////////////// select type,title_id,sum(price) from titles group by type order by title_id; // Error select type,title_id,sum(price) from titles group by type,title_id order by title_id; select * from titles;

81

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 titles order 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 itself able to generate Work Table...So the Compute by class relay order by class... select type,price from titles order by pub_id compute sum(price) by type; // Error Reason: The work table is built based on pub_id...In that work Table,we can’t find the sum of price by Type...’ select type,pub_id,price from titles order by type,pub_id compute sum(price) by type; select type,pub_id,price from titles order by type,pub_id compute sum(price) by pub_id; // Error Reason: Work Table Type pub_id Price -------------------------Business p1 200 Business p1 200 Business p2 300 Computer p2 400

82

Query -

Page #5

Computer Novel Novel Novel

p2 p1 p1 p2

200 200 240 450

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

select type,pub_id,price from titles order by type,pub_id compute sum(price) by type,pub_id; select type,pub_id,title_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id,title_id; select type,pub_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id; **************************************************** Afternoon:21-dec-2001 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 titles group 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 apply for a particular column. It will apply all the columns in the select list For Ex Business Business Business Computer Computer

p1 p1 p1 p2 p2

200 400 300 500 700

The Result is Business Computer

p1 p2

200 500

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

83

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

Query -

Page #6

////////////////////////////////////////////////////////// Having: Having clause should have group by class...but when using group by class it is optional to use Having clause. 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 // 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select type,sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 ///////////////////////////////////////////////////////////////////////////////////////////////// December-26-2001 Joins:

84

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

Query -

Page #7

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

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

// authors.* displays all fields in the Authors Table

Natural join: The redundat field names are eliminated in the Result

set

join Equi Join : The Redundat field names are present in the result set. Table Alias: select p.*,au_id,au_lname from authors, publishers p where authors.city=p.city; select p.*,au_id,au_lname from authors a, publishers p where a.city = p.city and a.au_lname like ’c%’ select p.*,au_id,au_lname from authors a, publishers p where au_lname like ’c%’ and a.city = p.city Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select select select select

* * * *

from from from from

authors; publishers; titles; 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: .................

85

Query -

Page #8

Explanation: Title: Authors au_id ----------a1 a2

au_lname ---------------------------lockley peter

Table: Publisher pub_id -----p1 p2 p3

pub_name ----------samy golgotia samba

Table: Titles title_id -------t1 t2 t3

pub_id -------p1 p2 p3

Table: TitleAuthor au_id title_id ----------- -------a1 t1 a1 t2 a2 t1 a2 t3 Virtual Tables: [Authors] aid aname a1 lockey a1 lockey

[TitleAuthor] au_id title_id a1 t1 a1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[titles] title_id t1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[ titles ] [ publisher] title_id pub_id pub_id pub_name t1 p1 p1 sams t2 p2 p2 golgotia

pub_id p1 p2

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 86 in the optimized way....

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

Query -

Page #9

Ans:

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

Cross Checking: select select select select

* * * *

from from from from

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

//////////////////////////////////////////////////////////////////////////////////////////////// Renaming the Tables sp_rename //////////////////////////////////////////////////////////////////////////////////////////////// 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 A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

au_id A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

Result set would be A1 A6 A2 A3 87

select a.au_id,a.city from authors a, authors b where a.city = b.city;

// It displays duplicate Records

Query -

Page #10

select state,count(*) from authors group by state having count(*)>1 // We should not use group by function in the self joining situations select distinct a.au_id,a.city from authors a, authors b where a.city = b.city; // It displays distinct records but it dispalys one author lives in the city select distinct a.au_id,a.city from authors a, authors b where a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered... select distinct a.au_id,a.city from authors a, authors b where 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 88 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???

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 e2 e3 e4 e5

boris becker peter Anderw Lafer

HRD HRD SYS SYS null

dep HRD SYS PER NET

Human Res Systems personal network

emp eno ename d_id dept ddid dname Display the emp details along with dept id?? select emp.* d.did from emp e,dept d where e.did=d.did REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS select emp.*,d.did from e,dept d where e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax) REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS e5 lafer

89

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

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 ] /////////////////////////////////////////////////////////////////////////////////////////////// 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 because the 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 q 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

90

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

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 b where 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_fname from authors a where exists ( select b.au_id from authors b where a.state = b.state and a.au_id <> b.au_id ); // This is correlated sub query 1.It has join. 2.The left or right side field name is oute The correlated sub query executed for every outer table row...but simple sub query executed only once...

It takes one record from the outer condition for that row all the rows of the inner codition will be exec If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct the correlated sub query.

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 wou 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; // if u want to include the duplicates use Union all keyword...

It will not give the duplicates of the re

select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ select price,title from titles union all select title_id,au_id from titleauthor; // Error

data type mis

Note: The order by statements can not be used in the individual query inside the union but group by and having is allowed. But order by allowed in the outside of the union . Example:

select title_id,title from titles union all select title_id,au_id from titleauthor o Note: The field name in the first select statement is allowed in the order by clause. we can not use group by clause in the order by place....

--------------------------------------------------------------------------------------------------------Self-Interest: Find total purchase for each customer?????????? Ans: drop vi create view v_sample as select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p 91 where o.proid=p.pid group by o.cuid select max(tprice) from v_sample

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 User Grant All Table_name to User Revoke select|update|insert|delete on Table_name from User Revoke 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_empdat as select eid,ename,did,dname from emp,dept where emp.did = dept.did; Grant select on v_empdat to sa Step 1: create view sen_view_v1 as select * from titles where title_id=’BU1111’ Step 2: select * from sen_view_v1; // The select statement inside the view will be executed.... delete sen_view_v1; 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 as select pub_id,sum(price) from titles group by pub_id; // The above statement would not work. Here the sum(price) is tried to derive a new column in the view To make work the above statement.... create select (or) create select

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

Query -

Page #15

////////////////////////////////////////////////////////////////////////////////////////////// Rule: 1. We can not use order by,compute by,compute in the selection list while creating views. 2. We can not use ’Select into’ on views. 3. We can use order by indirectly. ////////////////////////////////////////////////////////////////////////////////////////////// create table emp ( empno varchar(20) emp_name varchar(20) salary float dept_id varchar(20) phone varchar(20) );

not not not not not

null, null, null, null, null

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

will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olny it is possible insert,update,delete, If the view does not contain all not null columns, it is only readable veiw.We can not do insert,delete,update... Rule 2: If the select list in the view contains aggregate functions,the view is readable view... 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 as select * from emp where dept_id = ’HRD’; select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS find whether it is table or view...if it is view, it executes the select statement with where condition. And the statement looks like below.... 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 interpreted as 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 has been created by with check option condition. It allow only the where clause condition is match, it means that we can insert only ’HRD’ type...... ///////////////////////////////////////////////////////////////////////////////////////////////// Question: Find which type sales is greater??? We can not write in single select statement.... create view sen_v1 as

93

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)] as sql statements;

[ ]--->optional

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, it checks the existence of the column, if it is, the procudure will be created...if the column does not 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 compilation process is done.. select object_id (’demo’); // we can get the table id what the sql server maintains... create procedure pro(parameters) with recompile as 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 94 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 execute the procedure another time, it will no go for compilation process,it just checks the procedure

Query -

Page #17

cache and execute suitable obj file....If the system is gone for shut down, the contents of the procedure cache will be deleted....Whatever changes made in table contents, it will re-complile. if the table is dropped,the procedure for the table will not be deleted... ////////////////////////////////////////////////////////////////////////////////////////////// 18-January-2002:

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

Example

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 as goto a a: print "dgs" ------------------------------------------------------------------------------------------------21-January-2002: E-R Diagram: Entity:

96

The entity is an object about information can be recorded..

Query -

Page #19

For example, the employee and dept entity has some relationship between them... The are 3 different types of relationship.... 1. One to One 2. One to Many 3. Many to Many {Chen notation} [Entity] [Relation] Employee---------- Works In |[Rect] [Diamond] | |-------has --------Address [Diamond] [Rect]

[Entity] ----------------Dept [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] and one 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 d1 e2 d1 d2 e3 d2 d3 e4 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] Professor -------------[Entity](0,1)

[Diamond] [Rect] is allotted -----------Room [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) 97

one theatre can show many films [ one to Many left to rigth ] one film is shown in many theatres [ one to Many right to left ]

Query -

Page #20

The oracle and sql server can not support for many to many relationship....For these cases we have to split the relationship into two one to many relationship... 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 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 informatio Atomic values: A field should record about the single attribute... For example: To store address,we have to put street,city,state,country as a separate field names. Then only possible to search the employees by city,state or country.....

(*) The field names shoud accept null values, if the no specefic info for that recor and take to consideration the table should not have more null value fields. Example: 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 may depend on other non key attributes...

primary key or all the non key attributes

In the above table, the department id is partially belonging to the primary key,which means that the emp itself only need to identify the department id and the project id is no longer needed...

*In order conform second normal form,we have take out the non key attribute which does not depend entril the primary key and put it separate table along with the field on which the non key attribute is depen so we take off did from the above table eid did ---------

98

Query e1 e2 e3 24

Page #21 IS IS NET 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 th did 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 delete any enty in the master table,which is refered by in the child table...The SQL server maintains restrictions automatically...The cascade deletions is opposite of these restrictions.... Syntax: 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... 99 Trigger,Delete Trigger) These are all after only three types of triggers ( Insert Trigger,Update trigger,The SQL could not support Before Triggers..... Trigger can not accept parameters.....

Query -

Page #22

Book Magazine ---------------------------Bid Magid Bname Mname Author price Transaction -------------Tid Card_id book_id issue_date return_date -------------------------------------------------------------------------------------------------Implementing primary key constraint:Create trigger tri on temp for insert as declare @icount int select @icount=count(*) from temp,inserted where temp pk = insert pk if @icount >1 begin print ’Duplicate Record’ rollback end else print ’Successfully on inserting the record’ inserted--->trigger test table (or) magic table ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on emp for insert as if not exists(select * from dept,inserted where dept.did=inserted.did) begin print "Integrity violation" rollback; end else print "successfull insertion into the table" emp inserted ---------------------------------------------------e1 boris d1 d1 HRD e2 becker d2 d2 SYS e3 sapeg d3 ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on trans_member for insert as if 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’ 100 end else print ’Successfully inserted into the table’

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 dtri on publishers for delete as delete 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 dtri on publishers for delete as if exists( select * from titles,deleted where titles.pub_id=deleted.pub_id) begin print ’Attempt to create orphan Records’ rollback end -----------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables????? Hits provided: declare @i int select @i=Object_id(’publishers’) if exists(select * from sysobjects where id=@i) insert back_up select * from deleted -----------------------------------------------------------------------------------------------31-JAN-2002: customers invoice products ---------------------------------------------cid oid pid cname cid pname pid qoh (quantity in hand) qty price create trigger tri on invoice for insert as update products set qoh=qoh-inserted.qty from products,inserted where products.pid=inserted.pid checking the availability of products: --------------------------------------select @iqty = inserted.qty from inserted select @qty = products.qty from inserted,products where inserted.pid=products.pid if(@qty<@iqty) begin print "invalid transaction" 101 rollback return end

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 invoice for update if update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback return end if not exists (select * from products,inserted where inserted.productid=products.proudctid begin print ’Fk violation on products’ rollback return end -------------------------------------------------------------------------------------------Note: For update triggers, the inserted and deleted virutal table will be created.... deleted followed by inserted................... -------------------------------------------------------------------------------------------TSQL Cursors: The main application of cursors is ’report’ generation.......... The cursor contains following five ’jargons’ 1....Declare 2....Open 3....Fetch 4....Close 5....Deallocate A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’.. 1...Declare: Syntax: Declare cursorname cursor for select statement // 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..... 102 ------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Query -

Page #25

Note: It destroies the cursor [ like dropping tables ] ------------------------------------------------------------------------------------------------Example with procedure:create procedure sen_cur_pro as declare cur cursor scroll for select * from sen_catlog open cur fetch next from cur while(@@fetch_status=0) begin fetch next from cur end close cur deallocate cur exec sen_cur_pro; Note: @@fetch_status is system defined global variable which is automatically set to 0 which indicates for successful fetch... -----------------------------------------------------------------------------------------------1-02-2002: Application of Cursors: Create procedure sen_cpro as declare @tid varchar(20),@title varchar(20),@price float declare cur cursor scroll for select title_id,title,price from titles open cur fetch next from cur into @tid,@title,@price while(@@fetch_status=0) begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@price end close cur deallocate 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 as set nocount on declare @pid varchar(20),@pname varchar(20) declare @tid varchar(20),@title varchar(20),@price float declare @n int declare cur cursor scroll for select pub_id,pub_name from publishers open cur fetch next from cur into @pid,@pname while(@@fetch_status=0) begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ 103 else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid

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,@pname end close cur deallocate cur

exec sen_publisher_books --------------------------------------------------------------------------------------------------------2-Feb-2002: Indexing: It is a sorting process to reduce the searching process time.... Syntax: Create { nonClustered } index index_name on table_name(field_name) Default is Clustered indexing................ ------------------------------------------------------------------------------------------------NonClustered: create nonclustered index emp_eno on 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 or it is feasible for going for table scan...... -------------------------------------------------------------------------------------------------Note: Primary key creates Clustered automaically but to make it nonClustered index is more feasible than Clustered index -------------------------------------------------------------------------------------------Clustered: create clustered index emp_eno on 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 of record... 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 ------------------------------------------------------------------------------------------------

104

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 105

CREATE TABLE _TEMP ( empno int,

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;

106

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 d 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 TITLES GROUP BY TYPE,PUB_ID; SELECT * FROM TITLES ORDER BY TYPE DESC; ////////////////////////////////////////////////////////////////////////////////////////// select type,sum(price) from titles group by type order by title_id; When ever use an order by class along with group by class the order by class should have only those filels which are present in the group by class. ///////////////////////////////////////////////////////////////////////////////////////////// select type,title_id,sum(price) from titles group by type order by title_id; // Error select type,title_id,sum(price) from titles group by type,title_id order by title_id; select * from titles;

107

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 titles order 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 itself able to generate Work Table...So the Compute by class relay order by class... select type,price from titles order by pub_id compute sum(price) by type; // Error Reason: The work table is built based on pub_id...In that work Table,we can’t find the sum of price by Type...’ select type,pub_id,price from titles order by type,pub_id compute sum(price) by type; select type,pub_id,price from titles order by type,pub_id compute sum(price) by pub_id; // Error Reason: Work Table Type pub_id Price -------------------------Business p1 200 Business p1 200 Business p2 300 Computer p2 400

108

Query -

Page #5

Computer Novel Novel Novel

p2 p1 p1 p2

200 200 240 450

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

select type,pub_id,price from titles order by type,pub_id compute sum(price) by type,pub_id; select type,pub_id,title_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id,title_id; select type,pub_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id; **************************************************** Afternoon:21-dec-2001 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 titles group 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 apply for a particular column. It will apply all the columns in the select list For Ex Business Business Business Computer Computer

p1 p1 p1 p2 p2

200 400 300 500 700

The Result is Business Computer

p1 p2

200 500

///////////////////////////////////////////////// select type,sum(price),avg(price) from titles 109 group by price; // Error Reason: The field name in group by clause which is not used in aggregate function in select list

Query -

Page #6

////////////////////////////////////////////////////////// Having: Having clause should have group by class...but when using group by class it is optional to use Having clause. 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 // 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select type,sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 ///////////////////////////////////////////////////////////////////////////////////////////////// December-26-2001 Joins:

110

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

Query -

Page #7

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

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

// authors.* displays all fields in the Authors Table

Natural join: The redundat field names are eliminated in the Result

set

join Equi Join : The Redundat field names are present in the result set. Table Alias: select p.*,au_id,au_lname from authors, publishers p where authors.city=p.city; select p.*,au_id,au_lname from authors a, publishers p where a.city = p.city and a.au_lname like ’c%’ select p.*,au_id,au_lname from authors a, publishers p where au_lname like ’c%’ and a.city = p.city Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select select select select

* * * *

from from from from

authors; publishers; titles; 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: .................

111

Query -

Page #8

Explanation: Title: Authors au_id ----------a1 a2

au_lname ---------------------------lockley peter

Table: Publisher pub_id -----p1 p2 p3

pub_name ----------samy golgotia samba

Table: Titles title_id -------t1 t2 t3

pub_id -------p1 p2 p3

Table: TitleAuthor au_id title_id ----------- -------a1 t1 a1 t2 a2 t1 a2 t3 Virtual Tables: [Authors] aid aname a1 lockey a1 lockey

[TitleAuthor] au_id title_id a1 t1 a1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[titles] title_id t1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[ titles ] [ publisher] title_id pub_id pub_id pub_name t1 p1 p1 sams t2 p2 p2 golgotia

pub_id p1 p2

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 112 in the optimized way....

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

Query -

Page #9

Ans:

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

Cross Checking: select select select select

* * * *

from from from from

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

//////////////////////////////////////////////////////////////////////////////////////////////// Renaming the Tables sp_rename //////////////////////////////////////////////////////////////////////////////////////////////// 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 A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

au_id A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

Result set would be A1 A6 A2 A3 113

select a.au_id,a.city from authors a, authors b where a.city = b.city;

// It displays duplicate Records

Query -

Page #10

select state,count(*) from authors group by state having count(*)>1 // We should not use group by function in the self joining situations select distinct a.au_id,a.city from authors a, authors b where a.city = b.city; // It displays distinct records but it dispalys one author lives in the city select distinct a.au_id,a.city from authors a, authors b where a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered... select distinct a.au_id,a.city from authors a, authors b where 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 114 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???

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 e2 e3 e4 e5

boris becker peter Anderw Lafer

HRD HRD SYS SYS null

dep HRD SYS PER NET

Human Res Systems personal network

emp eno ename d_id dept ddid dname Display the emp details along with dept id?? select emp.* d.did from emp e,dept d where e.did=d.did REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS select emp.*,d.did from e,dept d where e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax) REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS e5 lafer

115

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

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 ] /////////////////////////////////////////////////////////////////////////////////////////////// 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 because the 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 q 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

116

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

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 b where 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_fname from authors a where exists ( select b.au_id from authors b where a.state = b.state and a.au_id <> b.au_id ); // This is correlated sub query 1.It has join. 2.The left or right side field name is oute The correlated sub query executed for every outer table row...but simple sub query executed only once...

It takes one record from the outer condition for that row all the rows of the inner codition will be exec If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct the correlated sub query.

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 wou 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; // if u want to include the duplicates use Union all keyword...

It will not give the duplicates of the re

select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ select price,title from titles union all select title_id,au_id from titleauthor; // Error

data type mis

Note: The order by statements can not be used in the individual query inside the union but group by and having is allowed. But order by allowed in the outside of the union . Example:

select title_id,title from titles union all select title_id,au_id from titleauthor o Note: The field name in the first select statement is allowed in the order by clause. we can not use group by clause in the order by place....

--------------------------------------------------------------------------------------------------------Self-Interest: Find total purchase for each customer?????????? Ans: drop vi create view v_sample as select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p 117 where o.proid=p.pid group by o.cuid select max(tprice) from v_sample

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 User Grant All Table_name to User Revoke select|update|insert|delete on Table_name from User Revoke 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_empdat as select eid,ename,did,dname from emp,dept where emp.did = dept.did; Grant select on v_empdat to sa Step 1: create view sen_view_v1 as select * from titles where title_id=’BU1111’ Step 2: select * from sen_view_v1; // The select statement inside the view will be executed.... delete sen_view_v1; 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 as select pub_id,sum(price) from titles group by pub_id; // The above statement would not work. Here the sum(price) is tried to derive a new column in the view To make work the above statement.... create select (or) create select

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

Query -

Page #15

////////////////////////////////////////////////////////////////////////////////////////////// Rule: 1. We can not use order by,compute by,compute in the selection list while creating views. 2. We can not use ’Select into’ on views. 3. We can use order by indirectly. ////////////////////////////////////////////////////////////////////////////////////////////// create table emp ( empno varchar(20) emp_name varchar(20) salary float dept_id varchar(20) phone varchar(20) );

not not not not not

null, null, null, null, null

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

will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olny it is possible insert,update,delete, If the view does not contain all not null columns, it is only readable veiw.We can not do insert,delete,update... Rule 2: If the select list in the view contains aggregate functions,the view is readable view... 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 as select * from emp where dept_id = ’HRD’; select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS find whether it is table or view...if it is view, it executes the select statement with where condition. And the statement looks like below.... 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 interpreted as 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 has been created by with check option condition. It allow only the where clause condition is match, it means that we can insert only ’HRD’ type...... ///////////////////////////////////////////////////////////////////////////////////////////////// Question: Find which type sales is greater??? We can not write in single select statement.... create view sen_v1 as

119

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)] as sql statements;

[ ]--->optional

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, it checks the existence of the column, if it is, the procudure will be created...if the column does not 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 compilation process is done.. select object_id (’demo’); // we can get the table id what the sql server maintains... create procedure pro(parameters) with recompile as 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 120 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 execute the procedure another time, it will no go for compilation process,it just checks the procedure

Query -

Page #17

cache and execute suitable obj file....If the system is gone for shut down, the contents of the procedure cache will be deleted....Whatever changes made in table contents, it will re-complile. if the table is dropped,the procedure for the table will not be deleted... ////////////////////////////////////////////////////////////////////////////////////////////// 18-January-2002:

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

Example

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 as goto a a: print "dgs" ------------------------------------------------------------------------------------------------21-January-2002: E-R Diagram: Entity:

122

The entity is an object about information can be recorded..

Query -

Page #19

For example, the employee and dept entity has some relationship between them... The are 3 different types of relationship.... 1. One to One 2. One to Many 3. Many to Many {Chen notation} [Entity] [Relation] Employee---------- Works In |[Rect] [Diamond] | |-------has --------Address [Diamond] [Rect]

[Entity] ----------------Dept [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] and one 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 d1 e2 d1 d2 e3 d2 d3 e4 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] Professor -------------[Entity](0,1)

[Diamond] [Rect] is allotted -----------Room [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) 123

one theatre can show many films [ one to Many left to rigth ] one film is shown in many theatres [ one to Many right to left ]

Query -

Page #20

The oracle and sql server can not support for many to many relationship....For these cases we have to split the relationship into two one to many relationship... 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 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 informatio Atomic values: A field should record about the single attribute... For example: To store address,we have to put street,city,state,country as a separate field names. Then only possible to search the employees by city,state or country.....

(*) The field names shoud accept null values, if the no specefic info for that recor and take to consideration the table should not have more null value fields. Example: 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 may depend on other non key attributes...

primary key or all the non key attributes

In the above table, the department id is partially belonging to the primary key,which means that the emp itself only need to identify the department id and the project id is no longer needed...

*In order conform second normal form,we have take out the non key attribute which does not depend entril the primary key and put it separate table along with the field on which the non key attribute is depen so we take off did from the above table eid did ---------

124

Query e1 e2 e3 24

Page #21 IS IS NET 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 th did 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 delete any enty in the master table,which is refered by in the child table...The SQL server maintains restrictions automatically...The cascade deletions is opposite of these restrictions.... Syntax: 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... 125 Trigger,Delete Trigger) These are all after only three types of triggers ( Insert Trigger,Update trigger,The SQL could not support Before Triggers..... Trigger can not accept parameters.....

Query -

Page #22

Book Magazine ---------------------------Bid Magid Bname Mname Author price Transaction -------------Tid Card_id book_id issue_date return_date -------------------------------------------------------------------------------------------------Implementing primary key constraint:Create trigger tri on temp for insert as declare @icount int select @icount=count(*) from temp,inserted where temp pk = insert pk if @icount >1 begin print ’Duplicate Record’ rollback end else print ’Successfully on inserting the record’ inserted--->trigger test table (or) magic table ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on emp for insert as if not exists(select * from dept,inserted where dept.did=inserted.did) begin print "Integrity violation" rollback; end else print "successfull insertion into the table" emp inserted ---------------------------------------------------e1 boris d1 d1 HRD e2 becker d2 d2 SYS e3 sapeg d3 ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on trans_member for insert as if 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’ 126 end else print ’Successfully inserted into the table’

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 dtri on publishers for delete as delete 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 dtri on publishers for delete as if exists( select * from titles,deleted where titles.pub_id=deleted.pub_id) begin print ’Attempt to create orphan Records’ rollback end -----------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables????? Hits provided: declare @i int select @i=Object_id(’publishers’) if exists(select * from sysobjects where id=@i) insert back_up select * from deleted -----------------------------------------------------------------------------------------------31-JAN-2002: customers invoice products ---------------------------------------------cid oid pid cname cid pname pid qoh (quantity in hand) qty price create trigger tri on invoice for insert as update products set qoh=qoh-inserted.qty from products,inserted where products.pid=inserted.pid checking the availability of products: --------------------------------------select @iqty = inserted.qty from inserted select @qty = products.qty from inserted,products where inserted.pid=products.pid if(@qty<@iqty) begin print "invalid transaction" 127 rollback return end

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 invoice for update if update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback return end if not exists (select * from products,inserted where inserted.productid=products.proudctid begin print ’Fk violation on products’ rollback return end -------------------------------------------------------------------------------------------Note: For update triggers, the inserted and deleted virutal table will be created.... deleted followed by inserted................... -------------------------------------------------------------------------------------------TSQL Cursors: The main application of cursors is ’report’ generation.......... The cursor contains following five ’jargons’ 1....Declare 2....Open 3....Fetch 4....Close 5....Deallocate A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’.. 1...Declare: Syntax: Declare cursorname cursor for select statement // 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..... 128 ------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Query -

Page #25

Note: It destroies the cursor [ like dropping tables ] ------------------------------------------------------------------------------------------------Example with procedure:create procedure sen_cur_pro as declare cur cursor scroll for select * from sen_catlog open cur fetch next from cur while(@@fetch_status=0) begin fetch next from cur end close cur deallocate cur exec sen_cur_pro; Note: @@fetch_status is system defined global variable which is automatically set to 0 which indicates for successful fetch... -----------------------------------------------------------------------------------------------1-02-2002: Application of Cursors: Create procedure sen_cpro as declare @tid varchar(20),@title varchar(20),@price float declare cur cursor scroll for select title_id,title,price from titles open cur fetch next from cur into @tid,@title,@price while(@@fetch_status=0) begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@price end close cur deallocate 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 as set nocount on declare @pid varchar(20),@pname varchar(20) declare @tid varchar(20),@title varchar(20),@price float declare @n int declare cur cursor scroll for select pub_id,pub_name from publishers open cur fetch next from cur into @pid,@pname while(@@fetch_status=0) begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ 129 else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid

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,@pname end close cur deallocate cur

exec sen_publisher_books --------------------------------------------------------------------------------------------------------2-Feb-2002: Indexing: It is a sorting process to reduce the searching process time.... Syntax: Create { nonClustered } index index_name on table_name(field_name) Default is Clustered indexing................ ------------------------------------------------------------------------------------------------NonClustered: create nonclustered index emp_eno on 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 or it is feasible for going for table scan...... -------------------------------------------------------------------------------------------------Note: Primary key creates Clustered automaically but to make it nonClustered index is more feasible than Clustered index -------------------------------------------------------------------------------------------Clustered: create clustered index emp_eno on 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 of record... 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 ------------------------------------------------------------------------------------------------

130

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 131

CREATE TABLE _TEMP ( empno int,

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;

132

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 d 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 TITLES GROUP BY TYPE,PUB_ID; SELECT * FROM TITLES ORDER BY TYPE DESC; ////////////////////////////////////////////////////////////////////////////////////////// select type,sum(price) from titles group by type order by title_id; When ever use an order by class along with group by class the order by class should have only those filels which are present in the group by class. ///////////////////////////////////////////////////////////////////////////////////////////// select type,title_id,sum(price) from titles group by type order by title_id; // Error select type,title_id,sum(price) from titles group by type,title_id order by title_id; select * from titles;

133

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 titles order 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 itself able to generate Work Table...So the Compute by class relay order by class... select type,price from titles order by pub_id compute sum(price) by type; // Error Reason: The work table is built based on pub_id...In that work Table,we can’t find the sum of price by Type...’ select type,pub_id,price from titles order by type,pub_id compute sum(price) by type; select type,pub_id,price from titles order by type,pub_id compute sum(price) by pub_id; // Error Reason: Work Table Type pub_id Price -------------------------Business p1 200 Business p1 200 Business p2 300 Computer p2 400

134

Query -

Page #5

Computer Novel Novel Novel

p2 p1 p1 p2

200 200 240 450

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

select type,pub_id,price from titles order by type,pub_id compute sum(price) by type,pub_id; select type,pub_id,title_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id,title_id; select type,pub_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id; **************************************************** Afternoon:21-dec-2001 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 titles group 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 apply for a particular column. It will apply all the columns in the select list For Ex Business Business Business Computer Computer

p1 p1 p1 p2 p2

200 400 300 500 700

The Result is Business Computer

p1 p2

200 500

///////////////////////////////////////////////// select type,sum(price),avg(price) from titles 135 group by price; // Error Reason: The field name in group by clause which is not used in aggregate function in select list

Query -

Page #6

////////////////////////////////////////////////////////// Having: Having clause should have group by class...but when using group by class it is optional to use Having clause. 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 // 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select type,sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 ///////////////////////////////////////////////////////////////////////////////////////////////// December-26-2001 Joins:

136

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

Query -

Page #7

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

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

// authors.* displays all fields in the Authors Table

Natural join: The redundat field names are eliminated in the Result

set

join Equi Join : The Redundat field names are present in the result set. Table Alias: select p.*,au_id,au_lname from authors, publishers p where authors.city=p.city; select p.*,au_id,au_lname from authors a, publishers p where a.city = p.city and a.au_lname like ’c%’ select p.*,au_id,au_lname from authors a, publishers p where au_lname like ’c%’ and a.city = p.city Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select select select select

* * * *

from from from from

authors; publishers; titles; 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: .................

137

Query -

Page #8

Explanation: Title: Authors au_id ----------a1 a2

au_lname ---------------------------lockley peter

Table: Publisher pub_id -----p1 p2 p3

pub_name ----------samy golgotia samba

Table: Titles title_id -------t1 t2 t3

pub_id -------p1 p2 p3

Table: TitleAuthor au_id title_id ----------- -------a1 t1 a1 t2 a2 t1 a2 t3 Virtual Tables: [Authors] aid aname a1 lockey a1 lockey

[TitleAuthor] au_id title_id a1 t1 a1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[titles] title_id t1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[ titles ] [ publisher] title_id pub_id pub_id pub_name t1 p1 p1 sams t2 p2 p2 golgotia

pub_id p1 p2

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 138 in the optimized way....

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

Query -

Page #9

Ans:

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

Cross Checking: select select select select

* * * *

from from from from

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

//////////////////////////////////////////////////////////////////////////////////////////////// Renaming the Tables sp_rename //////////////////////////////////////////////////////////////////////////////////////////////// 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 A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

au_id A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

Result set would be A1 A6 A2 A3 139

select a.au_id,a.city from authors a, authors b where a.city = b.city;

// It displays duplicate Records

Query -

Page #10

select state,count(*) from authors group by state having count(*)>1 // We should not use group by function in the self joining situations select distinct a.au_id,a.city from authors a, authors b where a.city = b.city; // It displays distinct records but it dispalys one author lives in the city select distinct a.au_id,a.city from authors a, authors b where a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered... select distinct a.au_id,a.city from authors a, authors b where 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 140 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???

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 e2 e3 e4 e5

boris becker peter Anderw Lafer

HRD HRD SYS SYS null

dep HRD SYS PER NET

Human Res Systems personal network

emp eno ename d_id dept ddid dname Display the emp details along with dept id?? select emp.* d.did from emp e,dept d where e.did=d.did REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS select emp.*,d.did from e,dept d where e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax) REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS e5 lafer

141

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

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 ] /////////////////////////////////////////////////////////////////////////////////////////////// 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 because the 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 q 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

142

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

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 b where 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_fname from authors a where exists ( select b.au_id from authors b where a.state = b.state and a.au_id <> b.au_id ); // This is correlated sub query 1.It has join. 2.The left or right side field name is oute The correlated sub query executed for every outer table row...but simple sub query executed only once...

It takes one record from the outer condition for that row all the rows of the inner codition will be exec If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct the correlated sub query.

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 wou 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; // if u want to include the duplicates use Union all keyword...

It will not give the duplicates of the re

select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ select price,title from titles union all select title_id,au_id from titleauthor; // Error

data type mis

Note: The order by statements can not be used in the individual query inside the union but group by and having is allowed. But order by allowed in the outside of the union . Example:

select title_id,title from titles union all select title_id,au_id from titleauthor o Note: The field name in the first select statement is allowed in the order by clause. we can not use group by clause in the order by place....

--------------------------------------------------------------------------------------------------------Self-Interest: Find total purchase for each customer?????????? Ans: drop vi create view v_sample as select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p 143 where o.proid=p.pid group by o.cuid select max(tprice) from v_sample

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 User Grant All Table_name to User Revoke select|update|insert|delete on Table_name from User Revoke 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_empdat as select eid,ename,did,dname from emp,dept where emp.did = dept.did; Grant select on v_empdat to sa Step 1: create view sen_view_v1 as select * from titles where title_id=’BU1111’ Step 2: select * from sen_view_v1; // The select statement inside the view will be executed.... delete sen_view_v1; 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 as select pub_id,sum(price) from titles group by pub_id; // The above statement would not work. Here the sum(price) is tried to derive a new column in the view To make work the above statement.... create select (or) create select

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

Query -

Page #15

////////////////////////////////////////////////////////////////////////////////////////////// Rule: 1. We can not use order by,compute by,compute in the selection list while creating views. 2. We can not use ’Select into’ on views. 3. We can use order by indirectly. ////////////////////////////////////////////////////////////////////////////////////////////// create table emp ( empno varchar(20) emp_name varchar(20) salary float dept_id varchar(20) phone varchar(20) );

not not not not not

null, null, null, null, null

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

will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olny it is possible insert,update,delete, If the view does not contain all not null columns, it is only readable veiw.We can not do insert,delete,update... Rule 2: If the select list in the view contains aggregate functions,the view is readable view... 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 as select * from emp where dept_id = ’HRD’; select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS find whether it is table or view...if it is view, it executes the select statement with where condition. And the statement looks like below.... 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 interpreted as 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 has been created by with check option condition. It allow only the where clause condition is match, it means that we can insert only ’HRD’ type...... ///////////////////////////////////////////////////////////////////////////////////////////////// Question: Find which type sales is greater??? We can not write in single select statement.... create view sen_v1 as

145

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)] as sql statements;

[ ]--->optional

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, it checks the existence of the column, if it is, the procudure will be created...if the column does not 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 compilation process is done.. select object_id (’demo’); // we can get the table id what the sql server maintains... create procedure pro(parameters) with recompile as 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 146 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 execute the procedure another time, it will no go for compilation process,it just checks the procedure

Query -

Page #17

cache and execute suitable obj file....If the system is gone for shut down, the contents of the procedure cache will be deleted....Whatever changes made in table contents, it will re-complile. if the table is dropped,the procedure for the table will not be deleted... ////////////////////////////////////////////////////////////////////////////////////////////// 18-January-2002:

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

Example

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 as goto a a: print "dgs" ------------------------------------------------------------------------------------------------21-January-2002: E-R Diagram: Entity:

148

The entity is an object about information can be recorded..

Query -

Page #19

For example, the employee and dept entity has some relationship between them... The are 3 different types of relationship.... 1. One to One 2. One to Many 3. Many to Many {Chen notation} [Entity] [Relation] Employee---------- Works In |[Rect] [Diamond] | |-------has --------Address [Diamond] [Rect]

[Entity] ----------------Dept [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] and one 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 d1 e2 d1 d2 e3 d2 d3 e4 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] Professor -------------[Entity](0,1)

[Diamond] [Rect] is allotted -----------Room [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) 149

one theatre can show many films [ one to Many left to rigth ] one film is shown in many theatres [ one to Many right to left ]

Query -

Page #20

The oracle and sql server can not support for many to many relationship....For these cases we have to split the relationship into two one to many relationship... 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 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 informatio Atomic values: A field should record about the single attribute... For example: To store address,we have to put street,city,state,country as a separate field names. Then only possible to search the employees by city,state or country.....

(*) The field names shoud accept null values, if the no specefic info for that recor and take to consideration the table should not have more null value fields. Example: 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 may depend on other non key attributes...

primary key or all the non key attributes

In the above table, the department id is partially belonging to the primary key,which means that the emp itself only need to identify the department id and the project id is no longer needed...

*In order conform second normal form,we have take out the non key attribute which does not depend entril the primary key and put it separate table along with the field on which the non key attribute is depen so we take off did from the above table eid did ---------

150

Query e1 e2 e3 24

Page #21 IS IS NET 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 th did 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 delete any enty in the master table,which is refered by in the child table...The SQL server maintains restrictions automatically...The cascade deletions is opposite of these restrictions.... Syntax: 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... 151 Trigger,Delete Trigger) These are all after only three types of triggers ( Insert Trigger,Update trigger,The SQL could not support Before Triggers..... Trigger can not accept parameters.....

Query -

Page #22

Book Magazine ---------------------------Bid Magid Bname Mname Author price Transaction -------------Tid Card_id book_id issue_date return_date -------------------------------------------------------------------------------------------------Implementing primary key constraint:Create trigger tri on temp for insert as declare @icount int select @icount=count(*) from temp,inserted where temp pk = insert pk if @icount >1 begin print ’Duplicate Record’ rollback end else print ’Successfully on inserting the record’ inserted--->trigger test table (or) magic table ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on emp for insert as if not exists(select * from dept,inserted where dept.did=inserted.did) begin print "Integrity violation" rollback; end else print "successfull insertion into the table" emp inserted ---------------------------------------------------e1 boris d1 d1 HRD e2 becker d2 d2 SYS e3 sapeg d3 ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on trans_member for insert as if 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’ 152 end else print ’Successfully inserted into the table’

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 dtri on publishers for delete as delete 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 dtri on publishers for delete as if exists( select * from titles,deleted where titles.pub_id=deleted.pub_id) begin print ’Attempt to create orphan Records’ rollback end -----------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables????? Hits provided: declare @i int select @i=Object_id(’publishers’) if exists(select * from sysobjects where id=@i) insert back_up select * from deleted -----------------------------------------------------------------------------------------------31-JAN-2002: customers invoice products ---------------------------------------------cid oid pid cname cid pname pid qoh (quantity in hand) qty price create trigger tri on invoice for insert as update products set qoh=qoh-inserted.qty from products,inserted where products.pid=inserted.pid checking the availability of products: --------------------------------------select @iqty = inserted.qty from inserted select @qty = products.qty from inserted,products where inserted.pid=products.pid if(@qty<@iqty) begin print "invalid transaction" 153 rollback return end

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 invoice for update if update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback return end if not exists (select * from products,inserted where inserted.productid=products.proudctid begin print ’Fk violation on products’ rollback return end -------------------------------------------------------------------------------------------Note: For update triggers, the inserted and deleted virutal table will be created.... deleted followed by inserted................... -------------------------------------------------------------------------------------------TSQL Cursors: The main application of cursors is ’report’ generation.......... The cursor contains following five ’jargons’ 1....Declare 2....Open 3....Fetch 4....Close 5....Deallocate A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’.. 1...Declare: Syntax: Declare cursorname cursor for select statement // 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..... 154 ------------------------------------------------------------------------------------------------5.....Deallocate: deallocate cur;

Query -

Page #25

Note: It destroies the cursor [ like dropping tables ] ------------------------------------------------------------------------------------------------Example with procedure:create procedure sen_cur_pro as declare cur cursor scroll for select * from sen_catlog open cur fetch next from cur while(@@fetch_status=0) begin fetch next from cur end close cur deallocate cur exec sen_cur_pro; Note: @@fetch_status is system defined global variable which is automatically set to 0 which indicates for successful fetch... -----------------------------------------------------------------------------------------------1-02-2002: Application of Cursors: Create procedure sen_cpro as declare @tid varchar(20),@title varchar(20),@price float declare cur cursor scroll for select title_id,title,price from titles open cur fetch next from cur into @tid,@title,@price while(@@fetch_status=0) begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@price end close cur deallocate 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 as set nocount on declare @pid varchar(20),@pname varchar(20) declare @tid varchar(20),@title varchar(20),@price float declare @n int declare cur cursor scroll for select pub_id,pub_name from publishers open cur fetch next from cur into @pid,@pname while(@@fetch_status=0) begin print @pid+ " " + @pname print ’------------------------------------------------’ select @n=count(*) from titles where pub_id=@pid if(@n =0) print ’*****No books found********’ 155 else begin declare tcur cursor for select title_id,title,price from titles where pub_id=@pid

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,@pname end close cur deallocate cur

exec sen_publisher_books --------------------------------------------------------------------------------------------------------2-Feb-2002: Indexing: It is a sorting process to reduce the searching process time.... Syntax: Create { nonClustered } index index_name on table_name(field_name) Default is Clustered indexing................ ------------------------------------------------------------------------------------------------NonClustered: create nonclustered index emp_eno on 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 or it is feasible for going for table scan...... -------------------------------------------------------------------------------------------------Note: Primary key creates Clustered automaically but to make it nonClustered index is more feasible than Clustered index -------------------------------------------------------------------------------------------Clustered: create clustered index emp_eno on 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 of record... 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 ------------------------------------------------------------------------------------------------

156

Query -

Page #1

-----------------------------------------------------------------------------------------------LIBRARY -----------------------------------------------------------------------------------------------Project Specification: Altair is a library renowned for its latest collection of books and magazines.The number of members is increasing every month and it is becoming difficult to keep track of so many members and transactions,which are currently maintained in registers. The chief librarian approaches you to seek help for designing a computerized system. All members in the library are given two member cards and one book is leased for each card. The membership fee for each member is Rs 500. One time payment,refundable on relinquishing of the cards.Both books and megazines are leased to the members.A book lent to a member can be with him for 15 days at most and an extension of another 15 days is given to the member for that particular book if that book is brought for renewal on the 15 th day after it is lent.The same member is not allowed to have the book for another 15 days after it is returned.Magazines are lent only for 4 days and no extension is allowed and there is no restriction for lending the magazine to the same member,as is the case with books. You need to store the book details for each book ( publisher name,title,author and the like ). Each book is identified by a unique title number.Magazines are identified in the following format. Each magazine has a short hand notation (Eg. otlk for the magazine outlook) To identify a particular magazine the short hand notation is used along with the month and year of issue Eg. otlk-jan-1999 identifies Outlook magazine jan issue of 1999. You need to store the number of copies of each book that is there in the library. One copy of each book is designated as reference and it is not lent to any member. ------------------------------------------------------------------------------------------------Create Table sen_catlog ( c_id varchar(10) constraint sc_pk primary key, title varchar(20), author varchar(20), publisher varchar(20), price float ); 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, ); 157

insert into sen_catlog values(’CB001’,’C’,’Dennis Ritche’,’Tech Media’,140.25); insert into sen_catlog values(’CB002’,’C++’,’Robert Rafore’,’BPB Publication’,356.90); insert into sen_catlog values(’CB003’,’JAVA’,’Balaguru swamy’,’Tech Media’,230);

Query -

Page #2

select * from sen_catlog; insert insert insert insert insert insert insert insert

into into into into into into into into

sen_books sen_books sen_books sen_books sen_books sen_books sen_books sen_books

values values values values values values values values

(’B001’,’CB001’,’issue’); (’B002’,’CB001’,’issue’); (’B003’,’CB001’,’reference’); (’B004’,’CB002’,’issue’); (’B005’,’CB002’,’issue’); (’B006’,’CB002’,’Reference’); (’B007’,’CB003’,’issue’); (’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 insert insert insert insert

into into into into into

sen_cards sen_cards sen_cards sen_cards sen_cards

values(’C001’,’M001’); values(’C002’,’M001’); values(’C003’,’M002’); values(’C004’,’M002’); values(’C005’,’M003’);

select * from sen_cards; insert insert insert insert insert insert insert

into into into into into into into

select select select select select

* * * * *

sen_transaction sen_transaction sen_transaction sen_transaction sen_transaction sen_transaction sen_transaction

from from from from from

values values values values values values values

(’T001’,’B001’,’C001’,’12-10-2000’,null,null); (’T002’,’B002’,’C002’,’11-11-2000’,’11-25-2000’,null); (’T003’,’B004’,’C004’,’10-10-2000’,’10-25-2000’,1); (’T004’,’B004’,’C004’,’09-27-2000’,’10-10-2000’,0); (’T006’,’B002’,’C003’,’01-28-2000’,null,0); (’T007’,’B004’,’C002’,’01-28-2000’,’02-10-2000’,0); (’T008’,’B005’,’C005’,’01-28-2000’,null,0);

sen_catlog; sen_books; sen_member; sen_cards; 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_tr 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 158 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

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 i create procedure sen_books_details as declare @c varchar(10) declare @n int declare @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) as declare @n int declare @i int declare @b varchar(10) declare @c varchar(10) declare @r datetime declare @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=@ddate if(@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 + " end end

" + @t_card + "

" + @t_title + "

" + @t_bid + " " + @message

159

exec sen_book_delevered @ddate=’2000-01-28’; ----------------------------------------------------------------------------------------------4.On any particular day you will have to display as report those books for which due date has

Query -

Page #4

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) 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) 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<@dday if(@n=0) print ’No Over due books on that day’ else begin select b_id,card_id into #temp from sen_transaction where rdate is null and tdate<@dday select @i = 1 while(@i<=@n) begin select top 1 @b=b_id,@c=card_id from #temp select distinct @t_title=c.title,@t_bid=b.b_id from sen_catlog c,sen_books b,sen_transaction t where t.b_id=@b and t.b_id=b.b_id and b.c_id = c.c_id select distinct @t_name=m.mname,@t_card=c.card_id from sen_transaction t,sen_cards c,sen_member m where t.card_id=@c and t.card_id=c.card_id and c.m_id=m.m_id delete from #temp where card_id=@c and b_id=@b select @i=@i+1 print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid end end exec sen_overdue_books @date=’2000-02-25’ -------------------------------------------------------------------------------------------------

160

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,

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;

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 d 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 TITLES GROUP BY TYPE,PUB_ID; SELECT * FROM TITLES ORDER BY TYPE DESC; ////////////////////////////////////////////////////////////////////////////////////////// select type,sum(price) from titles group by type order by title_id; When ever use an order by class along with group by class the order by class should have only those filels which are present in the group by class. ///////////////////////////////////////////////////////////////////////////////////////////// select type,title_id,sum(price) from titles group by type order by title_id; // Error select type,title_id,sum(price) from titles group by type,title_id order by title_id; select * from titles;

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 titles order 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 itself able to generate Work Table...So the Compute by class relay order by class... select type,price from titles order by pub_id compute sum(price) by type; // Error Reason: The work table is built based on pub_id...In that work Table,we can’t find the sum of price by Type...’ select type,pub_id,price from titles order by type,pub_id compute sum(price) by type; select type,pub_id,price from titles order by type,pub_id compute sum(price) by pub_id; // Error Reason: Work Table Type pub_id Price -------------------------Business p1 200 Business p1 200 Business p2 300 Computer p2 400

Query -

Page #5

Computer Novel Novel Novel

p2 p1 p1 p2

200 200 240 450

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

select type,pub_id,price from titles order by type,pub_id compute sum(price) by type,pub_id; select type,pub_id,title_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id,title_id; select type,pub_id,price from titles order by type,pub_id,title_id compute sum(price) by type,pub_id; **************************************************** Afternoon:21-dec-2001 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 titles group 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 apply for a particular column. It will apply all the columns in the select list For Ex Business Business Business Computer Computer

p1 p1 p1 p2 p2

200 400 300 500 700

The Result is Business Computer

p1 p2

200 500

///////////////////////////////////////////////// select type,sum(price),avg(price) from titles group by price; // Error Reason: The field name in group by clause which is not used in aggregate function in select list

Query -

Page #6

////////////////////////////////////////////////////////// Having: Having clause should have group by class...but when using group by class it is optional to use Having clause. 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 // 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 titles where sum(price) > 1000 group by type; // Error Rule 1 and 2 select type,sum(price) from titles where 1000<sum(price) group by type; // Error Rule 2 ///////////////////////////////////////////////////////////////////////////////////////////////// December-26-2001 Joins: select * from authors,publishers; // It does the cartisean product of two tables....

Query -

Page #7

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

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

// authors.* displays all fields in the Authors Table

Natural join: The redundat field names are eliminated in the Result

set

join Equi Join : The Redundat field names are present in the result set. Table Alias: select p.*,au_id,au_lname from authors, publishers p where authors.city=p.city; select p.*,au_id,au_lname from authors a, publishers p where a.city = p.city and a.au_lname like ’c%’ select p.*,au_id,au_lname from authors a, publishers p where au_lname like ’c%’ and a.city = p.city Question: Find the publisher name for the book written by the author with fname ’Lorsley’ select select select select

* * * *

from from from from

authors; publishers; titles; 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: .................

Query -

Page #8

Explanation: Title: Authors au_id ----------a1 a2

au_lname ---------------------------lockley peter

Table: Publisher pub_id -----p1 p2 p3

pub_name ----------samy golgotia samba

Table: Titles title_id -------t1 t2 t3

pub_id -------p1 p2 p3

Table: TitleAuthor au_id title_id ----------- -------a1 t1 a1 t2 a2 t1 a2 t3 Virtual Tables: [Authors] aid aname a1 lockey a1 lockey

[TitleAuthor] au_id title_id a1 t1 a1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[titles] title_id t1 t2

[authors] aid aname a1 lockey a1 lockey

[titleAuthor] aid title_id a1 t1 a1 t2

[ titles ] [ publisher] title_id pub_id pub_id pub_name t1 p1 p1 sams t2 p2 p2 golgotia

pub_id p1 p2

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

Query -

Page #9

Ans:

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

Cross Checking: select select select select

* * * *

from from from from

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

//////////////////////////////////////////////////////////////////////////////////////////////// Renaming the Tables sp_rename //////////////////////////////////////////////////////////////////////////////////////////////// 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 A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

au_id A1 A2 A3 A4 A5 A6

city CA LA LA WA Ny CA

Result set would be A1 A6 A2 A3 select a.au_id,a.city from authors a, authors b where a.city = b.city;

// It displays duplicate Records

Query -

Page #10

select state,count(*) from authors group by state having count(*)>1 // We should not use group by function in the self joining situations select distinct a.au_id,a.city from authors a, authors b where a.city = b.city; // It displays distinct records but it dispalys one author lives in the city select distinct a.au_id,a.city from authors a, authors b where a.city = b.city and a.au_id <> b.au_id; // It displays result but not ordered... select distinct a.au_id,a.city from authors a, authors b where 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???

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 e2 e3 e4 e5

boris becker peter Anderw Lafer

HRD HRD SYS SYS null

dep HRD SYS PER NET

Human Res Systems personal network

emp eno ename d_id dept ddid dname Display the emp details along with dept id?? select emp.* d.did from emp e,dept d where e.did=d.did REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS select emp.*,d.did from e,dept d where e.did *=d.did; // Display the matching records and addition to all unmatching records form emp (SQL Server Syntax) REsult Set e1 boris HRD e2 becker HRD e3 peter SYS e4 Andrew SYS e5 lafer select emp.*,d.did from e,dept d where e.did =* d.did; // Display the matching records and addition to all

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 ] /////////////////////////////////////////////////////////////////////////////////////////////// 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 because the 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 q 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.

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 b where 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_fname from authors a where exists ( select b.au_id from authors b where a.state = b.state and a.au_id <> b.au_id ); // This is correlated sub query 1.It has join. 2.The left or right side field name is oute The correlated sub query executed for every outer table row...but simple sub query executed only once...

It takes one record from the outer condition for that row all the rows of the inner codition will be exec If the inner condition becomes true, the inner condition will be terminated..so we need not use distinct the correlated sub query.

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 wou 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; // if u want to include the duplicates use Union all keyword...

It will not give the duplicates of the re

select * from authors union all select * from titleauthor; // Error Equal no of fields and same data typ select price,title from titles union all select title_id,au_id from titleauthor; // Error

data type mis

Note: The order by statements can not be used in the individual query inside the union but group by and having is allowed. But order by allowed in the outside of the union . Example:

select title_id,title from titles union all select title_id,au_id from titleauthor o Note: The field name in the first select statement is allowed in the order by clause. we can not use group by clause in the order by place....

--------------------------------------------------------------------------------------------------------Self-Interest: Find total purchase for each customer?????????? Ans: drop vi create view v_sample as select o.cuid as cid,sum(o.qty * p.price) as tprice from orders o, produ p where o.proid=p.pid group by o.cuid select max(tprice) from v_sample

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 User Grant All Table_name to User Revoke select|update|insert|delete on Table_name from User Revoke 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_empdat as select eid,ename,did,dname from emp,dept where emp.did = dept.did; Grant select on v_empdat to sa Step 1: create view sen_view_v1 as select * from titles where title_id=’BU1111’ Step 2: select * from sen_view_v1; // The select statement inside the view will be executed.... delete sen_view_v1; 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 as select pub_id,sum(price) from titles group by pub_id; // The above statement would not work. Here the sum(price) is tried to derive a new column in the view To make work the above statement.... create select (or) create select

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

Query -

Page #15

////////////////////////////////////////////////////////////////////////////////////////////// Rule: 1. We can not use order by,compute by,compute in the selection list while creating views. 2. We can not use ’Select into’ on views. 3. We can use order by indirectly. ////////////////////////////////////////////////////////////////////////////////////////////// create table emp ( empno varchar(20) emp_name varchar(20) salary float dept_id varchar(20) phone varchar(20) );

not not not not not

null, null, null, null, null

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

will work

Rule 1: The view has to contain all not null columns,[it will become updateable view] then olny it is possible insert,update,delete, If the view does not contain all not null columns, it is only readable veiw.We can not do insert,delete,update... Rule 2: If the select list in the view contains aggregate functions,the view is readable view... 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 as select * from emp where dept_id = ’HRD’; select * from v_emp where sal>2500; // It display only the type ’HRD’. Internally it check in SYSOBJECTS find whether it is table or view...if it is view, it executes the select statement with where condition. And the statement looks like below.... 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 interpreted as 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 has been created by with check option condition. It allow only the where clause condition is match, it means that we can insert only ’HRD’ type...... ///////////////////////////////////////////////////////////////////////////////////////////////// Question: Find which type sales is greater??? We can not write in single select statement.... create view sen_v1 as

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)] as sql statements;

[ ]--->optional

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, it checks the existence of the column, if it is, the procudure will be created...if the column does not 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 compilation process is done.. select object_id (’demo’); // we can get the table id what the sql server maintains... create procedure pro(parameters) with recompile as 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 execute the procedure another time, it will no go for compilation process,it just checks the procedure

Query -

Page #17

cache and execute suitable obj file....If the system is gone for shut down, the contents of the procedure cache will be deleted....Whatever changes made in table contents, it will re-complile. if the table is dropped,the procedure for the table will not be deleted... ////////////////////////////////////////////////////////////////////////////////////////////// 18-January-2002:

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

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 as goto a a: print "dgs" ------------------------------------------------------------------------------------------------21-January-2002: E-R Diagram: Entity: The entity is an object about information can be recorded..

Query -

Page #19

For example, the employee and dept entity has some relationship between them... The are 3 different types of relationship.... 1. One to One 2. One to Many 3. Many to Many {Chen notation} [Entity] [Relation] Employee---------- Works In |[Rect] [Diamond] | |-------has --------Address [Diamond] [Rect]

[Entity] ----------------Dept [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] and one 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 d1 e2 d1 d2 e3 d2 d3 e4 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] Professor -------------[Entity](0,1)

[Diamond] [Rect] is allotted -----------Room [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 ]

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 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 informatio Atomic values: A field should record about the single attribute... For example: To store address,we have to put street,city,state,country as a separate field names. Then only possible to search the employees by city,state or country.....

(*) The field names shoud accept null values, if the no specefic info for that recor and take to consideration the table should not have more null value fields. Example: 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 may depend on other non key attributes...

primary key or all the non key attributes

In the above table, the department id is partially belonging to the primary key,which means that the emp itself only need to identify the department id and the project id is no longer needed...

*In order conform second normal form,we have take out the non key attribute which does not depend entril the primary key and put it separate table along with the field on which the non key attribute is depen so we take off did from the above table eid did ---------

Query e1 e2 e3 24

Page #21 IS IS NET 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 th did 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 delete any enty in the master table,which is refered by in the child table...The SQL server maintains restrictions automatically...The cascade deletions is opposite of these restrictions.... Syntax: 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 after trigger,The SQL could not support Before Triggers..... Trigger can not accept parameters.....

Query -

Page #22

Book Magazine ---------------------------Bid Magid Bname Mname Author price Transaction -------------Tid Card_id book_id issue_date return_date -------------------------------------------------------------------------------------------------Implementing primary key constraint:Create trigger tri on temp for insert as declare @icount int select @icount=count(*) from temp,inserted where temp pk = insert pk if @icount >1 begin print ’Duplicate Record’ rollback end else print ’Successfully on inserting the record’ inserted--->trigger test table (or) magic table ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on emp for insert as if not exists(select * from dept,inserted where dept.did=inserted.did) begin print "Integrity violation" rollback; end else print "successfull insertion into the table" emp inserted ---------------------------------------------------e1 boris d1 d1 HRD e2 becker d2 d2 SYS e3 sapeg d3 ------------------------------------------------------------------------------------------------Implementing foreign key constraint:create trigger tri on trans_member for insert as if 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’ end else print ’Successfully inserted into the table’

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 dtri on publishers for delete as delete 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 dtri on publishers for delete as if exists( select * from titles,deleted where titles.pub_id=deleted.pub_id) begin print ’Attempt to create orphan Records’ rollback end -----------------------------------------------------------------------------------------------Question: Create a trigger to move the deleted records to that respective back_up tables????? Hits provided: declare @i int select @i=Object_id(’publishers’) if exists(select * from sysobjects where id=@i) insert back_up select * from deleted -----------------------------------------------------------------------------------------------31-JAN-2002: customers invoice products ---------------------------------------------cid oid pid cname cid pname pid qoh (quantity in hand) qty price create trigger tri on invoice for insert as update products set qoh=qoh-inserted.qty from products,inserted where products.pid=inserted.pid checking the availability of products: --------------------------------------select @iqty = inserted.qty from inserted select @qty = products.qty from inserted,products where inserted.pid=products.pid if(@qty<@iqty) begin print "invalid transaction" rollback return end

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 invoice for update if update(oid) // if the user tries to update field oid it will return true begin or it will retun false rollback return end if not exists (select * from products,inserted where inserted.productid=products.proudctid begin print ’Fk violation on products’ rollback return end -------------------------------------------------------------------------------------------Note: For update triggers, the inserted and deleted virutal table will be created.... deleted followed by inserted................... -------------------------------------------------------------------------------------------TSQL Cursors: The main application of cursors is ’report’ generation.......... The cursor contains following five ’jargons’ 1....Declare 2....Open 3....Fetch 4....Close 5....Deallocate A cursor is a symbolic name for a SQL statement.....and it ’will come only on select statement’.. 1...Declare: Syntax: Declare cursorname cursor for select statement // 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;

Query -

Page #25

Note: It destroies the cursor [ like dropping tables ] ------------------------------------------------------------------------------------------------Example with procedure:create procedure sen_cur_pro as declare cur cursor scroll for select * from sen_catlog open cur fetch next from cur while(@@fetch_status=0) begin fetch next from cur end close cur deallocate cur exec sen_cur_pro; Note: @@fetch_status is system defined global variable which is automatically set to 0 which indicates for successful fetch... -----------------------------------------------------------------------------------------------1-02-2002: Application of Cursors: Create procedure sen_cpro as declare @tid varchar(20),@title varchar(20),@price float declare cur cursor scroll for select title_id,title,price from titles open cur fetch next from cur into @tid,@title,@price while(@@fetch_status=0) begin select @tid + @title + convert(varchar,@price) fetch next from cur into @tid,@title,@price end close cur deallocate 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 as set nocount on declare @pid varchar(20),@pname varchar(20) declare @tid varchar(20),@title varchar(20),@price float declare @n int declare cur cursor scroll for select pub_id,pub_name from publishers open cur fetch next from cur into @pid,@pname while(@@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

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,@pname end close cur deallocate cur

exec sen_publisher_books --------------------------------------------------------------------------------------------------------2-Feb-2002: Indexing: It is a sorting process to reduce the searching process time.... Syntax: Create { nonClustered } index index_name on table_name(field_name) Default is Clustered indexing................ ------------------------------------------------------------------------------------------------NonClustered: create nonclustered index emp_eno on 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 or it is feasible for going for table scan...... -------------------------------------------------------------------------------------------------Note: Primary key creates Clustered automaically but to make it nonClustered index is more feasible than Clustered index -------------------------------------------------------------------------------------------Clustered: create clustered index emp_eno on 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 of record... 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 ------------------------------------------------------------------------------------------------

Query -

Page #1

-----------------------------------------------------------------------------------------------LIBRARY -----------------------------------------------------------------------------------------------Project Specification: Altair is a library renowned for its latest collection of books and magazines.The number of members is increasing every month and it is becoming difficult to keep track of so many members and transactions,which are currently maintained in registers. The chief librarian approaches you to seek help for designing a computerized system. All members in the library are given two member cards and one book is leased for each card. The membership fee for each member is Rs 500. One time payment,refundable on relinquishing of the cards.Both books and megazines are leased to the members.A book lent to a member can be with him for 15 days at most and an extension of another 15 days is given to the member for that particular book if that book is brought for renewal on the 15 th day after it is lent.The same member is not allowed to have the book for another 15 days after it is returned.Magazines are lent only for 4 days and no extension is allowed and there is no restriction for lending the magazine to the same member,as is the case with books. You need to store the book details for each book ( publisher name,title,author and the like ). Each book is identified by a unique title number.Magazines are identified in the following format. Each magazine has a short hand notation (Eg. otlk for the magazine outlook) To identify a particular magazine the short hand notation is used along with the month and year of issue Eg. otlk-jan-1999 identifies Outlook magazine jan issue of 1999. You need to store the number of copies of each book that is there in the library. One copy of each book is designated as reference and it is not lent to any member. ------------------------------------------------------------------------------------------------Create Table sen_catlog ( c_id varchar(10) constraint sc_pk primary key, title varchar(20), author varchar(20), publisher varchar(20), price float ); 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);

Query -

Page #2

select * from sen_catlog; insert insert insert insert insert insert insert insert

into into into into into into into into

sen_books sen_books sen_books sen_books sen_books sen_books sen_books sen_books

values values values values values values values values

(’B001’,’CB001’,’issue’); (’B002’,’CB001’,’issue’); (’B003’,’CB001’,’reference’); (’B004’,’CB002’,’issue’); (’B005’,’CB002’,’issue’); (’B006’,’CB002’,’Reference’); (’B007’,’CB003’,’issue’); (’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 insert insert insert insert

into into into into into

sen_cards sen_cards sen_cards sen_cards sen_cards

values(’C001’,’M001’); values(’C002’,’M001’); values(’C003’,’M002’); values(’C004’,’M002’); values(’C005’,’M003’);

select * from sen_cards; insert insert insert insert insert insert insert

into into into into into into into

select select select select select

* * * * *

sen_transaction sen_transaction sen_transaction sen_transaction sen_transaction sen_transaction sen_transaction

from from from from from

values values values values values values values

(’T001’,’B001’,’C001’,’12-10-2000’,null,null); (’T002’,’B002’,’C002’,’11-11-2000’,’11-25-2000’,null); (’T003’,’B004’,’C004’,’10-10-2000’,’10-25-2000’,1); (’T004’,’B004’,’C004’,’09-27-2000’,’10-10-2000’,0); (’T006’,’B002’,’C003’,’01-28-2000’,null,0); (’T007’,’B004’,’C002’,’01-28-2000’,’02-10-2000’,0); (’T008’,’B005’,’C005’,’01-28-2000’,null,0);

sen_catlog; sen_books; sen_member; sen_cards; 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_tr 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 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

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 i create procedure sen_books_details as declare @c varchar(10) declare @n int declare @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) as declare @n int declare @i int declare @b varchar(10) declare @c varchar(10) declare @r datetime declare @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=@ddate if(@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 + " end

" + @t_card + "

" + @t_title + "

" + @t_bid + " " + @message

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

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) 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) 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<@dday if(@n=0) print ’No Over due books on that day’ else begin select b_id,card_id into #temp from sen_transaction where rdate is null and tdate<@dday select @i = 1 while(@i<=@n) begin select top 1 @b=b_id,@c=card_id from #temp select distinct @t_title=c.title,@t_bid=b.b_id from sen_catlog c,sen_books b,sen_transaction t where t.b_id=@b and t.b_id=b.b_id and b.c_id = c.c_id select distinct @t_name=m.mname,@t_card=c.card_id from sen_transaction t,sen_cards c,sen_member m where t.card_id=@c and t.card_id=c.card_id and c.m_id=m.m_id delete from #temp where card_id=@c and b_id=@b select @i=@i+1 print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid end end exec sen_overdue_books @date=’2000-02-25’ -------------------------------------------------------------------------------------------------

Query -

Page #1

-----------------------------------------------------------------------------------------------LIBRARY -----------------------------------------------------------------------------------------------Project Specification: Altair is a library renowned for its latest collection of books and magazines.The number of members is increasing every month and it is becoming difficult to keep track of so many members and transactions,which are currently maintained in registers. The chief librarian approaches you to seek help for designing a computerized system. All members in the library are given two member cards and one book is leased for each card. The membership fee for each member is Rs 500. One time payment,refundable on relinquishing of the cards.Both books and megazines are leased to the members.A book lent to a member can be with him for 15 days at most and an extension of another 15 days is given to the member for that particular book if that book is brought for renewal on the 15 th day after it is lent.The same member is not allowed to have the book for another 15 days after it is returned.Magazines are lent only for 4 days and no extension is allowed and there is no restriction for lending the magazine to the same member,as is the case with books. You need to store the book details for each book ( publisher name,title,author and the like ). Each book is identified by a unique title number.Magazines are identified in the following format. Each magazine has a short hand notation (Eg. otlk for the magazine outlook) To identify a particular magazine the short hand notation is used along with the month and year of issue Eg. otlk-jan-1999 identifies Outlook magazine jan issue of 1999. You need to store the number of copies of each book that is there in the library. One copy of each book is designated as reference and it is not lent to any member. ------------------------------------------------------------------------------------------------Create Table sen_catlog ( c_id varchar(10) constraint sc_pk primary key, title varchar(20), author varchar(20), publisher varchar(20), price float ); 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);

Query -

Page #2

select * from sen_catlog; insert insert insert insert insert insert insert insert

into into into into into into into into

sen_books sen_books sen_books sen_books sen_books sen_books sen_books sen_books

values values values values values values values values

(’B001’,’CB001’,’issue’); (’B002’,’CB001’,’issue’); (’B003’,’CB001’,’reference’); (’B004’,’CB002’,’issue’); (’B005’,’CB002’,’issue’); (’B006’,’CB002’,’Reference’); (’B007’,’CB003’,’issue’); (’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 insert insert insert insert

into into into into into

sen_cards sen_cards sen_cards sen_cards sen_cards

values(’C001’,’M001’); values(’C002’,’M001’); values(’C003’,’M002’); values(’C004’,’M002’); values(’C005’,’M003’);

select * from sen_cards; insert insert insert insert insert insert insert

into into into into into into into

select select select select select

* * * * *

sen_transaction sen_transaction sen_transaction sen_transaction sen_transaction sen_transaction sen_transaction

from from from from from

values values values values values values values

(’T001’,’B001’,’C001’,’12-10-2000’,null,null); (’T002’,’B002’,’C002’,’11-11-2000’,’11-25-2000’,null); (’T003’,’B004’,’C004’,’10-10-2000’,’10-25-2000’,1); (’T004’,’B004’,’C004’,’09-27-2000’,’10-10-2000’,0); (’T006’,’B002’,’C003’,’01-28-2000’,null,0); (’T007’,’B004’,’C002’,’01-28-2000’,’02-10-2000’,0); (’T008’,’B005’,’C005’,’01-28-2000’,null,0);

sen_catlog; sen_books; sen_member; sen_cards; 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_tr 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 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

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 i create procedure sen_books_details as declare @c varchar(10) declare @n int declare @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) as declare @n int declare @i int declare @b varchar(10) declare @c varchar(10) declare @r datetime declare @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=@ddate if(@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 + " end

" + @t_card + "

" + @t_title + "

" + @t_bid + " " + @message

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

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) 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) 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<@dday if(@n=0) print ’No Over due books on that day’ else begin select b_id,card_id into #temp from sen_transaction where rdate is null and tdate<@dday select @i = 1 while(@i<=@n) begin select top 1 @b=b_id,@c=card_id from #temp select distinct @t_title=c.title,@t_bid=b.b_id from sen_catlog c,sen_books b,sen_transaction t where t.b_id=@b and t.b_id=b.b_id and b.c_id = c.c_id select distinct @t_name=m.mname,@t_card=c.card_id from sen_transaction t,sen_cards c,sen_member m where t.card_id=@c and t.card_id=c.card_id and c.m_id=m.m_id delete from #temp where card_id=@c and b_id=@b select @i=@i+1 print @t_name + " " + @t_card + " " + @t_title + " " + @t_bid end end exec sen_overdue_books @date=’2000-02-25’ -------------------------------------------------------------------------------------------------

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'

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

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,

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 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 off; set identity_insert

sen_temp off;

/* 13. Delete one record from the middle of the table and insert another record to see the

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 constraint senfk foreign key

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

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’); //////////////////////////////////////////////////////////////////////////////////////////////////

Query ---------------------------------------------------------------------------------------------PRACTICE - 3 ----------------------------------------------------------------------------------------------

Page #1

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 using the sample data given to you as an attachment.

data into the tables

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 co and sid in(select sid from sen_reserves where bid in(select bid from sen_boats where co

3.)

Find the names of sailors who have reserved a red boat. Ans:

Query -

Page #2 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; *************************************************************************************************

Query -

Page #1

---------------------------------------------------------------------------------------------PRACTICE - 5 ---------------------------------------------------------------------------------------------Create Table ( model_id model_name cspeed type );

sen_airmodels varchar(5) constraint sen_am_pk primary key, varchar(20), integer, 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 TOR A002 Sopwithcamel 500 VTL A003 Spitfire 700 VTL A004 Harrier 800 TOR A005 Hawkers 900 TOR A006 Stealth 600 VTL ................................................................................................. sen_certified: eid model_id ----- -------P001 A001 P001 A002 P001 A003 P002 A002 P002 A005 P003 A003 P004 A004 P005 A001 P005 A005 ................................................................................................. sen_flights: flight_no model_id start dest distance arrives departs --------- -------- ----- ---- ----------- ------- ------FL001 A001 NY CA 3000 13.30 14.00 FL001 A002 LA CA 3000 14.30 15.30 FL001 A003 LA NY 3000 14.00 15.15

Query -

Page #2

FL001 A004 LA ME 3000 8.30 9.30 FL001 A005 NJ ME 3000 7.30 8.30 FL002 A001 NY CA 2000 12.00 12.30 FL002 A002 SA CA 2000 16.30 17.30 FL002 A003 LA NY 3000 15.00 15.45 ................................................................................................. sen_emp: eid ename salary ----- -------------------- ----------e007 Joeph 20000 e008 Abraham 8000 P001 Sam 10000 P002 David 15000 P003 Stepen 16000 P004 Raj 12000 P005 Thomas 12000 P006 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))

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.m 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 ----P001 P002 P003 P004 P005 P006 P001 P002 P003 P004 P005 P006

ename -------------------Sam David Stepen Raj Thomas George Sam David Stepen Raj Thomas George

salary ----------10000 15000 16000 12000 12000 3000 10000 15000 16000 12000 12000 3000

eid ----e007 e007 e007 e007 e007 e007 e008 e008 e008 e008 e008 e008

ename -------------------Joeph Joeph Joeph Joeph Joeph Joeph Abraham Abraham Abraham Abraham Abraham Abraham

salary ----------20000 20000 20000 20000 20000 20000 8000 8000 8000 8000 8000 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

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’)) *************************************************************************************************

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 >

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

Query ---------------------------------------------------------------------------------------------Test I Date: 9-01-2002 ----------------------------------------------------------------------------------------------

Page #1

Query -

Page #1

---------------------------------------------------------------------------------------------Test II ----------------------------------------------------------------------------------------------

Specification: Note: 1) No table level constraints should be defined and all integrity constraints have to be enforced using triggers. 2) Reports are to be generated using cursors. Software Requiremet Specification: A movie production company needs to record information about movies that they produce including all the details of the movie, where it has been shot, in which theatres it has been screened and the like. Your task is to create a database design for the production company to record all the details. The specification and constraints that you have to take into account are as follows.. 1) The information for all directors, theatres and studios have to be stored 2) One director can direct many movies and one movie can have many actors. One studio can be used for many movies and one movie can be shot only in one studio. 3) For each theatre, you will have to record the movies screened in the theatre, screen date and the collections on each day for the movie till the screening is stopped in the particular theatre. 4) You also need to maintain the total collections for each movie. 5) Details of all actors as to in which movie the actor acted, the total amount which he has been promisied and the amount that he has been paid has to be recorded. The amount promisied can be paid in a maximum of three installments. 6) At any time the outstanding amount that has to be paid to a particular actor for a particular movie should be made available. Design an E-R Diagram for the above specification and arrive at a table design primary and foreign keys have to be indicated in the table. ’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 --------

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 ( m_id a_id p_amt ins_id );

sen_acting varchar(20), varchar(20), float, 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

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 used Movie---studio [one to many] Movie--Theatre [Many to Many] so screening table is used Collection table is used for calculating day to day collections of theatere no need of considering films is running in the theatre Installment table is used to store the installment amounts for an actor ------------------------------------------------------------------------------------------------Triggers: //// Primary key Trigger for Sen_movie Table ////// Create trigger sen_movie_insert on sen_movie for insert as declare @n int select @n=count(*) from inserted,sen_movie where inserted.m_id=sen_movie.m_id if(@n>1) begin print "Primary key violation:Duplicate m_id not allowed" rollback end 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_movie for update as if(update(m_id)) begin print ’coud not updated,primary key are not allowed to update’ rollback return end 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_actor for insert as declare @n int select @n=count(*) from inserted,sen_actor where inserted.a_id=sen_actor.a_id if(@n>1) begin print "Primary key violation:Duplicate a_id not allowed"

Query -

Page #4

rollback end 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_actor for update as if(update(a_id)) begin print ’coud not updated,primary key are not allowed to update’ rollback return end update sen_actor set a_id=’A005’ where a_id=’A001’ -----------------------------------------------------------------------------------------------// Foreign key Trigger for sen_acting Table create trigger sen_acting_insert on sen_acting for insert as declare @n int select @n=count(*) from sen_acting a,inserted i where i.m_id=a.m_id and i.a_id=a.a_id if(@n>1) begin print ’Primary key violation:Duplicate m_id and a_id combination not allowed’ rollback return end else begin 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’ end end insert insert insert insert

into into into into

sen_acting sen_acting sen_acting sen_acting

values values values values

(’M001’,’A001’,50000,1); (’M001’,’A003’,75000,2); (’M002’,’A002’,65000,3); (’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;

Query -

Page #5

-----------------------------------------------------------------------------------------------insert insert insert insert

into into into into

sen_theatre sen_theatre sen_theatre sen_theatre

values values values values

(’T001’,’Sarasvathi’,’Peruma palaya’); (’T002’,’Kathikeyan’,’Tiruchengode’); (’T003’,’Tirumalai’,’Peruma palaya’); (’T004’,’Gokul’,’Tiruchengode’);

select * from sen_theatre ------------------------------------------------------------------------------------------------insert insert insert insert insert insert insert

into into into into into into into

sen_screening sen_screening sen_screening sen_screening sen_screening sen_screening sen_screening

values values values values values values values

(’T001’,’M001’,’01-15-2002’); (’T001’,’M002’,’01-25-2002’); (’T002’,’M001’,’01-15-2002’); (’T002’,’M003’,’01-30-2002’); (’T003’,’M002’,’01-15-2002’); (’T003’,’M001’,’01-20-2002’); (’T004’,’M001’,’01-01-2002’);

select * from sen_screening ------------------------------------------------------------------------------------------------insert insert insert insert insert insert insert insert insert insert insert insert insert insert insert

into into into into into into into into into into into into into into into

sen_collection sen_collection sen_collection sen_collection sen_collection sen_collection sen_collection sen_collection sen_collection sen_collection sen_collection sen_collection sen_collection sen_collection sen_collection

values values values values values values values values values values values values values values values

(’T001’,’01-15-2002’,12500); (’T001’,’01-16-2002’,14600); (’T001’,’01-17-2002’,18500); (’T001’,’01-19-2002’,15000); (’T001’,’01-20-2002’,12000); (’T001’,’01-25-2002’,12500); (’T001’,’01-26-2002’,20000); (’T002’,’01-15-2002’,7800); (’T002’,’01-16-2002’,9560); (’T002’,’01-17-2002’,11500); (’T003’,’01-15-2002’,4500); (’T003’,’01-16-2002’,6700); (’T003’,’01-17-2002’,3500); (’T004’,’01-15-2002’,22500); (’T004’,’01-16-2002’,27800);

select * from sen_collection -----------------------------------------------------------------------------------------------// Cascade Deletion Trigger...for Sen_Theatre Table....... Create trigger sen_theatre_delete on sen_theatre for delete as declare @i varchar(20) select @i=t_id from deleted delete from sen_collection where t_id = @i delete from sen_theatre where t_id=’T001’; -----------------------------------------------------------------------------------------------// Trigger for Installment Checking................................... create trigger sen_installment_insert on sen_installment for insert as declare @n int declare @pamt float declare @amt float select @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 return end if(@n=0) begin select @pamt=act.p_amt from sen_acting act,inserted i where act.ins_id=i.ins_id

Query -

Page #6

select @amt=amt from inserted if(@amt>@pamt) begin print ’Error:Advance amount is greater than the promise amount’ rollback return end end if(@n > 0) begin select @pamt=act.p_amt from sen_acting act,inserted i where act.ins_id=i.ins_id select @amt= sum(inst.amt) from sen_installment inst,inserted i where inst.ins_id=i.ins_id if(@amt>@pamt) begin print ’Error:amount exceeds the the promise amount’ rollback return end end insert insert insert insert insert insert insert insert insert insert insert insert

into into into into into into into into into into into into

sen_installment sen_installment sen_installment sen_installment sen_installment sen_installment sen_installment sen_installment sen_installment sen_installment sen_installment sen_installment

values(1,45000); values(1,2000); values(1,3000); values(1,45000); // Error values(2,50000); values(2,25000); values(2,25000); // Error amount exceeds the promise amount values(3,60000); values(3,5000); values(4,20000); values(4,2000); values(4,20000);

select * from sen_installment -------------------------------------------------------------------------------------------------select * from sen_installment select * from sen_acting select * 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 as set nocount on declare @mid varchar(20),@mname varchar(20) declare @aid varchar(20),@aname varchar(20),@pamount float declare @i varchar(20) declare @total float select @total=0 print "Movie Name "+"Actor Name "+"Promise Amount" print "------------------------------------------------------------------------------" declare mcur cursor scroll for select m_id,m_name from sen_movie open mcur fetch next from mcur into @mid,@mname while(@@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

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 acur fetch next from mcur into @mid,@mname end close mcur deallocate mcur

exec movie_payment drop procedure movie_payment ------------------------------------------------------------------------------------------------create procedure theatre_amount as set nocount on declare @tid varchar(20),@tname varchar(20) declare @collection float declare @ddate datetime declare @total float select @total=0 print "TheatreName "+"Date "+"Amount" print "----------------------------------------------------------------" declare tcur cursor scroll for select distinct c.t_id,t.t_name from sen_collection c,sen_theatre t where t.t_id=c.t_id open tcur fetch next from tcur into @tid,@tname while(@@fetch_status=0) begin print @tname declare acur cursor scroll for select c.tdate,c.amt from sen_collection c where c.t_id=@tid open acur fetch next from acur into @ddate,@collection while(@@fetch_status=0) begin print " " +convert(varchar,@ddate) + " " + convert(varchar,@col fetch next from acur into @ddate,@collection select @total = @total + @collection end print ’----------------------------------------------------------------------’ print ’ Total=’ + convert(varchar,@total) print ’----------------------------------------------------------------------’ close acur deallocate acur select @total=0 fetch next from tcur into @tid,@tname end close tcur deallocate tcur exec theatre_amount drop procedure theatre_amount -----------------------------------------------------------------------------------------------create procedure sen_movie_details as set nocount on declare @mid varchar(20),@mname varchar(20) declare @sname varchar(20),@location varchar(20) declare @tname varchar(20) declare @sdate datetime declare @sid varchar(20)

Query -

Page #8

print "MovieName "+"Studio "+"Location "+"TheatreName " +"ReleaseDate" print "-----------------------------------------------------------------------------------" declare mcur cursor scroll for select m.m_id,m.m_name,s.s_name,s.loc from sen_movie m,sen_studio s where s.s_id=m.s_id open mcur fetch next from mcur into @mid,@mname,@sname,@location while(@@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( fetch next from acur into @tname,@sdate end close acur deallocate acur print "-----------------------------------------------------------------------------------" fetch next from mcur into @mid,@mname,@sname,@location end close mcur deallocate mcur exec sen_movie_details drop procedure sen_movie_details ------------------------------------------------------------------------------------------------select * from sen_acting select * 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

Query ---------------------------------------------------------------------------------------------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 #1

Query s_id j_id l_id m_id sdate

Page #2 varchar(10) varchar(10) varchar(10) varchar(10) datetime

constraint constraint constraint constraint

ss_pk primary key, ss_fk1 foreign key references sen_job_card(j_id), ss_fk2 foreign key references sen_labour(l_id), ss_fk3 foreign key references sen_maintenance(m_id),

); 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_index on 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_insert on sen_job_card for insert as declare @jid varchar(10) select @jid = j_id from inserted update sen_job_card set lcharge=0,total_cost=0 where j_id= @jid ------------------------------------------------------------------------------------------------create trigger sen_servicing_insert on sen_servicing for insert as declare @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

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 end else begin print ’Invalid Labourd id under Supervisior id’ rollback end ---------------------------------------------------------------------------------------------------insert into sen_vehicle values(’V001’,’TVS-XL Super’); insert into sen_vehicle values(’V002’,’SUZUKI MAX 100’); insert into sen_vehicle values(’V003’,’SUZUKI MAX 100-R’); insert into sen_vehicle values(’V004’,’YAMAHA 100 CC’); ------------------------------------------------------------------------------------------------insert into sen_maintenance values(’M001’,’Engine’); insert into sen_maintenance values(’M002’,’Gear Box’); insert into sen_maintenance values(’M003’,’Electrical’); -------------------------------------------------------------------------------------------------insert into sen_service_cost values(’V001’,’M001’,450) insert into sen_service_cost values(’V002’,’M001’,750) insert into sen_service_cost values(’V002’,’M002’,300) insert into sen_service_cost values(’V003’,’M001’,750) insert into sen_service_cost values(’V003’,’M002’,300) insert into sen_service_cost values(’V003’,’M003’,150) insert into sen_service_cost values(’V004’,’M001’,820) insert into sen_service_cost values(’V004’,’M002’,340) insert into sen_service_cost values(’V004’,’M003’,150) -------------------------------------------------------------------------------------------------insert into sen_labour values(’SP01’,’Senthil’,’Salem’,null) insert into sen_labour values(’SP02’,’Sabitha’,’Salem’,null) insert insert insert insert insert

into into into into into

sen_labour sen_labour sen_labour sen_labour sen_labour

values(’L001’,’Ravikumar’,’Salem’,’SP01’) values(’L002’,’Anjala’,’Tiruchengode’,’SP01’) values(’L003’,’Sudamani’,’Rasipuram’,’SP01’) values(’L004’,’Munian’,’Rasipuram’,’SP01’) 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’)

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_vehicle select * from sen_maintenance select select select select select select

* * * * * *

from from from from from from

sen_service_cost sen_servicing sen_replacement sen_labour sen_stores 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 day Ans: create procedure sen_service_come_particular_day(@cday datetime) as if(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_name end else print ’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) as set nocount on print ’Month ’ + convert(varchar,month(@date)) + ’ Year ’ + convert(varchar,year(@date)) print ’---------------------------------------------------------------’ select l.lname ’Labour Name’,v.v_name ’Vehicle Type’,count(v.v_id) ’Nos’ from sen_servicing s,sen_job_card j,sen_labour l,sen_vehicle v where s.l_id=@lid and s.j_id=j.j_id and j.v_id=v.v_id and s.l_id=l.l_id and month(sdate)=month(@date) and year(sdate)=year(@date) group by l.lname,v.v_name 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 v where c.sup_id=l.l_id and c.v_id=v.v_id and month(c.in_date)=month(@date) and year(c.in_date)=year(@date) group by l.lname,v.v_name

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 available Ans: create procedure sen_job_card_details(@cdate datetime) as if(exists (select c.reg_no ’Reg No’,v.v_name ’Vehicle Type’,l.lname ’Supervisior Name’,left(convert(varchar,c.exp_d 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_d 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 end else 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 available Ans: create procedure sen_previousday_not_delivered(@cdate datetime) as if(exists( select * from sen_job_card where in_date=convert(datetime,@cdate)-1 and d_date is null)) begin select 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’ end from sen_job_card c,sen_vehicle v,sen_labour l where 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 null end else 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)) as declare @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_id select @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 s where c.j_id=s.j_id and s.m_id = sc.m_id and c.v_id=sc.v_id and sc.m_id = m.m_id and c.j_id=@j_id select @ltcost=sum(sc.cost) from sen_job_card c,sen_maintenance m,sen_service_cost sc,sen_servicing s where c.j_id=s.j_id and s.m_id = sc.m_id and c.v_id=sc.v_id and sc.m_id = m.m_id and c.j_id=@j_id print ’-----------------------------------------------------------------------’ print ’Replacement/Repaired Summary’ print ’-----------------------------------------------------------------------’

Query -

Page #6

select s.tnmae ’Tool Name’,s.uprice ’Price’ from sen_stores s,sen_servicing ss,sen_replacement r where 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_id print ’ 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 delivered Ans: 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 Deliv 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 vehicles Ans: 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 insert Ans: create trigger sen_replacement_insert on sen_replacement for insert as declare @qty int declare @tid varchar(10) declare @price float declare @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) + ’/.’ end else begin print ’Unavailable qty in hand’ rollback end insert into sen_replacement values(’S012’,’T003’)

Query -

Page #7

-------------------------------------------------------------------------------------------------10.) At the end of each month the total revenue got by sale of parts and labour charges has to be made available.The report should contain the part name and labour type Ans: create procedure sen_total_revenue(@date datetime) as declare @ltotal numeric(8,2) declare @ttotal numeric(8,2) declare @rev numeric(8,2) set nocount on print ’Month ’ + convert(varchar,month(@date)) + ’ Year ’ + convert(varchar,year(@date)) print ’----------------------------------------------------------------------’ print ’Labour Charge Summary’ print ’----------------------------------------------------------------------’ 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 s where c.j_id=s.j_id and s.m_id = sc.m_id and c.v_id=sc.v_id and sc.m_id = m.m_id month(c.in_date)= month(@date) and year(c.in_date) = year(@date) group by m.m_name

and

print ’---------------------------------------------------------------------’ print ’Tools Sale Summary’ print ’---------------------------------------------------------------------’ select @ltotal=sum(sc.cost) from sen_job_card c,sen_maintenance m,sen_service_cost sc,sen_servicing s where c.j_id=s.j_id and s.m_id = sc.m_id and c.v_id=sc.v_id and sc.m_id = m.m_id month(c.in_date)= month(@date) and year(c.in_date) = year(@date)

and

select st.tnmae ’Tool Name’,sum(st.uprice)’Total Price’ from sen_job_card c,sen_servicing s,sen_replacement r,sen_stores st where c.j_id=s.j_id and s.s_id = r.s_id and r.t_id = st.t_id and month(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 st where c.j_id=s.j_id and s.s_id = r.s_id and r.t_id = st.t_id and month(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+@ttotal print ’ 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_vehicle select * 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

Query 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 #8

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

into into into into

sen_applicant sen_applicant sen_applicant sen_applicant

values(’A100’,’Senthil’,’Salem’,’T.gode’) values(’A101’,’kum’,’Salem’,’T.gode’) values(’A102’,’aravind’,’Salem’,’T.gode’) 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())

Query 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_registeration select * 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 #2

Query -

Page #3

Query -

Page #1

---------------------------------------------------------------------------------------------TRIGGERS - EXAMPLE ----------------------------------------------------------------------------------------------

Question: Create the following tables and impose the necessary constraints by using triggers..... --------------------------------------------------------------------------------------------------------Tables: Customers:c_id cname Address

int

(primary key) varchar(20) 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 pname qty_hand

int

primary key varchar(20) 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 c_id p_id idate qty

int primary key int int datetime 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 i 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

Query -

Page #2

); select * from sen_invoice select * from sen_products select * from sen_customers -------------------------------------------------------------------------------------------------Create trigger sen_customers_insert on sen_customers for insert as declare @n int select @n=count(*) from inserted,sen_customers where inserted.c_id=sen_customers.c_id if(@n>1) begin print "Primary key violation:Duplicate c_id not allowed" rollback end insert into sen_customers values (101,’Ashiwarya’,’3 Sidney square end,Sidney’); ---------------------------------------------------------------------------------------------------Create trigger sen_customers_update on sen_customers for update as if(update(c_id)) begin print ’Primary key c_id not allowed to change’ rollback end

update sen_customers set c_id=101,cname=’kumarn’ where c_id=101 --------------------------------------------------------------------------------------------------------Create trigger sen_customers_delete on sen_customers for delete as declare @n int declare @i int select @i=c_id from deleted select @n=count(*) from sen_invoice i,deleted d where i.c_id=d.c_id if(@n<>0) begin print ’Could not be deleted, c_id exists in the products table’ rollback end

delete sen_customers where c_id=101; --------------------------------------------------------------------------------------------------------Create trigger sen_products_insert on sen_products for insert as declare @n int select @n=count(*) from inserted,sen_products where inserted.p_id=sen_products.p_id if(@n>1) begin print "Primary key violation:Duplicate p_id not allowed" rollback end

insert into sen_products values(202,’Dream Flower’,25); --------------------------------------------------------------------------------------------------------create trigger sen_products_update on sen_products for update as if(update(p_id)) begin print ’Primary key p_id not allowed to change’ rollback end

Query -

Page #3

update sen_products set p_id=202 where p_id=205; --------------------------------------------------------------------------------------------------------Create trigger sen_products_delete on sen_products for delete as declare @n int declare @i int select @i=p_id from deleted select @n=count(*) from sen_invoice i,deleted d where i.p_id=d.p_id if(@n<>0) begin print ’Could not be deleted, p_id exists in the products table’ rollback end

delete sen_products where p_id=201; --------------------------------------------------------------------------------------------------------create trigger sen_invoice_insert on sen_invoice for insert as declare @n int declare @c int declare @i int select @n=count(*) from sen_invoice inv,inserted i where inv.o_id=i.o_id if(@n>1) begin print ’Primary key violation:Duplicate o_id not allowed’ rollback return end else begin 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_invoice for update as declare @old_qty int

Query -

Page #4

declare @new_qty int declare @i int declare @c int if(update(o_id) or update(c_id) or update(p_id)) begin print ’coud not updated,olny qty and date allowed to change’ rollback return end else begin 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’ end end

update sen_invoice set qty=1 where o_id=1 --------------------------------------------------------------------------------------------------------select * from sen_invoice select * from sen_products select * from sen_customers

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,52 insert into flight_master values(’SA102’,’Singapore-to-Manila’,’16’,’A310’,’14:25’,’23:00’,5,6500.00,3,52 insert into flight_master values(’SA103’,’Singapore-to-Muscat’,’25’,’B707’,’15:25’,’24:00’,100,6500.00,15 insert into flight_master values(’SA104’,’Singapore-to-Dubai’,’34’,’A310’,’16:25’,’20:00’,100,6500.00,150 insert into flight_master values(’SA105’,’Singapore-to-KulaLumpur’,’17’,’A310’,’10:25’,’04:00’,100,6500.0 insert into flight_master values(’SA106’,’Singapore-to-Jakarta’,’26’,’B707’,’12:25’,’14:00’,100,6500.00,1 ***************************************************************************** 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 declare declare declare declare declare declare

@rec_num int @day_num int @c1 int @c2 int @day_opt varchar(20) @pnr_no int @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)

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

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

@datediff int @class varchar(20) @amt float @minpnr int @waiting varchar(20)

select @datediff=datediff(day,date_of_travel,@cdate) from test_trans where pnr=@pnr select @class = class from test_trans where pnr=@pnr select @waiting= status from test_trans where pnr=@pnr select when when when end

@amt=case @class ’First’ then 6500 ’Business’ then 5200 ’Economy’ then 4700

if(@datediff=0) -- if he cancel the same date begin select (@amt*(90.0/100.0)) delete test_trans where pnr=@pnr

Query 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_cancellation drop procedure sen_reservation select * from test_trans delete 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 #4

Query ---------------------------------------------------------------------------------------------BANK CPP PROGRAM ---------------------------------------------------------------------------------------------// Computerized Bank #include #include #include #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 definitions void Alist :: Load_Account_Records() { ifstream ifile("Accounts.dat",ios::binary | ios :: in | ios :: nocreate );

Page #1

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 cout<<"Name cin>>cur->name; cout<<"Address cin>>cur->address;

: "<<cur->Acc_no<<endl; : "; : ";

again: cout<<"Balance Not < 500 "<<endl; cout<<"Initial Balance : "; cin>>cur->balance; if(cur->balance < 500) goto again; if(head==NULL) { head = cur; prev = cur; } else

Query -

Page #3

{ prev->link = cur; prev = cur; } } ///////////////////////////////////////////////////////////////////////////// void Alist :: List_all_Accounts() { cout<<"-----------------------------------------------------------------"<<endl; cout<<" Acc_no Name Address Balance "<<endl; cout<<"-----------------------------------------------------------------"<<endl; temp = head; while(temp!=NULL) { cout<Acc_no<<" "<name<<" temp = (Alist *) temp->link; }

"<address<<"

"<balance<<endl;

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 : "<Acc_no<<endl; cout<<"Name : "<name<<endl; cout<<"Address : "<address<<endl; cout<<"Balance : "<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 :"<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)

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 Functions void 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) {

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;

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

";

if(!strcmp(temp->type,"deposit")) { cout<transact_amount<<endl; total_deposit += temp->transact_amount; } else { cout<<" "<transact_amount<<endl; total_withdraw += temp->transact_amount; } } temp = (Tlist *) temp->link; } cout<<"--------------------------------------------------------"<<endl; cout<<"Total "<t_date,today)) { cout<Acc_no<<"

";

if(strcmp(temp->type,"deposit")==0) { cout<transact_amount<<endl; total_deposit += temp->transact_amount; } else { cout<<" "<transact_amount<<endl; total_withdraw += temp->transact_amount; } } temp = (Tlist *) temp->link; } cout<<"-----------------------------------------------------------"<<endl; cout<<"Total "<
Query -

Page #7

Tlist *p = head; float T_amount=0; while(temp!=NULL) { if((temp->Acc_no == a_no && strcmp(temp->mode,mode)==0 && // If equal strcmp(temp->t_date,date) == 0 && strcmp(temp->type,type)==0) || temp->Acc_no == a_no && strcmp(type,"DAll")) { if(temp==head) // Head Node { head = (Tlist*)head->link; T_amount = temp->transact_amount; delete temp; } else { p ->link = temp->link; T_amount = temp->transact_amount; delete temp; } } p = temp; temp =(Tlist*) temp->link; } if(strcmp(temp->type,"deposit")==0) return( -1 * T_amount); else return(T_amount); } ////////////////////////////////////////////////////////////////////////////// void Tlist :: Store_Transaction_Records() { ofstream ofile("Transaction.dat",ios::binary | ios :: out); temp = head; while(temp != NULL) { ofile.write((char *)temp,sizeof(Tlist)); temp = (Tlist *) temp->link; } ofile.close(); } ///////////////////////////////////////////////////////////////////////////// // Main Function void main() { clrscr(); int choice,acc_no; char today[15],mode[15],type[15]; 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;

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 :

case 3 : case 4 :

cout<<"Enter Account Number : "; cin>>acc_no; A.Update_Balance(acc_no,(float)(T.Make_Transaction(acc_no))); // cout<>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 : } clrscr(); }

next = ’n’; break;

Query A.Store_Account_Records(); T.Store_Transaction_Records(); } /////////////////////////////////////////////////////////////////////////////

Page #9

Query ---------------------------------------------------------------------------------------------LIBRARY CPP PROGRAM ---------------------------------------------------------------------------------------------// Computerized Libarary #include #include #include<string.h> #include #include<dos.h> #include<stdlib.h> #include ////////////////////////////////////////////////////////////////////////////// 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 void void void

Add_Book(); Delete_Book(); List_A_Book(); List_All_Books();

void void void void

Add_Member(); Delete_Member(); List_A_Member(); List_All_Members();

Page #1

Query void void void void

Page #2

Book_Issue(); Book_Return(); Book_Issue_Details(); List_Overdue_Books();

void Store_Books_Records(); void Store_Members_Records(); void Store_Issue_Register_Records(); ////////////////////////////////////////////////////////////////////////////// // Load Books Records Function definition void Load_Books_Records() { ifstream iBfile("Books.dat",ios::binary | ios :: in | ios :: nocreate ); 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 definition void 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

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 definition void 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) {

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 definition void Add_Book() { Bcur = new Book; Bcur->link = NULL; Bcur->accession_no = ++B_no; cout<<"Accession_No : "<accession_no<<endl; cout<<"Title : "; cin>>Bcur->title; cout<<"Author : "; cin>>Bcur->author; cout<<"Publisher : "; cin>>Bcur->publisher; cout<<"Purchase Date : "; cin>>Bcur->purchase_date; cout<<"Price : "; cin>>Bcur->price; if(Bhead==NULL) { Bhead = Bcur; Bprev = Bcur; } else { Bprev->link = Bcur; Bprev = Bcur; } } //////////////////////////////////////////////////////////////////////////// // List A Book Function definition void List_A_Book() { Btemp = Bhead; int a_no; cout<<"Enter Book Accession No : "; cin>>a_no; while(Btemp!=NULL) { if(Btemp->accession_no==a_no) { cout<<"Accession_No : "<accession_no<<endl; cout<<"Title : "<title<<endl; cout<<"Author : "<author<<endl; cout<<"Publisher : "<publisher<<endl;

Query -

Page #5 cout<<"Purchase Date : "<purchase_date<<endl; cout<<"Price : "<price<<endl; break;

} Btemp =

Btemp->link;

} if(Btemp==NULL) cout<<"Book Not Found!!"<<endl; } /////////////////////////////////////////////////////////////////////////// // Delete Book Function void Delete_Book() { Btemp = Bhead; Book *p = Bhead; int a_no; 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 definition void List_All_Books() { cout<<"-----------------------------------------------------------------"<<endl; cout<<" Accssion_no Title Author Publisher "<<endl; cout<<"-----------------------------------------------------------------"<<endl; Btemp = Bhead; while(Btemp!=NULL) { /* cout<<" "<accession_no<<" <publisher<<endl; */

"<title<<"

cout<<setw(10)<< Btemp->accession_no<<" "<<setw(-13)<title <<" "<<setw(-20)<author<<" "<<setw(-13) <publisher<<endl; Btemp = Btemp->link; } cout<<"-----------------------------------------------------------------"<<endl; } ///////////////////////////////////////////////////////////////////////////////// // Add Member function definition

"<author<<

Query void Add_Member() { Mcur = new Member; Mcur->link = NULL; Mcur->membership_no = ++M_no; cout<<"Membership_No : "<<Mcur->membership_no<<endl; cout<<"Name : "; cin>>Mcur->name; cout<<"Address : "; cin>>Mcur->address; cout<<"Caution Deposit : "; cin>>Mcur->caution_deposit; struct date d; getdate(&d); char temp[10]; itoa(d.da_day,Mcur->current_date,10); strcat(Mcur->current_date,"/"); itoa(d.da_day,Mcur->exp_date,10); strcat(Mcur->exp_date,"/"); itoa(d.da_mon,temp,10); strcat(Mcur->current_date,temp); strcat(Mcur->current_date,"/"); itoa(d.da_mon,temp,10); strcat(Mcur->exp_date,temp); strcat(Mcur->exp_date,"/"); itoa(d.da_year,temp,10); strcat(Mcur->current_date,temp); itoa((d.da_year+1),temp,10); strcat(Mcur->exp_date,temp);

if(Mhead==NULL) { Mhead = Mcur; Mprev = Mcur; } else { Mprev->link = Mcur; Mprev = Mcur; } } //////////////////////////////////////////////////////////////////////////// // List A Member Function definition void List_A_Member() { Mtemp = Mhead; int m_no; 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 #6

Query -

Page #7 cout<<"Caution Dep break;

: "<<Mtemp->caution_deposit<<endl;

} Mtemp =

Mtemp->link;

} if(Mtemp==NULL) cout<<"Member Not Found!!"<<endl; } /////////////////////////////////////////////////////////////////////////// // Delete Member Function void Delete_Member() { Mtemp = Mhead; Member *p = Mhead; int m_no; 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 definition void List_All_Members() { cout<<"-----------------------------------------------------------------"<<endl; cout<<" Membership_no Name Address Exp Date "<<endl; cout<<"-----------------------------------------------------------------"<<endl; Mtemp = Mhead; while(Mtemp!=NULL) { cout<<" "<< Mtemp->membership_no<<" <<Mtemp->exp_date<<endl; Mtemp = Mtemp->link; }

"<<Mtemp->name<<"

cout<<"-----------------------------------------------------------------"<<endl; } ///////////////////////////////////////////////////////////////////////////////// // Book Issue function details void Book_Issue() { int a_no,m_no;

"<<Mtemp->address<<"

cout<<"Accession No cin>>a_no;

: ";

Query 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 #8

Query -

Page #9

IRprev->link = IRcur; IRprev = IRcur; } } ///////////////////////////////////////////////////////////////////////////// void Book_Return() { int a_no,m_no; cout<<"Accession No : "; cin>>a_no; cout<<"Membership No : "; cin>>m_no; IRtemp = IRhead; Issue_Register *p = IRhead; while(IRtemp!=NULL) { if((IRtemp->accession_no == a_no && IRtemp->membership_no==m_no)) { if(IRtemp==IRhead) // Head Node { IRhead = IRhead->link; delete IRtemp; } else { p ->link = IRtemp->link; delete IRtemp; } } p = IRtemp; IRtemp = IRtemp->link; } } ///////////////////////////////////////////////////////////////////////////// // Book Issue Details function definition void Book_Issue_Details() { IRtemp = IRhead; cout<<"------------------------------------------------------------------"<<endl; cout<<"Accession_no Membership_no Issue_date Return_date "<<endl; cout<<"------------------------------------------------------------------"<<endl; while(IRtemp != NULL) { cout<<" "<accession_no<<" cout<membership_no<<" cout<issue_date<<" "; cout<return_date<<endl; IRtemp =

"; ";

IRtemp->link;

} cout<<"-----------------------------------------------------------------"<<endl; } ////////////////////////////////////////////////////////////////////////////// // Book Issue Details function definition void List_Overdue_Books() { char today[20]; cout<<"Enter Date : "; cin>>today; IRtemp = IRhead;

Query -

Page #10

cout<<"------------------------------------------------------------------"<<endl; cout<<"Accession_no Membership_no Issue_date Return_date "<<endl; cout<<"------------------------------------------------------------------"<<endl; int x; while(IRtemp != NULL) { x=strcmp(IRtemp->return_date,today); if(x<0) { cout<<" "<accession_no<<" cout<membership_no<<" cout<issue_date<<" "; cout<return_date<<endl; } IRtemp =

"; ";

IRtemp->link;

} cout<<"-----------------------------------------------------------------"<<endl; } //////////////////////////////////////////////////////////////////////////// // Store Books Records Function void Store_Books_Records() { ofstream oBfile("Books.dat",ios::binary | ios :: out); Btemp = Bhead; while(Btemp != NULL) { oBfile.write((char *)Btemp,sizeof(Book)); Btemp = Btemp->link; } oBfile.close(); } ////////////////////////////////////////////////////////////////////////////// // Store Members Records Function void Store_Members_Records() { ofstream oMfile("Members.dat",ios::binary | ios :: out); Mtemp = Mhead; while(Mtemp != NULL) { oMfile.write((char *)Mtemp,sizeof(Member)); Mtemp = Mtemp->link; } oMfile.close(); } ////////////////////////////////////////////////////////////////////////////// // Store Issue Register Records Function void Store_Issue_Register_Records() { ofstream oIRfile("IRegister.dat",ios::binary | ios :: out); IRtemp = IRhead; while(IRtemp != NULL) { oIRfile.write((char *)IRtemp,sizeof(Issue_Register)); IRtemp = IRtemp->link; } oIRfile.close(); } ////////////////////////////////////////////////////////////////////////////// // Main Function void main()

Query -

Page #11

{ clrscr(); Load_Books_Records(); Load_Members_Records(); Load_Issue_Register_Records(); int choice; char ch=’y’; while(ch==’y’) { cout<<"Sen’s Book Paradise "<<endl<<endl; cout<<"1. Add A Book "<<endl; cout<<"2. Delete A Book "<<endl; cout<<"3. List A Book "<<endl; cout<<"4. List All Books "<<endl; cout<<"-----------------------"<<endl; cout<<"5. Add A member "<<endl; cout<<"6. Delete A member "<<endl; cout<<"7. List A member "<<endl; cout<<"8. List All members "<<endl; cout<<"-----------------------"<<endl; cout<<"9. Book Issue "<<endl; cout<<"10.Book Return "<<endl; cout<<"11.Book Issue Details "<<endl; cout<<"12.List Overdue Details"<<endl; cout<<"13.Exit "<<endl; cout<<"Enter your choice : "; cin>>choice; switch(choice) { case 1 : Add_Book(); break; 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(); }

Query ////////////////////////////////////////////////////////////////////////////

Page #12

Query -

Page #1

#include<stdio.h> main() { int i,j; /* Returning every element address int *fun1(); int *p; p=fun1(); for(i=0;i<2;i++) { for(j=0;j<2;j++) printf("%d ",*(p+i*2+j)); printf("\n"); }

*/

/* 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; }

*/

Query -

Page #1

#include<stdio.h> void main() { char names[][5] = { {"Sabit"}, {"Dee"}, {"Kumar"} }; char *names1[3] = { {"Sabit"}, {"Dee"}, {"Kumar"} }; char char char char

(*p)[5]; (*q)[3][5]; **m; *(*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)); }

Related Documents

Query
October 2019 37
Query
November 2019 32
Query
October 2019 34
Query
October 2019 31
Query
November 2019 27
Query
December 2019 14