Você está na página 1de 53

--Using DDL commands

create table TEST (col1 int primary key identity(1,1) not null,
col2 varchar(50) not null,
col3 money not null,
BillDate datetime default GetDate())
--Add/Insert values into TEST table
insert into TEST(col2,col3,BillDate) values ('EXTE. HD' , 4500, '03-23-2015 15:5
0:00.345')
Select * from TEST
-- 2. insert to skip a nullable column
Insert into TEST(col2,col3) values ('USB 4.0', 5500)
Select * from TEST
-- 3. Insert to add a new row
Insert Into TEST(col2,col3,BillDate) values('SEAGATE', 7000, GETDATE())
SP_HELP TEST
Insert Into TEST(col2,col3,BillDate) values('DELL', 7000, GETDATE()), ('USB 3.0'
, 3500, GETDATE()), ('USB 5.0', 9500, GETDATE())
--update to modify record
update TEST set col2='Seagate 1 TB' where col1=3
-- delete a particular row or a record
Delete from TEST where col1=6
-- drop a table

Drop Table TEST


-- Truncate table
Truncate Table TEST
-- to rename
SP_RENAME 'TEST', 'TEST1'
-- alter command to add a new column in table TEST
ALTER table TEST ADD col4 varchar(20)
-- example
Create table Locations (Loc_Id int primary key identity(100,10) not null,
Locations varchar(50) not null)
create table Departments (DeptId int primary key identity(10,10) not null,
Dname varchar(50) not null,
Loc_Id int)
create table Employees (Empcode varchar(50) primary key not null,
EmpName varchar(50) not null,
Salary numeric(10,2) not null,
DeptId int)
-- adding records to tables
-- 1. locations
Insert into Locations (Locations) values ('Mumbai'), ('Chennai'), ('Hyderabad'),
('Delhi')
select * from Locations
--2. Departments
Insert into Departments(Dname, Loc_Id) values ('Admin', 110), ('HR', 120), ('Len
s', 110), ('SS', 120)
select * from Departments
select * from Locations
-- 3. Employees table
Insert into Employees values ('E-001', 'Harish k', 65000, 10), ('E-002', 'Tarun
A', 25000, 20), ('E-003', 'Kunal T', 25000, null), ('E-004', 'Rajesh V', 15000,
10), ('E-005', 'Gaurav S', 22000, 30)
select * from Employees
-- Simple querries to work with conditions
--1. querry to retrieve info of employee working for department 10

Select EmpName from Employees where DeptId =10


--2. querry to display employees whose name start with letter h
Select EmpName from Employees where EmpName like 'H%'
--3. querry to display whose name consist of letter h
Select EmpName from Employees where Empname like '%H%'
--4. select record from emp to display employees where name consist of second le
tter 'A'
Select EmpName from Employees where Empname like ('_A%')
delete from employees
Insert into Employees values ('E-001', 'Harish k', 65000, 10), ('E-002', 'Tarun
A', 25000, 20), ('E-003', 'Kunal T', 20000, null), ('E-004', 'Rajesh V', 15000,
10), ('E-005', 'Gaurav S', 22000, 30)
select * from Employees
-- aggregate functions like max, min, avg, count, sum
select sum(salary) from Employees
select sum(salary) as Total_Salary from Employees
update Employees set salary=20000 where Empcode like 'E-003'
select * from Employees
select count(*) Total_Emp from Employees where deptId = 10
select * from Employees
-- display emp details where deptId is not alloted
select * from Employees where DeptId is null
select count(distinct DeptId) as Dept_count from Employees
select count(*) as vaccant_dept from Employees where DeptId is null
select count(*) as vaccant_dept from Employees where DeptId is not null
-- group by clause
select DeptId, sum(salary) as 'Total Sal', avg(salary) as 'AVG Sal', min(salary)
as 'Min Sal' , max(salary) as 'Max Sal' from Employees group by DeptId
select EmpCode, sum(salary) as 'Total Sal', avg(salary) as 'AVG Sal', min(salary
) as 'Min Sal' , max(salary) as 'Max Sal' from Employees group by EmpCode

select DeptId, sum(salary) as 'Total Sal', avg(salary) as 'AVG Sal', min(salary)


as 'Min Sal' , max(salary) as 'Max Sal' from Employees group by DeptId order by
sum(salary) desc
select DeptId, count(*) as 'Total Employees' from Employees group by DeptId

-- grouping more than one column


select Empcode, DeptId, max(salary) as 'Max Sal', min(salary) as 'Min Sal' from
Employees group by EmpCode, DeptId order by Empcode desc
-- group by using having clause
select DeptId, max(salary) as 'Max Sal' from Employees group by DeptId having m
ax(salary)>23000
select DeptId, count(*) as 'Total Employees' from Employees group by deptId havi
ng count(*) >1

select DeptId, count(*) as 'Number of people working in same dept' from Employee
s group by deptId
Select DeptId, min(salary) as ' employee with lowest pay in department' from Emp
loyees group by DeptId order by min(salary) desc
-- displaying results of two or more columns into one
select EmpCode, salary as 'gross sal', salary * .10 as 'Allowances' , salary * 0
.15 as 'TA', salary * 0.07 as 'Deductions' , salary+(salary * 0.10) + (salary *
0.15) - (salary * 0.07) as 'Net Salary'from Employees
-- Date functions
select getDate() as 'current date'
--1. Day()
select day(getDate()) as 'Day of current Date'
--2. Month()
select month(getDate()) as 'month of current Date'
--3. year()
select year(getDate()) as 'year of current Date'
--4. dateadd(datepart,number,date)
select dateadd(d,5,getDate()) as ' days after 5 days from today'
select dateadd(m,-5,getdate()) as ' date before 5 months from today'
-- combining or concatenating two or more expressions into one column
select EmpCode+' Gets a salary of Rs.' + STR(salary,10,2) + ' and works for Dept
=' + STR(DeptId,3,2) from Employees

-- upper
select upper(EmpName) from Employees
select Ltrim('

eClerx') as ' Name without space'

select EmpName, len(EmpName) from Employees


--Datediff(datepart, start date, end date)
select col1,col2,datediff(d, billdate,getDate()) from TEST
select * from TEST
--datename (datepart, date)
select 'today is' + datename(mm,getDAte()) + str(datepart(dd,getDate())) + ',' +
str(datepart(yy,getDate()))
select 'you are' + str(datediff(yy,'03/08/1992', getDate())) + 'years old'
-- Unions
select EmpName, DeptId from Employees union
select dname, DeptId from Departments
-- Union All
select EmpName, DeptId from Employees union all
select dname, DeptId from Departments
--1.a inner joins
select e.EmpCode, e.EmpName, e.DeptId, d.Dname
from employees as e inner join Departments as d on
e.DeptId=d.DeptId
--1.b inner join to display records of emps whose name starts with T
Select E.EmpCode, E.EmpName, D.Dname
from Employees as E inner join Departments D on
E.DeptId=D.DeptId and E.EmpName like 'T%'
-- 1.c Joining two or more tables
select E.EmpName, D.Dname, L.Locations from Employees as E inner join
Departments d on E.DeptId = D.DeptId inner join
locations L on D.Loc_Id = L.Loc_Id
--2.a left outer join
select e.empname, e.deptid , d.dname from employees as e left outer join
departments d on e.deptid = d.DeptId
--2.b right outer join
select d.deptid, d.dname, l.locations from departments d right outer join
locations l on d.loc_id = l.loc_id
--2.c full outer join
select d.deptid, d.dname, l.locations from departments d full join

locations l on d.loc_id = l.loc_id


select * from Employees
-- adding one more column to employee table
Alter table Employees add mgr_id varchar(6)
update employees set mgr_id = 'E-001' where empcode = 'E-004'
update employees set deptid = 20, mgr_id = 'E-002' where empcode = 'E-003'
-- 2.4 self join querries
select e.empcode, e.empname as worker, e1.empname as manager from employees e j
oin
employees e1 on e.mgr_id = e1.empcode
-- adding foreign key instead of logical relationship
Alter table Employees add mgr_id varchar(6) foreign key refernces Employees(emp
code)
--cross join
select * from test
cross join locations
-- single row subquery
select empcode, empname, salary from employees where deptid = (select deptid fr
om employees where empcode = 'E-003' )
select * from employees
select empcode, empname, salary from employees where deptid = (select deptid f
rom employees where empcode = 'E-003' )
and empcode <>'E-003'
-- display list of employees whose salary is more than that of kunal E-003
select empcode, empname, salary from employees where salary > (select salary f
rom employees where empcode = 'E-003') and salary > (select salary from employee
s where empcode = 'E-004')
and empcode <> 'E-003'
-- display result of employees whose salary is least
select empcode, empname, salary from employees where salary = (select min(salary
) from employees)
-- Multiple row subquerry
--1.a IN operator
select empname, deptid, salary from employees where salary in (select min(salary
) from employees group by deptid )
--1.b ANY operator
select empname, deptid, salary from employees where salary < any (select salary
from employees where deptid = 10 )
--1.c ALL operator
select empname, deptid, salary from employees where salary < all (select salary
from employees where deptid = 10 )

-- nested subquerry
select empcode, empname, deptid from employees where deptid in (select deptid fr
om departments where loc_id in
(select loc_id from locations where locations = 'chennai'))
-- correlated subquerry
select dname from departments where deptid in (select deptid from employees wher
e departments.deptid = employees.deptid)
select * from employees
select * from Departments
select * from locations
-- list of employees who are working under manager E-002
update employees set mgr_id = 'E-002' where empcode = 'E-005'
select empcode, empname, deptid from employees where mgr_id ='E-002'
select empcode,empname from employees where deptid in (select deptid from employ
ees where departments.deptid = employees.deptid)
-- cube operator
-- 1. without cube
select empname, deptid, count(*) as total from employees group by empname, dept
id order by empname, deptid desc
-- this is not a valid summary hence we use cube operator
--2. with cube
select empname, deptid, count(*) as total from employees group by empname, depti
d with cube
-- rollup operator
select deptid, count(*) from employees group by deptid with rollup
-- assignment 1
select mgr_id, salary from employees where salary in (select min(salary) from em
ployees group by mgr_id) and salary > 16000 and mgr_id is not null
--assignmnet 2
select count(distinct mgr_id) from employees where mgr_id is not null
-- assignmnet 3.
select mgr_id, count(*) from employees where mgr_id is not null group by mgr_id
select * from employees
select * from Departments

select * from locations


-- common table expressions
select * from ( select e.empname, e.salary, d.dname from employees e inner join
departments d on e.deptid = d.deptid) T
where t.salary > 22000 order by t.empname
--1.a rewriting CTE
with T (empname, salary, dname) as (select E.empname, e.salary, d.dname from emp
loyees e inner join departments d on
e.deptid = d.deptid) select * from T where T.salary <22000 order by T.Empname
-- Except operator
select empname, deptid from employees except select dname, deptid from departme
nts
-- Intersect operator
select empname, deptid from employees intersect select dname, deptid from depar
tments
update employees set mgr_id ='E-001' where empcode='E-001'
update employees set mgr_id = null where empcode='E-005'
-- exists operator (returns multiple rows and works on joins also)
select empcode,salary, deptid from employees as e where exists (select * from de
partments D where d.deptid = e.deptid and
e.deptid = 10)
-- merge statement (here source is @order)
create table TORDERS(orderid int not null primary key, custid int not null, empi
d int not null, orderdate date not null)
insert TORDERS values (1,100,2,'20120612'),
(2,110,3,'20140612')
select * from TORDERS
declare @orders as Table (orderid int not null primary key, custid int not null,
empid int not null, orderdate date not null)
Insert into @orders(orderId,custid, empid, orderdate) values (2,1,3,'20120612'),
(3,2,2,'20120612'), (4,3,5,'20120612')
merge into TORDERS as TGT using @orders as SRC on src.orderid = tgt.orderid when
matched and (tgt.custid <> src.custid or tgt.empid <> src.empid or tgt.orderdate
<> src.orderdate) then update
set tgt.custid = src.custid, tgt.empid = src.empid, tgt.orderdate = src.orderdat
e
when not matched then insert values(src.orderid,src.custid,src.empid,src.orderda
te) when not matched by source then delete;
select * from torders
-- create views

create view VW1 as


select empcode,empname,salary from employees where deptid in(10,20)
-- To get result from the view
select * from VW1
--creating tables for using complex views
create table subjects(subid smallint primary key, subname varchar(20) not null)
insert into subjects values (1,'C'), (2,'C++'), (3,'JAVA'), (4,'vb.net'), (5,'As
p.Net')
select * from subjects
create table topics (subid smallint, topicname varchar(20))
insert into topics values (1,'unions'), (1,'structures'), (2,'classes'), (2,'obj
ects'), (3,'Applets'), (3,'beans'), (4,'winforms'), (4,'delegates'), (5,'ajax'),
(5,'MVC')
select * from topics
create view sub_topics as select s.subname as 'subject', t.topicname as 'topic'
from subjects as s inner join topics as T on s.subid = T.subid
select * from sub_topics
-- note :- if we change physical table then the view also gets updated as view i
s virtual table
-- update a table and display the view
update topics set topicname ='pointers' where topicname ='unions'
-- update a view and display the table
update sub_topics set topic = 'unions' where topic = 'pointers'
select * from topics
select * from sub_topics
--create view on another view
create view view2 as select * from vw1
select * from view2
-- using aggregate functions in views
alter table topics add chapters int
update topics set chapters = 2 where topicname = 'unions'
--using aggregate functions in views
create view totalchapters as select t.subid, sum(t.chapters) as 'total chapters'
from subjects as S inner join topics as t on s.subid =t.subid group by t.subid
select * from totalchapters

-- using view, details of those employees who works in chennai


create view emp_chennai as select e.empcode as 'code', e.empname as 'name' , e.s
alary as 'pay' , d.deptid as 'deptid', d.loc_id as 'locid'from employees as e
inner join departments as d on d.deptid = e.deptid inner join
locations l on d.loc_id = l.loc_id where l.locations like 'chennai'
select * from emp_chennai

--create view with encryption


use eClerxDb;
go
if object_ID('Test_view', 'V') is not null
drop view Test_view
go
create view Test_view
with encryption
as
select col1, col2, billdate from Test where billdate > convert(datetime, '201206
12', 101)
go
select * from test_view
sp_helptext test_view
-- synonyms
create synonym dbo.emps for employees
select * from Emps
--drop synonym
drop synonym dbo.emps
-- planning indexes
create table T1(col1 int , col2 varchar(10))
insert into T1 values(50,'A'), (10,'B'), (20,'C'), (70,'D')
select * from T1
-- note here data is not organized
--creating index
create clustered index clus_index on T1(col1)
insert into T1 values(21,'Z')
-- non clustered index
create table depts_name(dname varchar(10), ename varchar(10))

select * from depts_name


create nonclustered index nonclus_index on depts_name(Dname, Ename)
-- dropping non clustered index
drop index depts_name.nonclus_index
-- viewing indexes
sp_helpindex T1

-- simple stored procedure


/*
create procedure/proc <procedure_name>
[@<parametername> <data type>]
as <sql statements>
-- executing a stored procedure
execute/exec <procedurename> <@parametername> = value
*/
--1. first example
create proc P1 as select 'displaying records from emp table..'
select * from employees
select 'records displayed'
-- in case we want to execute several times
use eClerxDb
go
if
object_id('P1','P') is not null
drop proc P1
go
create proc P1 as select 'displaying records from emp table..'
select * from employees
select 'records displayed'
exec P1
-- creating T-SQL statements for temp.use
declare @N1 int
set @N1 = 100
print 'n1 is: '+STR(@N1,3)
print 'N1 is: '+convert(varchar(3),@N1)
select 'msg. is '+STR(@N1,3)
-- declare statement with tables
declare @ecode varchar(5)
select @ecode='E-001'
select * from employees where empcode=@ecode

-- stored procedures with parameters


use eClerxDb
go
if
object_id('Proc_ecode','P') is not null
drop proc Proc_ecode
go
create proc Proc_ecode
@ecode varchar(5)
as
select * from employees where empcode = @ecode
exec proc_ecode 'e-001'
-- stored procedure with multiple parameters
use eClerxDb
go
if
object_id('for_dep_loc','P') is not null
drop proc for_dep_loc
go
create proc for_dep_loc
@deptid int, @locid int
as
select e.empname, d.dname, l.locations from employees e inner join
departments d on e.deptid = d.deptid inner join locations l
on d.loc_id = l.Loc_id
where d.deptid = @deptid and l.loc_id = @locid
execute for_dep_loc 20,120
-- procedures with if else conditions
create proc obtain_dname
@deptid int
as
if(select count(*) from departments where deptId = @deptid) = 0
begin
print 'department with id ' + str(@deptid,3) +'does not exist'
end
else
select dname from departments where deptid =@deptid
exec obtain_dname 200
-- procedures with multiple parameters and check whether any parameter i
s missing
use eClerxDb
go
if
object_id('addnums','P') is not null
drop proc addnums
go
create proc addnums

@num1 smallint = null,


@num2 smallint = null
as
if @num1 is null or @num2 is null
begin
print'one of the inputs is missing'
return
end
else
begin
declare @ans smallint
set @ans = @num1 + @num2
return @ans
end
-- executing above SP
declare @ans int
exec @ans = addnums 10,20
select 'the sum is', @ans

--raiseerror statement
create proc dispdetails
@tname varchar (10)
as
if (select count(*) from sys.objects where type = 'U' and name = @tname) >0
begin
select * from sys.objects where type = 'U' and name = @Tname
end
else
begin
raiserror ('server error: %s - Table %s does not exists', 15,1,@@servern
ame, @tname)
end
exec dispdetails 'EMPloyees'

create table studentinfo(code varchar(5), name varchar(20), course varchar (10))


select * from studentinfo
-- explicit transactions
Begin Transaction
select 'before update'
select * from studentinfo where code = 'S-001'
update studentinfo set name='A_mod' where code='S-001'
select 'one row(s) updated'
commit transaction
select * from studentinfo where code = 'S-001'
select 'updated record is selected'
select @@Trancount

--1. Implicit transaction


set implicit_transactions on
select 'Before Insert'
select * from Studentinfo Insert into studentinfo values('S-006','F','XML')
select 'row inserted'
commit tran
select * from studentinfo
set implicit_transactions off
--2. Implicit transactions with data control
set implicit_transactions on
select 'deleting records from locations table'
delete from locations
select * from locations
select empcode, empname from employees where empcode = 'E-999'
if @@rowcount<>0
begin
commit transaction
select 'transanction committed. Records deleted from locations table'
end
else
begin
select 'ecode E-999 not found in Emp table'
Rollback transaction
select 'Transaction rolled back'
select * from locations
end
set implicit_transactions off
-- explicit transaction with @@trancount
begin transaction tran1
select 'transaction tran1 begins'
select 'trancount is ',@@trancount
select * from employees where
empcode = 'e-002'
begin transaction tran2
select 'transaction tran2 begins'
select 'trancount is ',@@trancount
select * from departments
commit transaction tran2
select 'Transaction tran2 committed'
select 'trancount is ', @@trancount
commit transaction tran1
select 'transaction tran1 committed'
select 'Trancount is', @@trancount
-- exception handling
begin try
declare @num int, @msg varchar(100)
print 'in try block..'
-- trying to divide a no. with zero
set @num = 5/0
print 'this will not execute'
end try

begin catch
print 'error occured is:'
set @msg = (select error_severity())
print @msg
end catch
--Try_convert and try_parse
SELECT
CASE WHEN try_convert(float, 'test') is null
then 'cast failed'
else 'cast succeeded'
end as result
go
set dateformat mdy;
select try_convert (datetime2, '12/31/2014') as result;
go
--try_parse
select try_parse ('1' as int)
select try_parse ('B' as int)
--try_catch
use eClerxDb
go
begin try
--table does not exists, object name resolution error
--error not caught
declare @num int
set @num = 5/0
end try
begin catch
select
error_number() as errornumber, error_severity() as errorseverity, error_state()
as errorstate, error_procedure() as errorprocedure, error_line() as errorline, e
rror_message() as errormessage
end catch
go
--xact_abort example
use eClerxDb
go
if object_id('tab2', 'U') is not null
drop table tab2
go
if object_id('tab1', 'U') is not null
drop table tab1
go
create table tab1
(A int not null primary key)
create table tab2
(A int not null references tab1(A))
go
insert into tab1 values(1), (3), (4), (6)

go
set xact_abort off;
go
begin transaction
insert into tab2 values
insert into tab2 values
insert into tab2 values
commit transaction
go
set xact_abort on;
begin transaction
insert into tab2 values
insert into tab2 values
insert into tab2 values
commit transaction
go

(1)
(2)
(3)

(4)
(5)
(6)

-- select shows only keys 1 and 3 added...key 2 inserted failed and will roll ba
ck but since xact_abort was off and rest of transaction will succeed
-- key insert error with xact_abort on will cause all of the second trans to rol
lback
select * from tab2
go
--user defined functions
--1. function with single parameter
create function fnGetEmpname (@fullname varchar(50))
returns varchar(30)
as
begin
return (select @fullname)
end
--1.a calling a function
select dbo.fnGetEmpname(empname)
as name, salary from employees
--2. function with two parameters
create function fnGetEmpname2 (@empcode varchar(50), @fullname varchar(30))
returns varchar(45)
as
begin
return (select @empcode + ':' + @fullname)
end
--2.a calling function
select dbo.fnGetEmpname2(empcode,empname)
as name, salary from employees
use eClerxDb
go
if object_id('fnGetEmpname2', 'FN') is not null
drop function fnGetEmpname2
go

create function fnGetEmpname2 (@empcode varchar(50), @fullname varchar(30))


returns varchar(45)
as
begin
return (select @empcode + ':' + @fullname)
end
select dbo.fnGetEmpname2(empcode,empname)
as name, salary from employees
-- create UDF with parameter and return instance of a table
use eClerxDb
go
if object_id ('fnGetEmpdetails','if') is not null
drop function fnGetEmpdetails
go
create function fnGetEmpdetails (@locid int)
returns table
-- we are looking f
or table and not a single value
as
return (select e.empname, d.dname, l.locations from employees e join
departments as d on e.deptid = d.deptid join
locations as l on d.loc_id = l.loc_id where l.loc_id = @locid)
go
-- invoke the above function
select * from dbo.fnGetempdetails(120)
-- while construct
set nocount on
declare @count as int=1;
while @count <=10
begin
print cast(@count as nvarchar);
set @count+=1
-- set @count=@count+1
end
-- waitfor
select * from employees
waitfor delay '00:00:15'
-- Triggers
if object_id('location_trigger','tr') is not null
drop trigger location_trigger
go
create trigger location_trigger
on locations
for insert
as
select 'trigger executed'
select 'Inserted Table'
select * from inserted
select 'deleted table'

select * from deleted


select 'original table'
select * from locations
insert into locations (locations)
values ('bangluru')

--After trigger
if object_id('Empdetails_trigger','tr') is not null
drop trigger Empdetails_trigger
go
create trigger Empdetails_trigger
on employees
after delete, insert, update
as
begin
if @@rowcount = 0
return;
set nocount on;
select count (*) as insertedcount from inserted
select count (*) as deletedcount from deleted
end
insert into employees
values ('E-007', 'Rahul K', '22000', '30', 'E-001')
delete from employees where empcode ='E-007'
--insert trigger for departments table
if object_id('check_dname','tr') is not null
drop trigger check_dname
go
create trigger check_dname
on departments
for insert
as
if (select count(*) from inserted where dname like '%[0-9]%')>0
begin
select 'department name cannot contain numbers'
rollback transaction
select 'inserted failed'
end
else
begin
select 'record inserted'
end
-- to execute above trigger
insert into departments(dname, loc_id) values ('fin10', 130)
--update trigger
create table deposits (depname varchar (20), depdate datetime, amt float)

insert into deposits values ('aaa', getdate(), 30000), ('BBB', dateadd(dd, -5, g
etdate()), 41000)
create trigger amt_check on deposits
for update
as
if(select amt from inserted )<25000
begin
print 'new amount cannot be less than 25000. update failed'
rollback transaction
-- if we do not menti
on roll back, message will get printed although it will update
end
else
begin
print 'update successful'
end
update deposits set amt=35000
where depname ='AAA'

-- Instead of trigger
-- The code in an INSTEaD OF trigger is executed in place of original DML statem
ent
create TABLE books(bookcode int primary key not null identity (100,1), bookname
varchar (50) not null, authors varchar (50) not null)
Insert into books(bookname, authors) values ('QUERING SQL 2012','aaa'), ('Java
EE', 'BBB'), ('C#.net', 'CCC'), ('XML', 'DDD')
select * from books
use eClerxDb
go
if object_id('books_trigger','tr') is not null
drop trigger books_trigger
go
create trigger books_trigger
on books
with encryption
instead of insert
as
if (select count(*) from books where bookname = (select bookname from inserted))
>0
begin
select 'duplicate book name found updating the book.'
update books set authors = (select authors from inserted) where booknam
e = (select bookname from inserted)
end
else
begin
insert into books (bookname, authors)
select bookname, authors from inserted
select 'record inserted'
end

insert into books (bookname, authors) values ('C#.net', 'WWW')


insert into books (bookname, authors) values ('VB.net', 'Patrick N.')
sp_helptrigger books
sp_helptext books_trigger
-- DELETE trigger
create table master (code int, ename varchar (20), address varchar (20))
insert into master values (100, 'david', 'NY'), (101, 'GEOFF', 'UK'), (102, 'JEA
N', 'LA'), (103, 'MARTIN', 'SYD'), (104, 'ALLAN', 'AUS'), (105, 'TIM', 'NJ')
select * from master
select * from deposits
create table newdeposits (code int, depdate datetime, amt money)
insert into newdeposits values (101, getdate(), 3000), (102, dateadd(dd, 5, getd
ate()), 4000), (102,getdate(), 2000), (101, dateadd(dd, 10, getdate()), 7000), (
105, getdate(), 1500), (105, dateadd(dd, 20, getdate()), 6000)
select * from newdeposits
--1.a trigger for enforcing data integrity
use eClerxDb
go
if object_id('deltrigger','tr') is not null
drop trigger deltrigger
go
create trigger deltrigger
on master
for delete
as
if (select count (*) from newdeposits where code = (select code from deleted)) >
0
begin
print 'cannot delete. There are child records'
rollback transaction
end
else
begin
print 'records deleted'
end
drop trigger deltrigger
delete from master where code = 105
delete from master where code = 104
select * from master

-- 1.b cascading delete

use eClerxDb
go
if object_id('casdeltrigger','tr') is not null
drop trigger casdeltrigger
go
create trigger casdeltrigger
on master
for delete
as
if (select count(*) from newdeposits where code = (select code from deleted)) >0
begin
delete from newdeposits where code = (select code from deleted)
print 'cascade delete successful. child records deleted'
end
else
begin
print 'no child record found. record deleted from master table'
end
delete from master where code = 101
select * from newdeposits
-- create a trigger on the 'employees' table which allows the user to insert a r
ecord only if the salary of the new record is more than 4000.
use eClerxDb
go
if object_id('employee_4000','tr') is not null
drop trigger employee_4000
go
create trigger employee_4000
on employees
for insert
as
if (select count(*) from inserted where salary > 4000)>0
begin
select 'found employee with salary more than 4000'
select 'inserted successful'
end
else
begin
select 'insert failed'
rollback transaction
end
insert into employees values ('E-009' , 'rounak V', 10000, 10, 'E-001')
select * from employees
-- create a trigger for departments table which allows user to insert only 2 rec
ords at a time
use eClerxDb

go
if object_id('dept','tr') is not null
drop trigger dept
go
create trigger dept
on departments
for insert
as
if (select count(*) from inserted) >2
begin
select 'records cannot be added. only 2 allowed'
rollback transaction
select 'inserted failed'
end
else
begin
select 'insert successful'
end
insert into departments( dname, loc_id) values ( 'xxx', 120), ( 'YYY', 130), ('z
zz', 110)
insert into departments( dname, loc_id) values ( 'xxx', 120), ( 'YYY', 130)
select * from departments
delete from departments where deptid = 130

-- cursor
/* syntax for declaring a cursor.
declare <cursor_name>
cursor
for
<select statement>

-- to open the declared cursor


open <cursor_name>
-- to fetch single row
fetch <cursor_name>
-- close an open cursor and releases the current result set
close <cursor_name>
-- to remove the cursor
deallocate <cursor_name>
*/
-- 1. simple cursor
declare cur1 cursor
for
select * from departments
open cur1

select ' cursor opened'


fetch next from cur1
while (@@fetch_status = 0)
begin
fetch Next from cur1
end
close cur1
select 'cursor closed'
deallocate cur1
select 'cursor deallocated'
-- 2. scrollable cursor
declare cur2 cursor
scroll
for
select * from departments
open cur2
select 'result of fetch absolute 2'
fetch absolute 2 from cur2
select 'result of fetch absolute 3'
fetch absolute 3 from cur2
select 'result of fetch relative 1'
fetch relative 1 from cur2
select 'result of fetch relative -2'
fetch relative -2 from cur2
close cur2
deallocate cur2
-- 3. scrollabe cursor (fetch next, first, last and prior actions)
declare cur3 cursor
scroll
for
select * from departments
open cur3
select 'result of fetch first'
fetch first from cur3
select 'result of fetch last'
fetch last from cur3
select 'result of fetch prior'
fetch prior from cur3
select 'result of fetch next'
fetch next from cur3
close cur3
deallocate cur3
-- 4. static cursor
set implicit_transactions on

declare cur4 cursor


scroll
static
for
select * from departments
open cur4
select 'modifying dname for deptid 10 in departments table'
update departments
set dname ='***' where deptid = 10
select 'the table is'
select * from departments
select 'first row from cursor'
fetch first from cur4
rollback transaction
close cur4
deallocate cur4
set implicit_transactions off
sp_helptrigger departments
drop trigger dept
--5. dynamic cursor
set implicit_transactions on
declare cur5 cursor
scroll
dynamic
for
select * from departments
open cur5
select 'modifying dname column for all rows in departments table'
update departments set dname = '***'
select 'the table is '
select * from departments
select 'first row from cursor'
fetch first from cur5
select 'inserting a record in department table '
insert into departments(dname, loc_id) values ('IT', 110)
select 'the table is'
select * from departments
select 'last row from cursor'
fetch last from cur5
rollback transaction
close cur5
deallocate cur5
set implicit_transactions off
select * from departments

-- 6.cursor with forward only ... this moves in forward direction only...prior w
ont work here
set nocount on
declare @code varchar (5)
declare @name varchar (20)
declare forward_cur_emp cursor forward_only
for
select empcode, empname from employees order by empname
open forward_cur_emp
if @@cursor_rows >0
begin
fetch next from forward_cur_emp into @code, @name
while @@fetch_status = 0
begin
if @name = 'Rajesh V'
update employees set salary = 24000 where current of forward_cur_emp
fetch next from forward_cur_emp
into @code, @name
end
end
close forward_cur_emp
deallocate forward_cur_emp
set nocount off
go
select * from employees
sp_helptrigger employees
-- local temporary tables
create table #T1
( col1 int not null)
insert into #T1 values(10), (20)
select * from #T1
select name from tempdb.sys.objects where name like '#%'
drop table #t1
-- temporary tables with transactions
create table #T1
( col1 int not null)
begin transaction
insert into #t1 values (10), (20)
rollback transaction
select col1 from #T1
drop table #T1

-- XML with SQL


-- XML datatype
create table EmpAsXML (Id int primary key not null identity(1,1), EmployeeData x
ml)
insert into EmpAsXML (EmployeeData) values ('<employee Id = "1"> <firstname>Dani
el</firstname> <lastname>Davilio</lastname> </employee>')
select * from EmpAsXML

-- XML type
--1. XML raw
select * from employees
for XML raw
--2. XML auto
select * from Employees for XML auto
--3. XML auto, elements
select * from employees for XML auto, elements
--4. XML auto, elements, root
select * from employees for XML auto, elements, root ('emps')
-- 5. Xpath query
Select deptid, dname as 'department1' from departments where deptid in (10,30) o
rder by deptid for xml path ('departments'), root ('depts')
-- Xquery methods
declare @xml XML
set @xml = '<suppliers> <user userno="1" email="sams@gmail.com">
<item no="1" name="usb 2.0"></item>
<item no="2" name="usb 3.0"></item> </user>
<user userno="2" email="john@gmail.com">
<item no="1" name="usb 4.0"></item>
</user>
<user userno="3" email="smith@gmail.com">
<item no="1" name="HDD 1TB"></item>
</user>
<user userno="35" email="jams@gmail.com">
<item no="2" name="HDD 2 TB"></item>
</user>
<user userno="4" email="tango@gmail.com">
<item no="3" name="HDD 4 TB"></item>
</user>
</suppliers>'

--1.xml.exist()
-- this method returns a boolean value depending on the conditions as :
select @xml.exist('/suppliers/user[@email="sams@gmail.com"]') as result1
select @xml.exist('/suppliers/user[@email="dams@gmail.com"]') as result2

-- 2. Xml.querry()
--this method takes an xquery statement and returns an instance of XML datatype
select @xml.query('/suppliers/user') as users
-- display unique values for representing item nos. from @xml
select @xml.query('distinct-values(data(/suppliers/user/item/@no))') as items
--3. xml.value()
--this method takes an xquery statement after type casting
select @xml.value('/suppliers[1]/user[1]/@email', 'varchar(20)') as resultemail1
select @xml.value('/suppliers[1]/user[2]/@email', 'varchar(20)') as resultemail2
--4. xml.nodes()
-- this method takes an xquery statement and returns a single value after type c
asting
select x.value('@userno','int') as userno, x.value('@email','varchar(20)') as em
ail
from @xml.nodes('/suppliers/user') tempxml(x)
select x.value('../@userno','int') as userno,
x.value('../@email','varchar(50)') as email,
x.value('@name','varchar(20)') as itemname
from @xml.nodes('/suppliers/user/item') tempxml(x)

--30/06/2015
-- INDEXES
select * from EmpAsXML

-- Sample data
create table XML_Table
(ID int identity (1,1) not null, customername varchar(50) null, customerphone va
rchar (50) null, customeraddress xml null,
constraint [ID_PK_XML] primary key([ID] asc))
-- insert data into xml_table
insert into xml_table(customername, customerphone, customeraddress)
values ('sam Smith','022-8845',
'<customer>
<address1>Marine Drive</address1>

<city>Mumbai</city>
<state>Mah</state>
<zip>400001</zip>
</customer>')
insert into xml_table(customername, customerphone, customeraddress)
values('Jean D','011-884578',
'<customer>
<address1>Connaught</address1>
<city>Delhi</city>
<state>ND</state>
<zip>909011</zip>
</customer>')
select * from xml_table
-- XML INDEXES
create primary XML index [PK_XML_DATA_customeradd]
on xml_table(customeraddress)
-- disable index
alter index [PK_XML_DATA_customeradd] on xml_table disable
-- droping index
drop index [PK_XML_DATA_customeradd] on xml_table

sp_help xml_table
-- OPEN XML
--1. open XML
declare @idoc int, @doc varchar(1000)
set @doc ='<root>
<customer customerid ="vinet" contactname ="Paul Henry">
<order customerid ="vinet" employeeid ="5" orderdate="2014-07-06T15:20:37">
<orderdetail orderid="1024" productid="10" quantity="12"/>
<orderdetail orderid="1024" productid="22" quantity="10"/>
</order>
</customer>
<customer customerid ="gloss" contactname ="carlos gonzel">
<order customerid ="gloss" employeeid ="3" orderdate="2015-06-06T19:25:37">
<orderdetail orderid="1028" productid="70" quantity="3"/>
</order>
</customer>
</root>'
-- 2.create an internal representation of xml doc
exec sp_xml_preparedocument @idoc output, @doc

-- now this i

doc works as output


--2.a execute a select document that uses open xml rowset provider
select * from openxml (@idoc,'/root/customer',1) with (customerid varchar(10), c
ontactname varchar(20))
select * from openxml (@idoc,'/root/customer/order',1) with (customerid varchar(
10), orderdate varchar(30))

-- insert records from xml doc to sql table


declare @xmlDtype varchar (200)
declare @OPT int
set @xmlDtype = '
<books>
<bookcode>1</bookcode>
<authors>smith</authors>
<bookname>SQL for beginners</bookname>
</books>'
-- 1.a creating xml document
exec sp_xml_preparedocument @OPT output, @xmlDtype
-- 1.b select statement for using openxml rowset
insert into books
select * from openxml(@OPT,'/books', 2) with (bookname varchar(50), authors varc
har (50))
go
select * from books
-- XML bulk load
--1. loading a single table
create table Student (Id int, Name varchar (50))
select * from student
drop table student
-- loading multiple tables (with foreign key relationship)
drop table student
create table student (Id int not null constraint PK_STUDID primary key (Id), Nam
e varchar (50))
create table studentGrade (StudentId int references Student(Id), Grade char(10))
select * from student
select * from studentGrade

-- partition functions
select deptid, row_number() over (partition by deptid order by empcode) as 'rown
um',
empname from employees
select * from employees
select * from departments
select distinct deptid, sum(salary) over (partition by deptid order by deptid)
as 'total salary' from employees
-- group by versus partition by clause

create table mytable (policyid int, trandate datetime, amount money)


insert mytable values (1,'01/02/12',12.00), (1,'03/01/2014', 15.00), (1,'05/04/2
014',10.00), (2,'01/02/2013',12.00), (2,'01/03/2013',11.00)
select * from mytable
--1. group by clause
with totals (policyid,totalamount,maxtrandate) as
(select policyid, sum(amount), max(trandate) from mytable group by policyid)
select * from mytable m join totals T
on
T.policyid = m.policyid and T.maxtrandate = m.trandate
--2. partition by example
with totals (policyid,totalamount,maxtrandate, rownum) as
(select policyid,sum(amount) over (partition by policyid), max(trandate) over (p
artition by policyid),
row_number() over (partition by policyid order by trandate desc) from mytable)
select * from totals where rownum=1

-- Pivot and Unpivot


-- create temporary tables
create table #coursesales (course varchar(20), [year] int, earnings money)
insert into #coursesales values ('.net',2014,10000), ('Java',2014,20000), ('.Net
',2014,5000), ('.Net',2013,48000), ('Java', 2013,30000)
select * from #coursesales

drop table #coursesales


--1. Pivot
select * from #coursesales
pivot(sum(earnings) for course IN([.Net], Java)) as PVTTable
--2.Pivot for making year as column headings
select * from #coursesales
pivot(sum(earnings) for year in ([2013], [2014])) as PVTTable
--3. create temporary sales table and insert 1000 sample records with random pas
t 0-1000 days as the sales date
create table #sales (SalesId int identity (1,1), SalesDate Datetime)
insert into #sales (SalesDate) values (dateadd(dd,-convert(int, (1000+1)*rand())
, getdate()))
go 1000
select * from #sales
--4. write pivot function with sales table to show data in quaretrs
select year, QPivot.[1] as Q1, QPivot.[2] as Q2, QPivot.[3] as Q3, QPivot.[4] as
Q4 from (select year(salesDate) [year] ,
datepart(quarter, SalesDate) [quarter], count(1) [sales count]
from #sales group by year (SalesDate), datepart(quarter, SalesDate)) as quarterl
ydata
pivot (sum([sales count]) for quarter in ([1],[2],[3],[4])) as QPivot
--5. pivot function to get monthly data
select * from (select year(salesDate)[year], Datename(month, salesdate) [Month],
count(1) [Sales Count]
from #sales group by year(SalesDate), datename(month,SalesDate)) as MonthlySales
Date
pivot (sum([Sales Count]) for month in ([january], [February], [[March])) as MN
amePivot

--6. Pivot and unpivot function


select * into #coursesalesPivotResult from #coursesales pivot(sum(earnings) for
course in ([.net], Java)) as PvtTable
select * from #coursesalesPivotResult
--6.a unpivot table data
select course, year, Earnings from #coursesalesPivotResult unpivot(earnings for
course in ([.net], java)) as UnPivotTable

-- Assignment 1. write a cursor which will target deptid 10 and 30 and fetch var
ious actions for showing first, last, next and previous records
declare cur3 cursor
scroll
for
select * from employees where deptid in (10,30) order by deptid
open cur3
select 'result of fetch first'
fetch first from cur3
select 'result of fetch last'
fetch last from cur3
select 'result of fetch prior'
fetch prior from cur3
select 'result of fetch next'
fetch next from cur3
close cur3
deallocate cur3

select * from employees


-- Assignment 2. create a table #candidatetable with columns
--1) candidateId int PK
--2) candidateName varchar(50)
--3) candidateAddress xml
--which will include data(elements) like address, city and phone no. select the
values for displaying city and phone nos.

create table #CandidateTable1 (CandidateId int primary key not null, CandidateNa
me varchar(50), CandidateAddress xml)
insert into #CandidateTable1 values (1,'john', '<candidate><address>airoli</add
ress> <city>Mumbai</city><phoneno>123456</phoneno></candidate>'),
(2,'robert','<address>rabale</address> <city>Mumbai</city><phoneno>987654</phone
no>')
select * from #CandidateTable1
declare @idoc int, @doc varchar(1000)
set @doc ='<root>
<candidate address ="Airoli" city ="mumbai" phoneno="123456">
</candidate>
<candidate address ="rabale" city ="mumbai" phoneno="987654">
</candidate>
</root>'
-- create an internal representation of xml doc

exec sp_xml_preparedocument @idoc output, @doc


doc works as output

-- now this i

-- execute a select document that uses open xml rowset provider


select * from openxml (@idoc,'/root/candidate',1) with (city varchar(10), phonen
o int )

-----------------alternative method--------------------------create table #CandidateTable (CandidateId int primary key not null, CandidateNam
e varchar(50), CandidateAddress xml)
insert into #CandidateTable values (1,'john', '<address>airoli</address> <city>
Mumbai</city><phoneno>123456</phoneno>'),
(2,'robert','<address>rabale</address> <city>Mumbai</city><phoneno>987654</phone
no>')
select CandidateAddress.value ('city[1]','varchar(50)') as city ,
candidateAddress.value ('phoneno[1]','int') as phoneno from #candidatetable

--1. filtering data with top to filter rows by number


select top(3) deptid, empname, salary from employees order by deptid desc
select * from employees
--2. filtering data with top with percent of rows to filter rather than by numbe
rs
select top(1) percent deptid, empname, salary from employees order by deptid des
c
select * from #sales
select top(1) percent salesid, salesdate from #sales order by salesid desc
--3. select null expression
select top(3) deptid, mgr_id, empname from employees order by (select null)
select * from employees
--4. offset -fetch filtering
select salesid, salesdate from #sales order by salesdate desc, salesid desc
offset 50 rows fetch next 25 rows only

select deptid, empname, salary from employees order by deptid

offset 2 rows fetch next 2 rows only


select * from employees
--5. rank ()
select deptid, salary, row_number() over (order by deptid) as rownum, rank() ove
r (order by deptid) as [rank] from employees
--6. dense_rank ()
select deptid, salary, row_number() over (order by deptid) as rownum, rank() ove
r (order by deptid) as [rank],dense_rank() over (order by deptid) as [denserank]
from employees
--7. first_value and last_value
select salesid, salesdate, first_value(salesid) over (partition by salesid order
by salesdate rows between unbounded preceding and current row) as first_value,
last_value(salesid) over (partition by salesid order by salesdate rows between c
urrent row and unbounded following ) as last_value
from #sales

-- 8.windows aggregate functions


select deptid, salary, avg(salary) over (partition by deptid
order by deptid rows between 2 preceding and current row) as 'movingavg' from em
ployees
--9. percentile function

-- DateTime enhanced datatypes


--1. Date and Datetime
declare @date Date='12-21-05';
declare @datetime DateTime =@date;
select @datetime as '@DateTime', @date as '@Date'
--2. Date function datefromparts(year,month,day)
declare @year int = 2014,
@month int = 1,
@day int = 9;
select datefromparts (@year, @month, @day) as [retrieved data from datefromparts
]
--3. timefromparts
declare @hour int = 11,
@min int = 59,
@sec int = 59;
select timefromparts (@hour,@min,@sec,500,3) as [timefromparts data]

--4. datetime from parts


declare @year int = 2015, @month int = 06, @day int = 30, @hour int = 11, @min i
nt = 40, @sec int = 59, @milisecond int = 10;
select datetimefromparts (@year,@month, @day,@hour, @min, @sec, @milisecond) as
[datetimefromparts]
-- example with datetimefromparts returning values from a date
declare @dt datetime
set @dt = getdate()
select datetimefromparts (year(@dt),month(@dt),day(@dt),datepart(hh,@dt),datepar
t(mi,@dt), datepart(ss,@dt),100)

--5. smalldatetimefromparts
declare @year int = 2015, @month int = 06, @day int = 30, @hour int = 11, @min i
nt = 40
select smalldatetimefromparts (@year,@month,@day,@hour,@min) as [smalldatetimefr
omparts]
--6. datetimeoffset
declare @datetimeoffset datetimeoffset(4) ='12-10-25 12:32:10 + 01:00'
declare @date date = @datetimeoffset
select @datetimeoffset as '@datetimeoffset', @date as '@date'
--7. datetime2fromparts
declare @year int = 2015, @month int = 06, @day int = 30, @hour int = 11, @min i
nt = 40, @sec int = 59
select datetime2fromparts (@year, @month, @day, @hour, @min, @sec, 500, 3) as [r
etrieved data from datetime2fromparts]
select sysdatetime() -- datetime2 datatype
select getdate ()
-- datetime datatype
select eomonth(sysdatetime()) as end_of_currentmonth
-- format function
--1. formatting the date (display datename, month name and day in year)
declare @date datetime ='07/01/2015'
select format(@date, 'D','en-US') as formatteddate
--2. display long date and time function
declare @date datetime =getdate()
select format(@date, 'yyyy/MM/dd hh:mm:ss tt','en-US') as formatteddate

-- 3.convert date into 12 hour system


declare @date datetime = convert(datetime, '2015/01/01 14:20:30')
select format (@date, 'yyyy/MM/dd hh:mm:ss tt','en-US') as formatteddate
--4.display the time part
declare @date DATETIME = getdate()
select format (@date, 'h\:m\:ss\.ffffff', 'en-US') as formatteddate
--5.chinese culture
declare @date datetime = getdate()
select format (@date, 'MMMM dddd d', 'zh-TW') as formatted

--6 formatting of numbers


--display the no. with currency using locale
declare @money MONEY ='125000'
select format (@money,'C') as MyMoney
--7. display currency with culture
declare @money MONEY ='125000'
select format (@money,'C', 'hi-IN') as MyMoney
--8. to change the language setting and display the currency
set language british
declare @money MONEY='125000'
select format (@money,'C') as MyMoney
--9. display the no. in percentage
declare @num bigint=5
select format(@num,'00.000%') as MyMoney
--10. other formats
select format (345.91, '###0.000')
select format(15,'0.00%')
select format (3333.4,'##,##0.00')
--11. other formats for datetime
declare @date datetime = getdate()
select format (@date,'h:m:s ')
select format (@date,'hh:mh:ss tt')
select format (@date,'dddd,MMM d yyyy')
--12. time xone

select format (getdate(),'M/d/yyyy H:mm tt zzz','hi-IN')


-- Assignment 1. design a table #emp with columns
--empid bigint pk identity (1000,1), Empname varchar(30) not null, salary money
not null, DOB datetime not null, DOJ datetime default systemdate
--insert some records into above table
create table #emp (empid bigint primary key identity (1000,1),
empname varchar(30) not null,
salary money not null,
DOB datetime not null,
DOJ datetime default getdate())
insert into #emp (empname, salary, DOB, DOJ)
values
('john', 10000, '1970/06/03', '2011/30/06'),
('Sam',15000, '1992/07/03',getdate() ),
('Marry',20000, '1988/04/02', '2012/30/12'),
('Santa',12000, '1991/08/03', getdate())
update #emp set DOJ='2010/05/03' where empid = 1000
update #emp set DOJ='2011/06/03' where empid = 1002
select * from #emp
drop table #emp
--2. write a querry to display experience of employees with the company from the
ir DOJ
--4. dateadd(datepart,number,date)
select empname + ' has work experience of ' + STR(datediff(yy, DOJ,getDate()))
+ ' years' from #emp
--3. write a querry to display employees who have joined in the last day of prev
ious month
insert into #emp (empname, salary, DOB)
values
('jay', 11000, '2015/30/06')
select empname from #emp where DOJ = eomonth(dateadd(m,-1,getdate()))
--4. write a querry to display records of those employees whose age is more than
30
select * from #emp where datediff (yy, DOB, getdate()) >30

-- Throw statement
-- perform a check
declare @unitprice money, @discount numeric (4,3)
select @unitprice = 5
select @discount = .6

if @unitprice <10 and @discount > 0.5


begin
throw 50000, 'Discount must be <= .5 when unit price is less than 10', 1
end
else
begin
print 'valid unitprice and discount offered'
end

-- Pagination in sql server 2012


-- 1.creating a dummy table
create table #DummyTable (DummyId int not null, Name varchar (50) null, Details
varchar (50) null,
constraint [PK_DummyTable] primary key clustered ([DummyId] ASC ))
--2.inserting 5000 rows into #dummy
declare @count int =1
declare @max int=5000
while (@count <=@max)
begin
insert into #DummyTable
select @count, 'name ' + cast(@count as varchar(50)), 'record ' + cast(@count as
varchar (50))
set @count = @count +1
end
select * from #DummyTable
--3. pagination controls
--3.a procedure to set default start and end values
create proc pagination_1
(@start int = 1, @end int = 500)
as
begin
select DummyId, name, details from #DummyTable where DummyId between @start and
@end order by DummyId
end
exec Pagination_1 1,10
exec Pagination_1 100,130
--3.b Pagination can be used with top statement and get the records
create proc pagination_2
(@start int =1) as
begin
select top 10 DummyId, Name, Details from #DummyTable where DummyId >=@start ord
er by DummyId

end
exec pagination_2 100
--3.c pagination with offset filter
create proc pagination_3
(@start int =1)
as
begin
select DummyId, Name, Details from #DummyTable order by DummyId
offset @start rows fetch next 10 rows only
end
exec pagination_3 1000
--3.d
create proc pagination_4
(@start int = 1, @end int=1 )
as
if (@end <100)
begin
select DummyId, name, details from #DummyTable where DummyId between @start and
@end order by DummyId
end
else
begin
throw 50000, 'end point should be less than 100',1
end
exec pagination_4 1, 50
drop proc pagination_4
-- execute sp_executesql
exec sp_executesql
N' select * from #DummyTable where DummyId = @id',
N' @id int',
@Id = 500
-- parametrize query with SQL string
declare @v int
declare @s nvarchar (500)
declare @p nvarchar(500)
--1.a build the sql string
set @s = N' select deptid, empcode, salary from employees where deptid = @deptid
'
set @p = N' @deptid int'
--1.b setting the value for parameter integer
set @v = 10

execute sp_executesql @s, @p, @deptid = @v

--spartial datatypes
/*
describes physical location and shape of geometry objects. These objects can be
point, locations such as roads, lakes, countries etc.
Two spatial datatypes supported in sql are geometry and geography.
circular string - is an object of type geometry which is defined by 3 points i.e
. startpoint, endpoint, anchor point (lies in between end and start point)
*/
-- 1. example of circular string
declare @gm geometry
set @gm = geometry :: STGeomFromText ('CIRCULARSTRING(2 0, 1 1, 0 0)', 0)
select @gm
--2. another example
declare @g geometry = 'CIRCULARSTRING(1 1, 2 0, -1 1)'
select @g
--3. closed circular string
declare @g geometry
set @g = geometry::Parse('CIRCULARSTRING(2 1, 1 2, 0 1, 1 0, 2 1)')
select @g
--4. compound curve
/*
--4. compound curve - a single continued path that connects a set of points. E
ach pair of points can be linear or curved.
-- the parameters are
1)linestring (determined by circular string),
2)circular string,
each linestring and circular string segment must begin at the point where previo
us segment ended.
*/
declare @g geometry = 'compoundcurve (circularstring (1 0, 0 1, -1 0), (-1 0, 1.
25 0))'
select @g
--curved polygon with 5 points
declare @g geometry ='curvepolygon((4 2,8 2, 8 6, 4 6, 4 2))'
select @g
--curved polygon with gepgraphy
declare @g geography
set @g = 'curvepolygon(circularstring(-122.358 47.653, -122.348 47.649, -122.348

47.658, -122.358 47.658, -122.358 47.653))'


select @g
--bufferwithcurves
/*
it pads a line effectively convert it into polygon
*/
declare @streets geometry = 'geometrycollection(linestring(100 -100, 20 -180, 18
0 -180),
linestring (300 -300, 300 -150, 50 -50))'
select @streets.BufferWithCurves(10)
-- STNumPoints
declare @C geometry = 'circularstring(0 4,4 0,8 4,4 8,0 4)'
--1.a to show a curved shape along with points
select shape = @C, ShapeWKT =@C.ToString(), ShapeLen = DATALENGTH (@C), Point =
@C.STNumPoints ()
-- COnvert to lines
select shape = @C.STCurveToLine(), ShapeWKT =@C.STCurveToLine().ToString(), Shap
eLen = DATALENGTH (@C.STCurveToLine()), Point = @C.STCurveToLine().STNumPoints (
)

--03/07/2015--- Execute statement with resultsets


/*
syntax
exec Stored_procedure_name
with result sets
(( column 1 Datatype
..
..
column N datatype))
*/
create table salesorder (OrderId int not null, CustomerCode varchar (20), OrderD
ate Date , TotalAmount money, TaxAmount money )
insert into SalesOrder values
(1000,'A001','2014-10-10',2500,25),
(1001,'A001','2014-10-13',2650,26.50),
(1002,'A003','2014-10-14',3300,33),
(1003,'A006','2014-10-15',4300,43),
(1004,'A002','2014-10-18',5300,53),
(1005,'A005','2014-10-20',2800,28)
drop table salesorder
select * from SalesOrder

--create procedure
create proc GetSalesOrder
As
Begin
select OrderId, CustomerCode, OrderDate, TotalAmount from SalesOrder
end
--result of proc without "with resultsets"
exec GetSalesOrder
-- return column namesorderId, CustomerCode, OrderDate and TotalAmount to OrderI
d, CustCode, OrderDate and Amount
exec GetSalesOrder
with Result Sets
((
OrderId int,
CustCode varchar(20),
OrderDate varchar(10),
Amount float))
-- the default option for execute statement is "with result sets undefined"
exec GetSalesOrder
with result sets undefined
--Execute statement "with resultsets none" option
-- this will not return a result
create proc noresult
As
Begin
print 'This is a test'
end
exec noresult
with result sets none
-- with existing procedure GetSalesOrder
exec GetSalesOrder
with result sets none
-- multiple resultsets defining two results
create procedure GetEmpDeptTwoResultSet
as
Begin
select EmpCode, EmpName, Salary, Deptid from employees
select Deptid, Dname from departments
End
execute GetEmpDeptTwoResultSet
with result sets

(
(
ECode varchar(5),
Name varchar (30),
Salary money,
deptid int),
(
deptid int,
department varchar (20))
)
-- Parse conversion function
/*
PARSE(String_value AS data_type [USING CULTURE])
nal
*/

culture is optio

--1.Parse String to INT


Select PARSE ('999' AS INT) AS 'String to INT'
--2. Parse string to Numeric
Select PARSE ('999.99' AS NUMERIC(8,2)) AS 'String to NUMERIC'
--3. PArse string to datetime
Select PARSE ('01-01-2015' AS DATETIME) AS 'String to DATETIME'
--4. Parse string value in INDIA date format to DATETIME
Select PARSE ('18-06-2015' AS DATETIME using 'en-IN') AS 'String to INT'
--5. Parse string value in US currency format to Money
Select PARSE ('$2550' AS MONEY using 'en-US') AS 'String to MONEY'
--6. Failed Parse expression with invaid string
Select PARSE ('2012/02/31' AS DATETIME)
--7. Parse function to translate date not supported in US formate.
Select PARSE ('18-06-2015' AS DATETIME using 'en-US')
-- Difference between parse and converion
Select PARSE ('Saturday,04 July 2015' AS DATETIME) AS 'Parsed Date'
Select PARSE ('Sat,04 July 2015' AS DATETIME) AS 'Parsed Date'
-- convert function fails to perform
SELECT CONVERT (DATETIME, 'Saturday,04 July 2015') as 'Converted Date'
-- sequence objects is similar to identity; however it is not associated with on

e table
--create a sequence object viz; invoice number that will start from seed -1000 a
nd increment by 5 every time whenever sequence object is accessed
use eClerxDb
go
create Sequence InvoiceNumber
as INT
start with 1000
increment by 5
--let's use the sequence with next value for clause
select next value for InvoiceNumber
-- sequence generated now will use it when inserting rows into a table
use eClerxDb
go
if OBJECT_ID ('NewInvoice','U') is not null
BEGIN
DROP TABLE NewInvoice
END
BEGIN
CREATE TABLE NewInvoice (InvoiceId INT null, name VARCHAR(1000) null)
END
--Insert values
INSERT INTO NewInvoice VALUES (
next value for InvoiceNumber, 'PATRICK N')
INSERT INTO NewInvoice VALUES (
next value for InvoiceNumber, 'McGraw')
select * from NewInvoice
drop table NewInvoice
drop sequence InvoiceNumber
-- The current value of sequence
select current_value from sys.sequences where name ='InvoiceNumber'

-- use sequence with different table


create sequence IND_POPULATION
AS BIGINT
START WITH 12345678
Increment by 1
-- create table for each city in India
create TABLE MUM_Population (
IndPopulationId bigint, PopulationId bigint identity (1,1),

FirstName varchar (50),


LastName varchar (50))
create TABLE DEL_Population (
IndPopulationId bigint, PopulationId bigint identity (1,1),
FirstName varchar (50),
LastName varchar (50))
create TABLE KOL_Population (
IndPopulationId bigint, PopulationId bigint identity (1,1),
FirstName varchar (50),
LastName varchar (50))
--Insert rows into above tables for new borns in each city
INSERT into MUM_Population (IndPopulationId, FirstName, LastName)
VALUES (NEXT VALUE FOR IND_POPULATION, 'Tarun', 'Kapoor')
INSERT into DEL_Population (IndPopulationId, FirstName, LastName)
VALUES (NEXT VALUE FOR IND_POPULATION, 'Karan', 'Ahuja')
INSERT into MUM_Population (IndPopulationId, FirstName, LastName)
VALUES (NEXT VALUE FOR IND_POPULATION, 'Kelly', 'Jones')
INSERT into MUM_Population (IndPopulationId, FirstName, LastName)
VALUES (NEXT VALUE FOR IND_POPULATION, 'Robert', 'Hill')
INSERT into DEL_Population (IndPopulationId, FirstName, LastName)
VALUES (NEXT VALUE FOR IND_POPULATION, 'Len', 'Marks')
INSERT into KOL_Population (IndPopulationId, FirstName, LastName)
VALUES (NEXT VALUE FOR IND_POPULATION, 'Abhilash', 'Chatterjee')
INSERT into KOL_Population (IndPopulationId, FirstName, LastName)
VALUES (NEXT VALUE FOR IND_POPULATION, 'Tarkesh', 'Ghosh')
select * from MUM_Population
select * from DEL_Population
-- Recycling the sequence
create Sequence RECYCLE_Sequence
As TINYINT
Start with 250
increment by 1
minvalue 0
maxvalue 255
cycle
-- generate sequence numbers and see the recycling
select
select
select
select
select
select
select

next
next
next
next
next
next
next

value
value
value
value
value
value
value

for
for
for
for
for
for
for

RECYCLE_Sequence
RECYCLE_Sequence
RECYCLE_Sequence
RECYCLE_Sequence
RECYCLE_Sequence
RECYCLE_Sequence
RECYCLE_Sequence

select next value for RECYCLE_Sequence


-- display status of sequence objects
select Name, start_value, minimum_value, maximum_value, current_value
from sys.sequences
where name = 'RECYCLE_Sequence'
--Get a range of sequence number for an object
--Procedure available is sp_sequence_get_range
--try to get a range of 10 sequence nos. from sequence object RECYCLE_Sequence
Declare @range_first_value SQL_Variant
Declare @startrange SQL_Variant
Declare @rangesize bigint
set @rangesize = 10
exec sp_sequence_get_range
@sequence_name = N'RECYCLE_Sequence',
@range_size = @rangesize,
@range_first_value = @startrange OUTPUT
select @startrange AS StartingNumber
-- view the status of sequence generated
select Name, start_value, minimum_value, maximum_value, current_value
from sys.sequences
where name = 'RECYCLE_Sequence'
-- performance improvement could be achieved by using an option CACHE. When it
is used, a range of values are cached in the memory.
create Sequence NewSequence
As INT
Start with 2
Increment by 3
Maxvalue 500
cycle
cache 10
select
select
select
select

next
next
next
next

value
value
value
value

for
for
for
for

NewSequence
NewSequence
NewSequence
NewSequence

select current_value from sys.Sequences where name = 'NewSequence'


-- to modify existing cache value
ALTER Sequence NewSequence cache 100
select * from sys.Sequences
/*

Create a sequence CountBy1 which starts with 10, adds by 10 and recycles from 1
Then add a table MyOrders with columns
OrderId int not nullable PK,
Custid int not nullable with a check constarint that custid >0
Empid int not null with a check constarint that empid >0
orderdate date not null
1. Insert rows for the table above with orderid mapped to sequence
2. Rows inserted should be shown in stored procedure where new column sets shoul
d be created with new column names as order_id, customer_id, EmployeeId and Ordd
ate
*/
create Sequence CountBY1
As int
Start with 10
increment by 10
minvalue 1
maxvalue 50
cycle
select
select
select
select
select
select
select

next
next
next
next
next
next
next

value
value
value
value
value
value
value

for
for
for
for
for
for
for

CountBY1
CountBY1
CountBY1
CountBY1
CountBY1
CountBY1
CountBY1

CREATE TABLE MyOrders


(OrderId int primary key not null,
CustId int not null CHECK (CustId >0),
EmpId int not null CHECK (EmpId >0),
OrderDate Date not null)
Insert into MyOrders
values (NEXT VALUE FOR CountBY1, 1, 50, '2015-06-30')
Insert into MyOrders
values (NEXT VALUE FOR CountBY1, 2, 51, '2015-05-30')
Insert into MyOrders
values (NEXT VALUE FOR CountBY1, 3, 52, '2015-04-30')
Insert into MyOrders
values (NEXT VALUE FOR CountBY1, 4, 53, '2015-06-25')
Insert into MyOrders
values (NEXT VALUE FOR CountBY1, 5, 54, '2015-05-24')

create proc MyOrders1


As
Begin

select OrderId, CustId, EmpId, OrderDate from MyOrders


end
exec MyOrders1
with Result Sets
((
Ord_Id int,
CustomerId int,
EmployeeId int,
OrdDate date))
select * from MyOrders

-- Contained database
use Master
GO
Sp_configure 'SHOW ADVANCED options',1
GO
RECONFIGURE WITH OVERRIDE
GO
SP_CONFIGURE 'Contained database authentication',1
GO
RECONFIGURE WITH OVERRIDE
GO
SP_CONFIGURE 'Show advanced option',0
GO
RECONFIGURE WITH OVERRIDE
GO

-- Execute Login through user


Use DemoContainedDB
select Suser_Sname()
Execute AS login = 'sa'
Select SUSER_SNAME()
Select * from sys.DM_OS_WINDOWS_INFO
revert
select SUSER_SNAME()
--user defined server role in SQL server 2012
-- create sql server login
use [master]
go
create login [L1DBAs]
with password = N'L1$upp0rtDBAs',
default_database = [master],
check_expiration = off,

check_policy = off
go

--viewing permissions assigned to the newly created server role


/* since permissions are not set for backing up database, the script fails to pe
rform an action
*/
-- Backup database eclerxDb
backup database eclerxDb
to disk = 'C:\eclerxDb.bak'
go
--script for shutdowning the database, but since permissions are not given hence
script fails
-- shutdown command shutdown the instance of sql
shutdown
go
-- results of following script which works since we have permissions to view ser
ver state permissions
select * from sys.dm_exec_requests where session_id >50

-- Column Store Index


use eclerxDb
go
create table MysalesOrderDetails (
SalesOrderId int not null, SalesOrderDetailId int not null, CarrierTrackingNumbe
r nvarchar(25) not null, OrderQty smallint not null,
ProductId int not null, SpecialOfferId int not null, UnitPrice money not null, M
odifiedDate datetime not null )

-- create a clustered index


create clustered index [CL_MySalesOrderDetails] on MySalesOrderDetails (SalesOrd
erDetailId)
-- performance test using STATISTICS IO ON
set statistics IO ON
go
--select table with regular index
SELECT ProductId, sum(UnitPrice) as SumUnitPrice,

avg(UnitPrice) as AvgUnitPrice,
Sum (OrderQty) as SumOrderQty
from MySalesOrderDetails group by ProductId order by ProductId
-- create column store index
create nonclustered columnstore index [CIX_MySalesOrderDetails_ColumnStore] on M
ySalesOrderDetails (UnitPrice, OrderQty, ProductId)
--view/select the table with columnstore index
select ProductId, SUM(UnitPrice) as SumUnitPrice, Avg(UnitPrice) as AvgUnitPrice
, SUM (OrderQty) as SumOrderQty, Avg (OrderQty) as AvgOrderQty
from MySalesOrderDetails group by ProductId Order by ProductId

-- configure a service broker for sending and receiving messages


-- creating a database for service broker
create database ServiceBrokerDb
go
use ServiceBrokerDb
go
--activate service broker for the above created database
Alter database ServiceBrokerDb
set ENABLE_BROKER
go
-- create a message type
create message type SBMsg
validation = None
go
--create a contract
create contract SBContract (SBMsg sent by Initiator )
go
-- create send queue
create queue SBSendQueue
go
--create receive queue
create Queue SBReceiveQueue
go
-- create a send service on send queue
create service SBSendService
on queue SBSendQueue (SBContract)
go
--create a receive service on receive queue
create service SBReceiveService
on queue SBReceiveQueue (SBContract)
go

--begin dialog using service contract


declare @SBDialog uniqueidentifier
declare @Message Nvarchar(100)
begin dialog conversation @SBDialog
from Service SBSendService
to service 'SBReceiveService'
on
contract SBContract
with encryption = off
--send message on dialog
set @Message = N'My first message';
send on conversation @SBDialog
message type SBMsg (@Message)
set @Message = N'My second message';
send on conversation @SBDialog
message type SBMsg (@Message)
set @Message = N'My third message';
send on conversation @SBDialog
message type SBMsg (@Message)

-- view message from received queue


select Convert (nvarchar(100), message_body)
as Message
from SBReceiveQueue
-- File Table and filestream
exec sp_configure filestream_access_level, 2
reconfigure

-- create a table for filestreaming


create database FileTableDB1
on
primary (name = FileTableDB1, FileName = N'C:\filetable\FileTableDB1.mdf'),
filegroup FTFG contains filestream (name = FileTableFS, filename = N'C:\filetabl
e\FS')
log on
(Name = FileTableDB1Log, Filename = N'C:\filetable\FileTableDB1Log.ldf')
with
filestream (non_transacted_access = full, directory_name =N'filetable')
go

select db_name(database_id), non_transacted_access,


non_transacted_access_desc from sys.database_filestream_options
--create filetable table
use FileTableDB1
go
create table FileTableTb as FileTable with (FileTable_Directory = 'FIleTable_DIr
')
go
-- select data from filetable
select * from FileTableTb
select * from filetabletb
-- Analytic functions lead and lag
/*
lead() is used to access the subsequent rows(or columns from the subsequent row)
without using a self join
lead () takes 3 parameters
1) scalar expression or ccolumn name whose value from subsequent row is to be re
turned
2) we can specify offset to access next immediate row and any row after the curr
ent row
3) we can specify the default value to be returned
*/
-- create table for lead and lag
use eclerxDb
create table customerPlan (CustomerCode varchar(10), PlanCode varchar (10), Star
tDate date)
insert into customerPlan
values ('C00001','P00001','20140901'),
('C00001','P00002','20141001'),
('C00001','P00003','20141010'),
('C00001','P00004','20141025'),
('C00002','P00001','20141001'),
('C00002','P00002','20141101')
select * from CustomerPlan
drop table customerplan
-- lead function
select *, dateadd(day, -1, lead(StartDate, 1, '01-Jan-2100')over (partition by C
ustomerCode order by StartDate asc))
as enddate
from customerplan
--lag() function allows to access previous rows from the same result set without
self join
-- second offset parameter can be specify the physical offset that comes before

the current row


select customercode, plancode as currentplancode, lag(plancode, 1, 'NA') over (p
artition by customercode order by startdate asc) as lastplan
from customerplan
-- Normalization
/*
--process of removing redundencies of incoming data. Different tables will be cr
eated to associate the data using primary foreign key relationships.
2 approaches:1) top down approach
2) Bottom up approach (normally used)
Denormalization
*/

Você também pode gostar