venky sql server metierial

Upload: dinesh-reddy-g

Post on 04-Apr-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Venky SQL Server Metierial

    1/37

    SQL Server Metiereal--Date 20-02-2012--Creating Databasecreatedatabase mahesh123

    on(name='mahesh',filename='c:\mahesh.mdf',size=4mb,maxsize=5mb,filegrowth=1mb)logon(name='mahesh_log',filename='c:\mahesh_log.ldf',size=3mb,maxsize=4mb,filegrowth=1mb)--note:The minimum size of primary file is 3mb--we can create database without log file also--the size,maxsize,filegrowth are optionalcreate databae mahesh123on(name='mahesh',filename='c:\mahesh.mdf')

    --if you want to add the log file use the following syntaxalterdatabase mahesh123

    addfile(name='mahesh_log',filename='c:\maheshlog.ldf')--if you want to remove the log file use the following syntaxalterdatabase mahesh123remove file mahesh_log--to enter into your databaseuse mahesh--**********************Removing Database******************

    dropdatabase mahesh--**********************DataTypes In SqlServer***************--*******************Integer************--1.TinyInt-----1byte--Range is 2 power 8 or 0-255--2.SmallInt---2bytes--Range is 2 power 15 or -32768 to +32767--3.Int----------4bytes--Range is 2 power 31 or -2147483648 to +2147483647--4.Big int-----8bytes--Range is 2 power 53 or -9223372036854775808 to+9223372036854775807--tinyint

    declare @a TinyIntset @a=255print @a--smallintdeclare @a smallintset @a=32767print @a--int (4 bytes)declare @a intset @a=2147483647

    print @a--int (8bytes)declare @a bigintset @a =9223372036854775807

  • 7/31/2019 Venky SQL Server Metierial

    2/37

    print @a--*********Charecter**********--1.char--------------------- Range is single charecter--2.varchar(upto 8000)-- Range is upto 8000 charecters--3.nchar--------------------Range is single charecter--4.nvarchar(upto 4000)-Range is upto 4000 charecters--5.Text,Ntext,Img are not for the local variables--1chardeclare @a charset @a='$'print @a--2.varchardeclare @a varchar(4)set @a='mahe'print @a--nchar

    declare @a ncharset @a='m'print @a--nvarchardeclare @a nvarchar(4000)set @a='maehshehsejkljdlfjldkjfldfj........4000charecters'print @a--text ,ntext ,img is not ment for local variables--Note:char,varchar and nchar,nvarchar the diffrence is only their size

    --*********Float*****************--1.Float ------->4Bytes--2.Decimal----->8bytes--*********Money****************--1.SmallMoney-->4Bytes--2.Money--------->8Bytes

    --********BINARY****************

    --1.BIt------------->1 byte--2.Img------------>upto 2gb--********LargeObjects************--1.varchar(MAX)--2.NVARCHAR(MAX)--********DATE AND TIME**********--SMALLDATE -->2BYTES--> YEARS UPTO 2079--DATETIME---->4BYTES-->YEARS UPTO 9999--DATE---------->3BYTES-->ONLY DATE

    --TIME---------->3BYTES-->ONLY TIME

    --********MISCELLANEOUS*********--SQL_VARINT-->ANY TYPE OF DATA CAN BE STORED

  • 7/31/2019 Venky SQL Server Metierial

    3/37

    --XML -TO STORE XML FORMATE--TEXT--NTEXT--------------------------CREATING TABLE------------------------**********************************************CREATETABLE STUDENT(STUD_ID INTPRIMARYKEY,SNAMEVARCHAR(15),LOCATION VARCHAR(15),MARKS INT)--Here I already added primary key while creating table itselfcreatetable student1(stud_id int,sname varchar(15),location varchar(15),marks int)--adding primary key explicitly for adding we have to add notnull constraint firstaltertable student1altercolumn stud_id intnotnull--now you can add primary keyaltertable student1addconstraint pk_student1 primarykey(stud_id)--Adding records

    insertinto student values(101,'mahesh','khammam',100)insertinto student values(102,'neena','khammam',200)--To view records in the tableselect*from student--deleting records from the tabledeletefrom student where stud_id=102deletefrom student --it will delete all records--*************Identity***********************-->Used to generate the unique values in sequential manner

    createtable student3(stud_id intidentity(10,1),sname varchar(12))insertinto student3 values('mahesh')insertinto student3 values('neena')--now observe values in the tableselect*from student3--automatically stud_id is generated

    --************Operators in SqlServer******************--1.Arithamatic operators(+-/*)--2.Relational Operators(,=)

    --3.Logical Operators(and,or,not)--4.Concatination Operators(+)--5.Assignment Operators(=)--Arithamatic operators usagecreatetable student4_arithusage(sidintprimarykey,sname varchar(12),m1 int, m2int,m3 int)insertinto student4_arithusage values(10,'mahesh',10,20,43)insertinto student4_arithusage values(20,'neena',12,29,22)select m1+m2+m3 from student4_arithusage

    select m1+m2-m3 from student4_arithusageselect m1/m2+m3 from student4_arithusage--divison is higher priorityselect m1*m2*m3 from student4_arithusage

  • 7/31/2019 Venky SQL Server Metierial

    4/37

    --Relational Operatorscreatetable student5_relationalUsage(sidintprimarykey,sname varchar(12),totalmarksint)insertinto student5_relationalUsage values(10,'mahesh',159)insertinto student5_relationalUsage values(20,'neena',300)

    insertinto student5_relationalUsage values(22,'mahe',33)select*from student5_relationalUsage where totalmarks>100select*from student5_relationalUsage where totalmarks =100select*from student5_relationalUsage where totalmarks 10select*from student5_relationalUsage where totalmarks >10 and sname like'm%'select*from student5_relationalUsage wheresid=10 or totalmarks isnotnullselect*from student5_relationalUsage wheresidisnotnull

    --assignment operatordeclare @aa intselect @aa=-2147483648print @aa--create login maa with password='password123',default_database=harsha,check_policy=off--roughcreatetable employee(empno int,ename varchar(20),job varchar(13),Mgr int,HireDate

    date,sal money,comm int,dno int)insertinto employee values(101,'mahesh','manager',null,'12-mar-2009',20000,null,10)insertinto employee values(102,'emp1','clerk',101,'12-jun-2010',3000,100,10)insertinto employee values(103,'emp2','salesman',101,'23-jul-2010',3400,200,10)insertinto employee values(104,'Neena','manager',null,'22-jun-2008',30000,null,20)insertinto employee values(105,'anil','clerk',104,'30-jun-2009',3000,200,20)insertinto employee values(106,'babi','salesman',104,'30-aug-2009',3300,200,20)select*from employee

    --

    **************************Operators***************************--1.Like--2.Is--3.In--4.Between and--1.Like Operator:This operator is used to work with columns contains charecter--while working with this operator we must know wild charecters--'_'and'%' are called wild charecters--1.To get Employee name starting with 'N'

    select ename from employee where ename like'N%'--2.To get Employee names ending with 'a'select ename from employee where ename like'%a'--3.To get employee names whose second charecter is e

  • 7/31/2019 Venky SQL Server Metierial

    5/37

    select ename from employee where ename like'_e%'--4.To get Employee name whose name doesnot start with Nselect ename from employee where ename notlike'N%'--5.To get employee names starting with a,b,c,dselect ename from employee where ename like'[A-d]%'--6.To Get employee names whose job starts with 'm'select ename from employee where job like'm%'--7.To get employee names whose names ending with 1select ename from employee where ename like'%1'--In Operator =>Used to give set of values in where condition--1.To Get employee details whose empno is 101,102,103--general queryselect*from employee where empno=101 or empno =102 or empno=103--using In operatorselect*from employee where empno in(101,102,103)--2.To get employee details whose job is either manager or clerk

    select*from employee where job in('manager','clerk')--3.To get employee details whose mgr is either 101,0r 102select*from employee where Mgr in(101,104)--Between and Operator=>Used to give range in where condition--1.To get employee sal between 1000 and 10000select*from employee where sal between 1000 and 10000--2.To get employee details whose joining data is between 20-mar-2008 and 20-jul-2010select*from employee where HireDate between'20-mar-2008'and'20-jul-2010'--Is Operator =>Used to work with null values in the column

    --1.To get employee details whose mgr is nullselect*from employee where Mgr isnull--2.To get employee details whose comm is nullselect*from employee where comm isnull--3.To get employee details whose comm is not nullselect*from employee where comm isnotnull--4.To get Employee Details whose mgr is not nullselect*from employee where Mgr isnotnull--5.To get employee details whose sal is null

    select*from employee where sal isnull--6.To get employee details whose sal is not nullselect*from employee where sal isnotnull--*********************Orderby and Group by***********************--Order by =>Used to display records in the table either ascending or descending--1.To get employee names in ascending orderselect*from employee orderby ename--2.To get employee names in descending orderselect*from employee orderby ename desc

    --3.To get employee sal in ascending orderselect*from employee orderby sal--4.To get employee sal in descending orderselect*from employee orderby sal desc

  • 7/31/2019 Venky SQL Server Metierial

    6/37

    --5.To get jobs in ascending order and sal in descending orderselect*from employee orderby job,sal desc--6.To get the employee details in ascending order whose deptno is 10select*from employee where dno =10 orderby sal--Group by =>Used to group simillar or identical values in the columns of the table--With in the group by statement we can use group fuctions or aggrigate functions

    --****Aggrigate Functions--1.Sum-->Used to get the sum of values--To get the sum of sal in employee detailsselectSUM(sal)from employee--2.Max-->To get the maximum number from set of values--1.To get the maximum value from sal column in employee tableselectMAX(sal)from employee--2.To get maximum value from comm columnselectMAX(comm)from employee--3.Min-->To get the minimum value from the values--1.To get the lowest sal from employeeselectMIN(sal)from employee--2.To get the lowest comm from employeeselectMIN( comm)from employee--4.Count-->To get the count of records in the column--1.To get the count of dno from employeeselectCOUNT(dno)from employee--2.To get the count of dname from employeeselectCOUNT(ename)from employee

    --5.Avg -->To get the average of values--1.To get the average sal from the employeeselectAVG(sal)from employee--2.To get the average comm from the employeeselectAVG(comm)from employee--6.Stdev()-->to get the standard deveation from the employee table--1.To get the standard deveation of sal in employee tableselectSTDEV(sal)from employee--2.To get the satandard deveation of comm in employee table

    selectSTDEV(comm)from employee--7.Var()-->To Get the variance--1.To get the variance of sal in employee tableselectVAR(sal)from employee--2.To get the variance of comm in employee tableselectVAR(comm)from employee--8.count_big()--it is similar to count and it returns big int--To get the count of sal from employeeselectCOUNT_BIG(sal)from employee

    --To get the count of sal from employeeselectCOUNT_BIG(comm)from employee--To get the count of employees in each dept

  • 7/31/2019 Venky SQL Server Metierial

    7/37

    --Group by examples--1.To get the count of employees in each deptselect dno,COUNT(dno)from employee groupby dno--2.To get the count of employees under maheshselect dno,COUNT(dno)from employee where dno=10 groupby dno--3.To get the count of employees under employee 104

    select dno,COUNT(dno)from employee where Mgr=104 groupby dno--4.To get the count of employees under employee 102select dno,COUNT(dno)from employee where Mgr=101 groupby dno--5.Select the deptno from employee morethan 2select dno,COUNT(dno)from employee groupby dno havingCOUNT(dno)>2--6.To get the highest sal from each deptselect dno,MAX(sal)from employee groupby dno--7.To get the Highest sal from each jobselect job,MAX(sal)from employee groupby job--8.To get the minimum sal from employe in each deptselect dno,MIN(sal)from employee groupby dno--9.To get the minimum sal from employee in each jobselect job,MIN(sal)from employee groupby job--10.To get Highest sal from each job and display in descendingselect job,MAX(sal)from employee groupby job orderbyMAX(sal)descselect job,MAX(sal)from employee groupby job orderbyMAX(sal)select job,MAX(sal)as t from employee groupby job orderby t

    --DDLCommands--Create,alter,drop

    --create we have seen above examples--****************Alter Command Usage*******************--To Add or remove table columns--To add or remove constraints--To alter columnscreatetable employee_Alter(eno int,ename varchar(21))--Adding Columns to the employee_Alter by using alter commandaltertable employee_Alteradd sal int

    --Removing column from employee_Alteraltertable employee_Alterdropcolumn sal--Alter existing columns datatypes(Changing ename datatype from varchar to int)altertable employee_AlterAltercolumn ename int--Adding Constraints--Adding Primary key to the employee_Alter table--To Add primary key first we have to add not null constrain to the table--Adding Not null

    Altertable employee_alteraltercolumn eno intnotnull--now we can add primary keyaltertable employee_alter

  • 7/31/2019 Venky SQL Server Metierial

    8/37

    addconstraint pk_emp_alter primarykey(eno)--adding unique key to employee_alteraltertable employee_alteraddconstraint UN_emp_alter Unique(eno)--Droping constraints to the tablesaltertable employee_alterdropconstraint UN_emp_alter--***************Drop********--By using drop command we can drop table,constaints,views,procedures,function--Droping Tabledroptable emp_drop--Droping stored procedures--drop procedure sp_myproc

    --*******************Dml commands***************--Insert--Update--delete--Insert is used to insert the vaues into the tablecreatetable employee_insert(eno int,ename varchar(23))insertinto employee_insert values(101,'mahesh')insertinto employee_insert values(102,'Neena')insert employee_insert values(103,'Mahesh')insert employee_insert values(104,'ljl')--Udate ->Used to update the content in the tableselect*into employee_update from employee_insert

    select*from employee_updateupdate employee_updateset ename='Naresh'where ename='mahesh'--Update by using conditionscreatetable student_update(sidint,sname varchar(20),marks int,total int,avgint)insertinto student_update values(10,'mahesh',30,null,null)insertinto student_update values(102,'Nani',50,null,null)insertinto student_update values(103,'Mahe',30,null,null)select*from student_update

    altertable student_updatedropcolumn marks,total,avgaltertable student_updateadd m1 int,m2 int,m3 int,total int,avgintupdate student_updateset m1=casewhen sname='mahesh'then 89when sname='Nani'then 98

    end,m2=casewhen sname='mahesh'then 90

  • 7/31/2019 Venky SQL Server Metierial

    9/37

    when sname='Nani'then 78end,m3=casewhen sname='mahesh'then 78when sname ='Nani'then 89end

    --now caliculate total and average marks based on m1,m2,m3--1.To update total and avgupdate student_updatesettotal=m1+m2+m3update student_updatesetavg=total/3select*from student_update

    altertable student_updateadd division varchar(12)update student_updatesetdivision=casewhen total >260 and total

  • 7/31/2019 Venky SQL Server Metierial

    10/37

    --in average caliculated column if you write--average as (total)/3 it will cause error--because you cannot create caliculated column based on another caliculated columninsertinto student_Caliculated(sid,sname,m1,m2,m3) values(101,'mahesh',78,87,99)insertinto student_Caliculated(sid,sname,m1,m2,m3)values(102,'Neena',89,89,8)select*from student_Caliculatedupdate student_Caliculatedset m1=63wheresid=102select*from student_Caliculated--*******************Top Key word ****************--top keywrod has several features like delete or update singlerow from two duplicaterows--and caliculating highest salary etc.--updating single record from two simillar recordscreatetable student(sidint,sname varchar(12))

    insert student values(101,'mahesh')insert student values(101,'mahesh')

    select*from studentupdatetop(1) student setsid=102 where sname ='mahesh'--Caliculating Highest sal's from employee table with out Top keyword--select 1st highest sal from employeeselectMAX(sal)from employee--select 2 nd highest sal from emploeeselectMAX(sal)from employee where sal

  • 7/31/2019 Venky SQL Server Metierial

    11/37

    selectMIN(sal)from employee--to get the second lowest sal with out top keywordselectMIN(sal)from employee where sal>(selectMIN(sal)from employee )--to get the third highest sal from employee with out top keywordselectMIN(sal)from employee where sal>(selectMIN(sal)from employee wheresal>(selectMIN(sal)from employee))--to get the fourth highest sal from employee with out top keywordselectMIN(sal)from employee where sal>(selectMIN(sal)from employee wheresal>(selectMIN(sal)from employee where sal>(selectMIN(sal)from employee)))--Caliculating Lowest sal Usin TOp keyword--To get the first lowest sal from employeeselecttop(1) sal from employee order by sal--To get the second lowest sal from employeeselecttop(1) sal from (selectdistincttop(2) sal from employee orderby sal )aa orderbysal desc--To get the third lowest sal from employee

    selecttop(1) sal from(selectdistincttop(3) sal from employee orderby sal ) aa orderbysal desc--To get the fourth lowest sal from employeeselecttop(1) sal from(selectdistincttop(4) sal from employee orderby sal) aa orderbysal desc

    --********************Constraints ********************************--Constraints is nothing but conditions on the table--we can apply constraints to the table column level as well as table level

    --Column level-->if you apply constraint end of perticular columncreatetable student_columnlevel(sidintprimarykey,sname varchar(12)unique)--Table level-->If you apply constraint at the end of table creationcreatetable student_tablelever(sidint,sname varchar(12),primarykey(sid),Unique(sname))--Constraints--Unique-->>(It will accept new values and allow one null value)--Not null-->>(It will not accept null values but it will accept duplicate values)--Primary Key-->(This is combination of unique and not null constraints it will accept

    new values and doesnot accept null values)--Foreign Key -->This is to maintaine referential integrity--Check Constraint-->Used to give condition on the column--1.Uniquecreatetable student_Unique(sidintUnique,sname varchar(12))insertinto student_Unique values(101,'mahesh')--insertedinsertinto student_Unique(sname)values('mahesh')--inserted-->here allowing first nullvalueinsertinto student_Unique(sname)values('Neena')--it willnot insert because unique will

    allow only one null value--2.Not NUllcreatetable student_notnull(sidintnotnull,sname varchar(23))insertinto student_notnull values(101,'mahesh')--inserted

  • 7/31/2019 Venky SQL Server Metierial

    12/37

    insertinto student_notnull(sname)values('mahe')--it will not insert because the sidshould not be nullinsertinto student_notnull values(101,'mahesh')--inserted even it is duplicate value--3.Primary keycreatetable student_PrimaryKey(sidintprimarykey,sname varchar(12))insertinto student_PrimaryKey values(101,'mahesh')--insertedinsertinto student_PrimaryKey values(101,'mahesh')--not inserted because it will notallow duplicate valuesinsertinto student_PrimaryKey(sname)values('mahesh')--not inserted because primarykey column should not be nullinsertinto student_PrimaryKey(sid)values(102)--inserted--4.Foreign key--create parent table--(parent table should contain primary key)createtable product(pid intprimarykey,pname varchar(15),price smallmoney)insertinto product values(10,'soaps',100)insertinto product values(20,'cloths',2000)

    insertinto product values(30,'computers',12000)--now create a child tabel with foreign key constraintscreatetable items(itemid int,itemname varchar(12),mrp smallmoney,Pid intreferencesproduct(pid))insertinto items values(101,'soaps',900,10)--insertedinsertinto items values(101,'soaps',344,10)--With in the child tabel having primary key or not that is your wish--deleting records from parent tabledeletefrom product where pid=20--deleted

    update product set pid=12 where pid=10--not updateddeletefrom product where pid=10 --not deleted--you cannot delete/update parent records directly if the parent record contains relationwith child records.--To delete or update parent records we have two options--option-1.first delete the all associated child records and then delete parent records--option-2.while creating child table you can use On delete cascade ,On update cascade-- creating child table by Applying On delete cascade and On update cascade--creating parent table

    createtable product_parent(pid intprimarykey,pname varchar(12))insertinto product_parent values(10,'Computers')insertinto product_parent values(20,'Soaps')insertinto product_parent values(30,'Mobiles')--creating child table having foreign key with on delete cascade and on update cascadecreatetable Items_Child(ItemId intprimarykey,Item_name varchar(12),Pid intreferences Product_parent(Pid)ondeletecascadeon updatecascade)insertinto Items_Child values(101,'keyboards',10)insertinto Items_Child values(102,'mouse',10)

    --Update parent table pid to 33update product_parent set pid =33 where pid=10--this will executes and effects on childrecords also--check child records

  • 7/31/2019 Venky SQL Server Metierial

    13/37

    select*from Items_Child--the pid column values changes from 10 to 33--5.Check Constraint--Create table employee_Check with check constraintcreatetable Employee_Check(eno int,ename varchar(12),sal int,check(sal between 1200and 2000))insertinto Employee_Checkvalues(10,'mahesh',1000)--It will not insert because sal mustbe between 1200 to 2000insertinto employee_Checkvalues(20,'Neena',1200)--insertedinsertinto Employee_Checkvalues(10,'Mahe',2000)--insertedselect*from Employee_Check

    --**********************SubQueries*******************************--Query with in the another query is called sub query--1.To get the details of employee with highest salselect*from employee where sal=(selectmax(sal)from employee)

    --2.To get the details of employee with second highest salselect*from employee where sal=(selectmax(sal)from employee where sal(selectAVG(sal)from employee)--Examples on SubQueries--Take two tables with name s1 and s2createtable s1(sidintprimarykey,sname varchar(12),marks int)insertinto s1 values(10,'mahesh',99)insertinto s1 values(20,'Neena',90)insertinto s1 values(30,'Mahe',90)insertinto s1 values(40,'Naresh',98)createtable s2(sidintprimarykey,module varchar(12),faculty varchar(12))insertinto s2 values(10,'c#','suresh')insertinto s2 values(20,'dotnet','ramesh')insertinto s2 values(40,'java','mahe')

    --Queries using above tables--1.To get the details of the student who are learning java.select*from s1 wheresid=(selectsid from s2 where module='java')--2.To get the students list who are learning dotnet.select*from s1 wheresid=(selectsidfrom s2 where module='dotnet')--3.To get the details of the student who are learning javaselectCOUNT(sid)as cc from s2 groupby module havingCOUNT(sid)>1--4.To get the details of employee working in 10 th deptno

    select*from employee where empno in(select empno from employee where dno=10)--*********Nested SubQuries*****************--if select statement contains 3 or more than three then those queries called subqueries--1.To get the third highest sal from employee table

  • 7/31/2019 Venky SQL Server Metierial

    14/37

    select*from employee where sal=(selectMAX(sal)from employee where sal(selectMIN(sal)from employee )))

    --*********Correlated SubQueries**************--In Correlated sub query the main query will execute first and then the value--of the main query will be used by sub query--1.To get the first highest sal from employee tableselect*from employee e where 0=(selectCOUNT(distinct sal)from employee m wherem.sal>e.sal)--2.To get the second highest sal from employee tableselect*from employee a where 1=(selectCOUNT(distinct sal)from employee x wherex.sal>a.sal)--3.To get the third Highest sal from employeeselect*from employee x where 2=(selectCOUNT(distinct sal)from employee x1where x1.sal>x.sal)

    --************Set Operators****************--It is used to work on multiple tables used to join the records of different tables but thecolumn names should be same in all tables.--1.Union:Used to display unique values from the different tables--2.Union all:Used to display all values from the diffrent tables even records areduplicate.--3.Intersect:Display similar values existing from both the tables--Examples--4.Except:Used to display values from the first table which are not in second table--Create two table with name oldlanguages,and newlanguages--creating oldlanguages tablecreatetable oldlanguages(subjectvarchar(12))insertinto oldlanguages values('c')insertinto oldlanguages values('c++')insertinto oldlanguages values('cobal')insertinto oldlanguages values('pascal')

    --Creating NewLanguages tablecreatetable newlanguages(subjectvarchar(10))insertinto newlanguages values('DotNet')insertinto newlanguages values('java')insertinto newlanguages values('c++')--Unionselect*from oldlanguages unionselect*from newlanguages--here you will get unique values from both the tables--Union all

    select*from oldlanguages unionallselect*from newlanguages--here you will get all the values from both the tables even duplicate values--intersectselect*from oldlanguages intersect select*from newlanguages

  • 7/31/2019 Venky SQL Server Metierial

    15/37

    --here you will get common values existing in the both tables--Exceptselect*from oldlanguages exceptselect*from newlanguages unionselect*fromemployee--it displays values from the first table which are not in second table

    --************************Joins**************************

    --used to work with multiple tables used for joining the columns of different tables.--In sqlserver 8 to 10 tables can be joined.--We have two types of joins--1.Inner Joins

    --I.Self Join--II.Equi Join--III.NaturalJoin--IV.Non Equi Join

    --2.Outer Joins--I.Left outer Join--2.Right Outer Join--3.Full Outer Join

    --1.Equi join :if the tables can be joined by using '=' symbolcreatetable dept(dno intprimarykey,dname varchar(12),location varchar(12))insertinto dept values(10,'Accounts','hydrabad')insertinto dept values(20,'Baking','khammam')insertinto dept values(30,'It','khammam')createtable emp(eno intprimarykey,ename varchar(12),sal int,dno intreferencesdept(dno))

    insertinto emp values(101,'mahesh',1000,10)insertinto emp values(102,'Neena',2000,10)insertinto emp values(103,'Mahe',4000,20)insertinto emp values(104,'Nani',2300,20)--Equi join:if the two tables are joined by using '=' operator then--that join is called equi join--To get the employee details working in dept 10select e.eno,e.ename,d.dno,d.dname from emp e,dept d where e.dno=d.dno--Non Equi join:If the two tables are joined by using

    --Create the following tablescreatetable emp_ex1(eno int,sal int)insertinto emp_ex1 values(101,1000)insertinto emp_ex1 values(102,2000)createtable emp_ex2(eno int,sal int)insertinto emp_ex2 values(10,200)INSERTinto emp_ex2 values(20,100)--To get the employees details from emp_ex1 whose sal is greater than emp_ex2select e.eno,e.sal,e1.eno,e1.sal from emp_ex1 e,emp_ex2 e1 where e.sal>e1.sal

    --To get the employees details from emp_ex2 whose sal is less than emp_ex1select e1.eno,e1.sal,e.eno,e.sal from emp_ex1 e1,emp e where e1.eno

  • 7/31/2019 Venky SQL Server Metierial

    16/37

    select e.empno,e.ename,e.mgr,d.empno,d.ename,d.mgr from employee e,employee dwhere d.empno=e.Mgr--legacy join--in any join if you use on condition then it is called legacy join and it is lossy joinselect empno,ename,dno,d.deptno,d.dname from employee innerjoin department d ondno=d.deptno--instead of where condition we used here on operator--Natural join:If two tables are joind without any condition it is called Natural join--or if two tables are joined without '='symbolselect empno,ename,sal,deptno,dname,loc from employee,department--Outer Joins:If the tables are not having matched record then Outer joins are used--1.Left Outer join:It will takes all the records from the first table and joins with secondtable--Create two tables dept_Outer and emp_outercreatetable dept_outer(dno intprimarykey,dname varchar(23),location varchar(12))insertinto dept_outer values(10,'Accounts','Hyderabad')

    insertinto dept_outer values(20,'Banking','Khammam')insertinto dept_outer values(30,'It','Hyderabad')createtable emp_outer(eno intprimarykey,sal int)altertable emp_outeradd dno intreferences dept_outer(dno)insertinto emp_outer values(101,1000,10)insertinto emp_outer values(102,1022,20)

    --Queries on Left Outer joinselect eno,sal,dept_outer.dno,dname,location from dept_outer leftouterjoin emp_outer

    on dept_outer.dno=emp_outer.dnoselect eno,sal,dept_outer.dno,dname,location from dept_outer,emp_outer wheredept_outer.dno=emp_outer.dnoselect eno,sal,dept_outer.dno,dname,location from dept_outer leftouterjoin emp_outeron dept_outer.dno=emp_outer.dno--Right outer join : In this join it will take all the records from the second table and joinswith first tableselect eno,sal,dept_outer.dno,dname,location from emp_outer rightouterjoin dept_outeron dept_outer.dno=emp_outer.dno

    Select dept_outer.dno,dname,location,eno,sal from emp_outer rightouterjoin dept_outeron dept_outer.dno=emp_outer.dno--Full outer join:This is the combination of right and left outer joinselect A.eno,A.sal,B.dno,B.dname,B.location from emp_outer A fullouterjoindept_outer B on A.dno=B.dno

    --

    *****************************Views****************************--A view is a logical table used to display records information from the table

    --View will generate by using select statement--View will not store any data and will not use any memory.--Creating view

  • 7/31/2019 Venky SQL Server Metierial

    17/37

    createview View_emp_dno10asselect*from employee where dno=10select*from employee--Executing viewselect*from View_emp_dno10--Altering Viewalterview View_emp_dno10asselect*from employee where dno=20--Droping the existing viewdropview View_emp_dno10

    --Types of views--1.Simple views:It can be created by using simple select statement--2.complex views:It can be created by using Order by,Group by and joins--3.Materialized views:if a clustered or non clustered index is applied on view then that

    view------is called materialized view.

    --Example on Simple View--Create View on employee that gives only dept 10 employee detailscreateview View_dept10asselect*from employee where dno=10--view created --check viewselect*from View_dept10

    --Crate view on employee details which has to give all dept 20 detailscreateview view_dept20asselect*from employee where dno=20--execute view_dept20select*from view_dept20

    --We can perform all dml operations on views.--what ever modifications you are doing on views the modifications affects on original

    table--Insert one record into the table by using viewsinsert View_dept10 values(108,'Mahe','salesman',104,'09-mar-2010',2000,100,20)select*from employee--update one record of view_dept10update View_dept10set job='clerk'where job='salesman'select*from View_dept10--delete one record from view_dept10

    deletefrom view_dept20where empno=107select*from view_dept20--Altering the views

  • 7/31/2019 Venky SQL Server Metierial

    18/37

    alterview view_Dept10asselect*from employee where Mgr isnull--Check itselect*from view_Dept10--Result is all employee details whose mgr is null--Droping viewdropview view_Dept10--With Check OPtion and With out check option--Create a view that gives all employee detailscreateview view_without_Check_10asselect*from employee where dno=10--Insert one record with dno=20 using the above viewinsert view_without_Check_10 values(107,'Mahes','clerk',104,'23-mar2000',2000,200,20)

    --Record is inserted --here the view always gives employee details with dno=10--if you want to restrict the insertion of another dept details we can use with check optio--Create a view with check optioncreateview view_with_Check_10asselect*from employee where dno=10 withcheckoption--Now try to insert the another dept valuesinsert view_with_Check_10values(108,'mahe','salesman',104,'9-mar-2000',2999,200,20)--You will get an error

    --the attempted insert or delete or update failed bcz target view eithere specifies withcheck option--Complex Views :If the view contains group by or order by or joins .--Examples on complex views--1.create view that gives all employee details in ascending order based on salcreateview view_sal_ascendingasselecttop(154156)*from employee orderby salselect*from view_sal_ascending

    --create view for getting first highest salcreateview view_first_highest_salasselect*from employee where sal=(SELECTtop(1)sal from(selecttop(1)sal fromemployee orderby sal desc)aa orderby sal)select*from view_first_highest_sal--Create view fro getting second highest salcreateview view_second_highest_salas

    select*from employee where sal=(SELECTtop(1) sal from (SELECTtop(2) sal fromemployee orderby sal desc)aa orderby sal)select*from view_second_highest_sal--Create view for getting second lowest sal

  • 7/31/2019 Venky SQL Server Metierial

    19/37

    select*from employee where sal=(selecttop(1)sal from(selectdistincttop(2)sal fromemployee orderby sal)aa orderby sal desc)--Create view for getting third lowest salselect*from employee where sal=(SELECTtop(1) sal from (SELECTdistincttop(3)salfrom employee orderby sal )aa orderby sal desc)--Create view for getting fourth lowest salselect*from employee where sal=(SELECTtop(1) sal from (selectdistincttop(4) salfrom employee orderby sal )aa orderby sal desc)select*fromsysobjectswheretype='v'---Views with schema binding--if a view is created with schema binding the table name we cannot changecreateview my_scema_view1 withschemabindingasselect empno,ename from dbo.employeesp_rename'employee.ename','maheshname'--it will give you error--object 'employee.ename' cannot be renamed because the object participates in enforced

    dependencies.--********Materialized views *******--this concept is attached at the ending of Indexes concept.

    --********************Indexes**********************************--Indexes are used for faster access of records and display recorords in ascending orderor descending order.--Indexes in sqlserver automatically works there is no need to open and close an index.--Types of indexes

    --1.Clustered index--If you apply Primary key on perticular column the clustered index will automaticallycreate for that perticular column.--Clustered index will change the physical arrangement of the table.--A table can containe only one clustered index that means only one primary key.--Example:Craete clustered index on normal table--Ascending order--step1:Create table with out primary key--step2:Apply clusterd index on that tablecreatetable emp_Clust_example(cid int,cname varchar(12))

    --Creatin clustered index on Emp_Clust_Examplecreateclusteredindex my_index on emp_Clust_example(cid)--insert some recordsinsertinto emp_Clust_example values(10,'mahesh')--insertedinsertinto emp_Clust_example values(10,'mahesh')--inserted--because if you apply primary key for the perticular column the clustered index willautomatically created but reverse is----not possible--Dont think if you apply clustered index primary key will also apply.

    --applying clustered index only for performance base.--Example:Craete clustered index on normal table--Descending ordercreatetable emp_clust_desc(dno int,dname varchar(12))--create clustered index in descending order

  • 7/31/2019 Venky SQL Server Metierial

    20/37

    createclusteredindex clust_desc on emp_clust_desc(dno desc)--insert some values and execute select command on this table all the records will beappeare in descending order--because the clustered index changes physical order of the table.

    --***Non Clustered Index--This is also to improve the performance of accessing records,--If you apply the Unique key the non clustered index will automatically created for thatcolumn but reverse is not possible.--we can create upto 249 non clustered indexes on table--Non clustered index willnot change the physical order of the tabel.--create sample table with primary key or with out primary key and apply the nonclustered index on itcreatetable Employee_nonclust_asc(eno intprimarykey,ename varchar(12))createnonclusteredindex emp_non_asc on employee_nonclust_asc(eno)--the non

    clustered index is created--another example --on ascending ordercreatetable emp_nonclust_asc(eno int,ename varchar(12))createnonclusteredindex emp_non_asc1 on emp_nonclust_asc(eno)--Nonclustered index descending ordercreatetable emp_nonclust_desc(eno int,ename varchar(12))createnonclusteredindex emp_nc_desc on emp_nonclust_desc(eno)--***********Working with multiple non clustered indexes************--we can create up to 249 non clustered indexes on the table ..

    --by using include we can apply multiple nonclustered indexes at a time.createtable emp_multiple_non(eno int,ename varchar(12),job varchar(21),mgr int,salint,comm int,dno int)createnonclusteredindex emp_multiple_non_1 on emp_multiple_non(eno)include(ename,job,sal,mgr,dno,comm)---Materialized veiws--If indexes are created on views is called Materialized views.----applying clustered and non clustered index on views.createview my_materialized withschemabinding

    asselect empno,ename,sal,dno from dbo.employee

    createuniqueclusteredindex my_clust_materializedonmy_materialized(empno)createnonclusteredindex my_clust_materialized12on my_materialized(ename)createview my_met1 withschemabinding

    asselect empno,dno,mgr from dbo.employeecreateuniqueclusteredindex my12on my_met1(empno)

  • 7/31/2019 Venky SQL Server Metierial

    21/37

    --***************SystemDefined Functions in Sqlserver**************8--I.Numeric funcitons

    --1.abs():returns absolute value.selectABS(40)--ans is :40--2.len():to find out the length og the string.selectLEN('Mhaesh')--ans is :6

    select ename,LEN(ename)from employeeselect job,LEN(job)from employee--3.ceiling:Returns the next integer valueselectCEILING(33.89)--ans is :34--4.Floor:Removes the decimal value and return integer value.selectFLOOR(33.99)--ans is :33--5.Round():Returns the decimal value according to the given argument.selectROUND(45.8990909,3)--ans is :45.8990000selectROUND(34.9827888,3)--ans is :34.9830000

    --II.String Functions:--1.Ascii():returns ascii values for the given charecterselectASCII('z')--ans is :122selectASCII('a')--ans is :97--2.lower():Returns string in lower case.selectLOWER('MAHESH')--ans is :maheshselectLOWER('NARESH')--ans is :naresh--3.LTrim():Removes unwanted spaces before the Given string.selectLTRIM(' mahesh')--ans is :mahesh--4.Reverse():Returns reverse of the stringselectREVERSE('mahesh')--ans is hsehamselectREVERSE('Neena')---ans is :aneeN--5.Space():Retruns no of charecter spaces according to the given argument.print'sai'+space(2)+'ram'--ans is : sai ramprint'naresh'+space(2)+'is'+space(2)+'the best institute'--ans is :naresh is the best

    institute--6.Substring():Returns the charecters according to the given argument.selectSUBSTRING('Striveforournation',7,12)--ans is:forournationselectSUBSTRING('mahesh',1,4)--ans is :mahe

    --7.soundex():Returns the string according to the pronounciation,It will not check thespelling.

    createtable soundex_a(sno int,sname varchar(123))insertinto soundex_a values(10,'smith')insertinto soundex_a values(20,'shmith')select*from soundex_a where soundex(sname)=soundex('smyth')--result is :--10 smith--20 shmith

    --III.Group or Aggrigate Functions--1.sum():returns the sum of the integersselectSUM(sal)from employee--ans is :63400.00--2.Avg():returns the avg of integer values

  • 7/31/2019 Venky SQL Server Metierial

    22/37

    selectAVG(sal)from employee--ans is :9057.1428--3.min():returns the minimum value from set of integersselectMIN(sal)from employee--ans is:2000--4.max():returns the maximum value from set of integersselectMAX(sal)from employee--ans is :30000--5.count():returns the count of records from the tableselectCOUNT(dno)from employee--ans is :7

    --IV.Date Functions--1.Getdate():returns the current date and timeselectGETDATE() --ans is:2011-07-28 17:15:30.437--2.day():To get the current dayselectDAY(GETDATE())--ans is 28--3.Month():Returns the month of the year.selectMONTH(getdate())--ans is 2--4.year():To get the yearselectYEAR(getdate())--ans is 2012

    --DatePart():Is used to get small part of the date and timeselectDATEPART(DY,getdate()) --ans is: 209

    --V.Convert():Used to convert datatypes form one type to another typeselectCONVERT(varchar(12),getdate())--feb 26 2012

    ---******************************PL/SQL************-Procedural languageor structured query language--Declaring Variables

    --local variables @a--global variables @@a

    --exampledeclare @a int--declaring local variableset @a=1000 --assigninn value to the declared variable by usin set or selectprint @a --printing

    --II.Conditional Statements--1.If:--if --statement(s)--else

    --statement(s)--end--example:write a program to check wheather the given no is greater than 50 or not.declare @a intselect @a=33if@a>50print @a+'is greater than 50'elseprintcast(@a asvarchar(12))+'is less than 50'

    --2.case:(Acts like switch)--case--when then--when then

  • 7/31/2019 Venky SQL Server Metierial

    23/37

    --else --end--example:write a program to to give user tdeclare @a charset @a='d'select*from employee orderbycasewhen @a='d'then dnowhen @a='y'then empnoend--3.while--while --begin--stmts--enddeclare @a int

    select @a=1while @a

  • 7/31/2019 Venky SQL Server Metierial

    24/37

    --[with recompile]--as begin--stmts--end

    --Executing--exec argruments

    --Droping--drop procedure

    --Examples--1.Create a procedure that displays the th dept details given by the useralterproc proc_tablefind @a intwithrecompileasbeginselect*from employee where dno=@aend

    exec proc_tablefind10--2.Create procedure that print the sum of two numberscreateproc proc_sum @a int,@b intwithrecompileasbeginprint @a+@b

    endexec proc_sum12,33

    --3.Create procedure that print 1 to 100 numberscreateproc proc_firsttenwithrecompileasbegindeclare @a intselect @a=1while @a @bprint @a-@belse

  • 7/31/2019 Venky SQL Server Metierial

    25/37

    print @b-@aendexec proc_substract120,23--5.create a procedure that takes empno as a argument and delete that recordcreateprocedure proc_ename_Delete @eno intasbegindeletefrom employee where empno=@enoprint'The record is deleted'end--6.Create a procedure that accept the 2 args for updating salcreateproc proc_Emp_Update @eno int,@sal intasbeginupdate employee set sal=@sal where empno=@enoprintcast(@eno asvarchar)+'Is Updated'

    endselect*from employeeexec proc_Emp_Update103,5000select*from employee--7.Create a procedure to insert new records in the employee tablecreateproc proc_Emp_insert @eno int,@ename varchar(15),@job varchar(15),@mgrint,@hiredate date,@sal int,@comm int,@dno intasbegin

    insertinto employeevalues(@eno,@ename,@job,@mgr,@hiredate,@sal,@comm,@dno)print'Row is inserted'endexec proc_Emp_insert108,'mahesh','manager',null,'23-mar-2000',20000,null,20select*from employee

    --************************ExceptionHandling************--while working with programs 3 types of errors will arise--1.compilation Errors

    --2.Logical Errors--3.Runtime errors

    --Compilation errors and logical errors can be recified by the programmer whiledeveloping.--but runtime errors will be managed by the Exception handling.--Synatx:Begin Try

    --Statements--End Try--Begin Catch

    --StateMents--End Catch--Example On Try Catch blocks--Create procedure for division of two numbers

  • 7/31/2019 Venky SQL Server Metierial

    26/37

    createproc proc_div @a int,@b int,@c intasbegintryselect @c=@a/@bprint @cendtrybegincatchselectERROR_NUMBER(),ERROR_MESSAGE()endcatch--execute the procedureDeclare @aa intexec proc_div12,2,@aa--Out Put is :6Declare @ab intexec proc_div23,0,@ab--you will get an output as follows--8134 Divide by zero error encountered.--In the above programm error_number(),error_message() are predifined function

    *************TRANSACTIONS*************--Set of sqlcommands will be executed as a unit or block.--To start the transactions BEGIN TRANSACTIONS .--To end the trasactions ROLLBACK OR COMMIT.--Rollback is used to cancell the execution of all commands.--commit is used to make changes effect on the table.--Examples--Create a table by using Into Keyword

    select*into employee_transactions from employeeselect*from employee_transactions--here you will get all employee records--which are copied from the employee table--Example1-To Delete records from the tablebegintransactiondeletefrom employee_transactionsselect*from employee_transactions--This command willnot display any records becauseall records are deletedrollback--here roll back is performed so all above commands will be cancelled .

    --if you execute the above transaction the those commands will not do any changes toyour tableselect*from employee_transactions--you will get all records--Example2:createproc emp_mytrasbeginbegintransactiondeletefrom employee_transactions

    rollbackendexec emp_mytr--here you will get message 7 rows affected but after that rollback willwork

  • 7/31/2019 Venky SQL Server Metierial

    27/37

    select*from employee_transactions--Exampl3:begintransactiondroptable employee_transactionsrollbackselect*from employee_transactions--rollback will work on truncate,delete,drop--Save Point--It is used to rollback few statements in the Transaction--Syntax:Save Transaction --ExampleOn SavePoint:begintransactionsavetransaction Ts1

    begindeletefrom employee_transactions where dno=10select*from employee_transactions

    endsavetransaction ts2deletefrom employee_transactions where dno=20savetransaction Ts3deletefrom employee_transactions where dno=30Rollbacktransaction ts3

    --all transactions will commited except ts3--Example 2:begintransaction

    savetransaction TS1begin

    deletefrom employee_transactions where dno=10select*from employee_transactions

    endsavetransaction TS2

    begindeletefrom employee_transactions where dno=20select*from employee_transactions

    endsavetransaction TS3

    begindeletefrom employee_transactions where dno=30select*from employee_transactions

    endrollbacktransaction ts1committransaction ts2committransaction ts3

    --In the above example we will not loose even single record because if you perform rollback--on first transaction(ts1) automatically the rollback operation will perform on succeeded

  • 7/31/2019 Venky SQL Server Metierial

    28/37

    --transactions(ts2,ts3) event you write commit also.

    *****************TRIGGERS****************--Trigger is a programm which will raise when ever peritcular action is done.--Types of triggers--DDL Triggers:These triggers are created on database and on server also.

    --DML Triggers:These triggers are created on Table.--DDL Triggers:--we have Create_table,drop_table,alter_table triggers.--By using this ddl triggers we can restrict creating,altering,droping tables on your

    database.--Syntax for Creating DDL triggers on Database:--selecting database

    --select your database where you want to write trigger by using following stmt.--use

    --creating trigger--create trigger --on database--for [create_table|drop_table|alter_table]--as--begin--rollback--print or raiserror()fuction--end

    --Altering trigger

    --alter trigger --on database--for [create_table|drop_table|alter_table]--as--begin--rollback--print or raiserror()fuction--end

    --Syntax for Droping Trigger on Database:

    --drop trigger on database--1.Create trigger which will not allow user to create table in your database.createtrigger mahesh_tr_Createondatabasefor create_tableasbeginrollbackRAISERROR('you cannot create table on this database',12,1)

    endcreatetable mahe(aa int)--you will get following error--Msg 50000, Level 12, State 1, Procedure mahesh_tr_Create, Line 7--you cannot create table on this database

  • 7/31/2019 Venky SQL Server Metierial

    29/37

    --Msg 3609, Level 16, State 2, Line 1--The transaction ended in the trigger. The batch has been aborted.

    droptrigger mahesh_tr_Create ondatabase--2.Create Trigger on Mahesh database which will not allow you to alter and drop

    tables.createtrigger mahesh_tr_drop_alterondatabasefor drop_table,alter_tableasbeginrollbackraiserror('Mahesh is not allowing to alter,drop on his database',15,2)enddroptable employee--you willget erroraltertable employeeadd eaddress varchar(23)

    --you will get an error message as follows--Msg 50000, Level 15, State 2, Procedure mahesh_tr_drop_alter, Line 7--Mahesh is not allowing to alter,drop on his database--Msg 3609, Level 16, State 2, Line 1--The transaction ended in the trigger. The batch has been aborted.droptrigger mahesh_tr_drop_alter

    --Syntax for Creating DDL triggers on Server:--create trigger --on all server

    --for [create_table|drop_table|alter_table]--as--begin--rollback--print or raiserror()fuction--end

    --Syntax for Altering DDL triggers on Server:--alter trigger

    --on all server--for [create_table|drop_table|alter_table]--as--begin--rollback--print or raiserror()fuction--end

    --Syntax for Droping ddl triggers on server

    --drop trigger on all server--Example1:Create a trigger which will not allow users to create,alter,drop tables onserver.

  • 7/31/2019 Venky SQL Server Metierial

    30/37

    createtrigger mahe_serveronallserverfor create_table,alter_table,drop_tableasbeginrollbackprint'mahesh is not allowing to create any databases on server'end

    --droping the trigger on server .droptrigger mahe_server onallserver

    --DML Triggers:(apply for tables)--dml triggers are used to perform action when insert,update,delete commands are

    executed on table--Sql server supports afterinsert,afterdelete,afterupdate triggers only .--oracle supports after and before triggers.--Magic Tables:

    --These tables contains the columns of the table on which trigger is created.--Magic tables will exists only at the time of trigger execution.--TypesOfMagic tables:--1.Inserted:new records you have entered in the table.--2.Deleted:The records deleted from the table will be stored.

    --Syntax for Creating Dml Triggers on Table:--create trigger --on --for [Insert|Update|Delete]

    --as--begin--statements (Which operation you want to perform)--end

    --Syntax for Altering Dml Triggers on Table:--alter trigger --on --for [Insert|Update|Delete]--as

    --begin--statements (Which operation you want to perform)--end

    --Syntax for Droping Dml Trigger On Table:--drop trigger

    --1.Create trigger which will not allow user to insert or update or delete any record from--Employee table

    createtrigger mahesh_tron employee

    forinsert,update,deleteasbeginselect*from inserted--for getting records from magic tables

  • 7/31/2019 Venky SQL Server Metierial

    31/37

    select*from deleted--for getting records from magic tablesendinsertinto employee values(104,'mahesh',3000)--here record will be inserted because you did not perform rollback operation.--2.Update the above trigger by writing the rollback in triggeraltertrigger mahesh_tron employeeforinsert,update,deleteasbeginrollbackselect*from inserted--for getting records from magic tablesselect*from deleted--for getting records from magic tablesendinsertinto employee values(105,'mahesh',3000)--here the records will not be inserted.

    --3.Write a trigger that will not allow user to add,update,delete before 11 am and after 8pmcreatetrigger mahesh_time_triggeron empforinsert,update,deleteasbegindeclare @@dt intselect @@dt=DATEPART(HH,getdate())

    if@@dt notbetween 12 and 20beginrollbackprint'You cannnot performa any operation between 12 am and 8 pm'endend--note it will take server time--3.Create a trigger Which will not allow you to delete multiple records at a time fromMahe_triggers.

    createtrigger mahe_tr_Restrict_multiple_recordson mahe_triggersfordeleteasbeginif((SELECTCOUNT(*)from deleted)>1)beginrollbackprint'You cannot delete multiple records at a time'

    endenddeletefrom mahe_triggers--here you will get an error as follows

  • 7/31/2019 Venky SQL Server Metierial

    32/37

    --You cannot delete multiple records at a time--Msg 3609, Level 16, State 1, Line 1--The transaction ended in the trigger. The batch has been aborted.---INSTEAD OF TRIGGERS--with the above normal triggers(after triggers) when insert command is executed

    --the new values will go to the table after that the new values will be inserted inmagic tables.

    --With the Instead of triggers when insert command is executed the new values will goto the

    -- inserted magic table first and it will work on views and tables.--Normal triggers will not work on views.

    --1.Create an instead of trigger on emp table which willnot allow you to insert records.createtrigger mahe_instead_inserton empinsteadofinsertas

    begindeclare @eno int,@ename varchar(12),@sal int,@dno intselect @eno=eno,@ename=ename,@sal=sal,@dno=dno from insertedprint @enoprint @enameprint @salprint @dnorollbackprint'record is not inserted'

    end--Insert any values

    insertinto emp values(122,'mahesh',9999,10)--This record willnot be inserted out putas follows

    -- 122-- mahesh-- 9999-- 10-- record is not inserted

    -- Msg 3609, Level 16, State 1, Line 1-- The transaction ended in the trigger. The batch has been aborted.

    *************Functions*********--Functions are used to reduces the burden of writing the same statements again andagain.--It always returns value.--By using stored procedures you cannot return bool type but with functions we canreturn

    --any statandard datatypes.--Types :1.System or Predefined functions--2.User Defined Functions

    --Syntax for User Defined Functions

  • 7/31/2019 Venky SQL Server Metierial

    33/37

    --create function (args)--returns --as--begin--statements--returns--end

    --Syntax for altering The functions--alter function (args)--returns --as--begin--statements--returns--end

    --To Execute The function

    --select dbo. args--To drop the function--Drop function --To see all functions in current database--select * from sysobjects where type='fn'--Examples:--1.Write a function that returns the cube of the given numbercreatefunction find_cube(@a int)returnsint

    asbeginreturn @a*@a*@aend--Executionselect dbo.find_cube(6)--ans is 216select dbo.find_cube(122)--ans is 1815848

    --2.Create a function that takes any string and convert into Upper charecterscreatefunction fun_to_upper(@aa varchar(max))

    returnsvarchar(max)asbeginreturnupper(@aa)end--executeselect dbo.fun_to_upper('abcdefghijklmnopqrstuvwxyz')--ans is:ABCDEFGHIJKLMNOPQRSTUVWXYZ--3.Create a function that returns the area of the rectangle

    createfunction fun_find_rect_area(@a int,@b int)returnsintasbegin

  • 7/31/2019 Venky SQL Server Metierial

    34/37

    return @a *@bend--Executeselect dbo.fun_find_rect_area(12,212)--ans is:2544--4.Create a function that accept empno and returns sal from employee tablecreatefunction fun_find_sal(@a int)returnsintasbegindeclare @b intselect @b=sal from employee where empno=@areturn @bend--Execute the functionselect dbo.fun_find_sal(101)--ans is 20000--5.Create a function that accept dno and returns records of employee who ever working

    under that deptno.createfunction fun_get_emp_details_under_dno(@dno int)returnstableasreturn(select*from employee where dno=@dno)--Execute the functionselect*from dbo.fun_get_emp_details_under_dno(10)--here while executing we havet to use select * from because * is misellenious datatype

    *****************CURSORS*****************--Cursor is a memory location where sqlserver tables are stored .It can be implicit or

    --It can be explicit cursor.--Types Of cursors:1.Implicit Cursors:the memory location is created by the sql server

    -- and select statement uses these implicit cursors.--If you use implicit cursors you will get all records at a time.

    --2.Explicit Cursors:--If memory location is created by the user then it is called Explicit cursor.

    --In this cursor we can store any number of tables.--But the tables stored in explicit cursors can display records one by one.

    --types Of Cursors--1.static:After creating explicit cursor the changes done in the table will not effected

    --in the cursor.--2.Dynamic:After creating explicit cursor the changes done in the table will be

    effected--in the cursor

    --3.Keyset:If an explicit cursor is created as keyset cursor for each record in the cursor

    --will have unique Key used to identify each record in explicit cursor.--all the keys will be stored in a table and the table will be in msdb format.--4.FastForward:we can access records in the cursor only forward direction and All

    record

  • 7/31/2019 Venky SQL Server Metierial

    35/37

    --are readonly.--Navigation Types:--1.ForwardOnly:We can access records only in forward direction.--2.Scroll:It is used to get records in forward and backword direction.--Syntax for Creating cursors:--Declare cursor [static|dynamic|keyset|fastforward]

    [forwardonly|scroll]--for

    --Note:@@Fetch_Status-->is the predifined globalvariable to check wheather the cursor--contains records or not.

    --Example1:Create an explicit cursor that caliculate total sal from employe tabledeclare @teno intdeclare @tname varchar(max)declare @tsal intdeclare @tcom intdeclare cursor_to_cal_totalsal cursorfor

    select empno,ename,sal,comm from employeeopen cursor_to_cal_totalsalfetchnextfrom cursor_to_cal_totalsal into @teno,@tname,@tsal,@tcomwhile@@FETCH_STATUS=0beginupdate employee set total=@tsal+ISNULL(@tcom,0)where empno=@tenofetchnextfrom cursor_to_cal_totalsal into @teno,@tname,@tsal,@tcomend

    close cursor_to_cal_totalsaldeallocate cursor_to_cal_totalsal--after executing you will get the following output--(1 row(s) affected)--(1 row(s) affected)--(1 row(s) affected)--(1 row(s) affected)--Example2:take student table with sid m1,m2,m3,total,avg columns and

    -- insert sid,m1,m2,m3 values and

    --update total,Avg field by using cursors--creating tablecreatetable student_cursor(sidintprimarykey,m1 int,m2 int,m3 int,total int,avgint)--insert valuesinsertinto student_cursor(sid,m1,m2,m3)values(101,20,89,99)insertinto student_cursor(sid,m1,m2,m3)values(102,99,89,90)insertinto student_cursor(sid,m1,m2,m3)values(103,29,39,50)insertinto student_cursor(sid,m1,m2,m3)values(104,90,90,89)--using cursor updating total marks of a student

    declare @tsid int,@tm1 int,@tm2 int,@tm3 intdeclare cursor_to_update_totalmarks cursordynamicscrollforselectsid,m1,m2,m3 from student_cursorSopen cursor_to_update_totalmarks

  • 7/31/2019 Venky SQL Server Metierial

    36/37

    fetchnextfrom cursor_to_update_totalmarks into @tsid,@tm1,@tm2,@tm3while@@FETCH_STATUS=0beginupdate student_cursor set total=@tm1+@tm2+@tm3 wheresid=@tsidfetchnextfrom cursor_to_update_totalmarks into @tsid,@tm1,@tm2,@tm3endclose cursor_to_update_totalmarksdeallocate cursor_to_update_totalmarks--total will be updated in the student_cursor table--Updating avg column in student_cursor tabledeclare @tsid int,@total intdeclare cursor_to_update_avg cursorforselectsid,total from student_cursoropen cursor_to_update_avgfetchnextfrom cursor_to_update_avg into @tsid,@totalwhile@@FETCH_STATUS=0begin

    update student_cursor setavg=@total/3 wheresid=@tsidfetchnextfrom cursor_to_update_avg into @tsid,@totalendclose cursor_to_update_avgdeallocate cursor_to_update_avg--all avg column records will be updated--=====================================================

    - *************END******--**************************DBA- COMMANDS**********--For creating logins first we have to create schema.--Schema:Schema is used to group the table and other objects.--Syntax for creating The Schema--create schema createschema Mahe_Schema1--Creating Logins--Syntax:Create Login

    --with password=',default_database=maheshcreatelogin Mahe1

    withpassword='Mahesh@123',default_database=mahesh

    --after creating login we have to create users as followscreateuser ma1forlogin Mahe1withdefault_schema=Mahe_schema1

    --after creation of users we have to grant permissions to the users.--grant permissions for select,update,insert,alter,execute for you schema.--and grant permissions for creating tables and views also.

    grantselect,insert,update,delete,alter,executeonschema::Mahe_schema1 to ma1grantcreatetable,createviewto ma1--note:while working with logins you have to present in your database--on which you want to create login.

  • 7/31/2019 Venky SQL Server Metierial

    37/37

    --use --After successfull creation of all above three steps--go to Object explorer and right click on your database choose NewQuery--give LoginName=Mahe1--Password=Mahesh@123--now you can do your operations as per granted permissions.--****Delete Logins

    --drop login droplogin Mahe1

    --****Delete Users--drop user dropuser ma1

    --****Delete Schema--drop schema dropschema Mahe_Schema1

    --Note:While deleting schema check wheather schema has tables or not

    --if it containes tables you cannot delete.--Removing Permissions From the user--revoke select,insert,update,alter,delete on schema:: from revokeselect,insert,update,delete,alteronschema::Mahe_schema1 from ma1

    --revoke create table,create view from revokecreatetable,createviewfrom ma1

    --******************END*********************

    --If any errors are there please ignore me as per my knowledge--i wrote These SqlNotes.-----------------Than Q------------------------------