SQL Server Notes
SQL Server Notes
MONEY 11. NCHAR 12. NTEXT 13. NUMERIC 14. NVARCHAR 15. REAL 16. SMALLDATETIME 17. SMALLINT 18. SMALLMONEY 19. SQL_VARIANT 20. TEXT 21. TIMESTAMP 22. TINYINT 23. UNIQUEIDENTIFIER 24. VARBINARY 25. VARCHAR
*We
can execute more than one command on the prompt using terminator (;) in Oracle/MySQL/SQL-server and in SQL-server without terminator too.
In SQL Server insert into student values(1,'amit'); In MYSQL insert into student values(1,'amit'); In Oracle insert into student (name,roll) values('amit',2); In SQL Server insert into student (name,roll) values('amit',2); In MYSQL insert into student (name,roll) values('amit',2);
# Selected columns and all rows:In Oracle select name from student; In SQL Server select name from student; In MYSQL select name from student; # Selected rows and all columns:In Oracle select * from student where roll=1; In SQL Server select * from student where roll=1; In MYSQL select * from student where roll=1; # Selected columns and selected rows:In Oracle
select name from student where roll=1; In SQL Server select name from student where roll=1; In MYSQL select name from student where roll=1; # Elimination of duplication from the Select statement:In Oracle select distinct name from student; select distinct roll,name from student; select distinct * from student; In SQL Server select distinct name from student; select distinct roll,name from student; select distinct * from student; In MYSQL select distinct name from student; select distinct roll,name from student; select distinct * from student;
Note:-If distinct is applied with two or more column then union of this column should be unique in the output of Oracle/SQLServer/Mysql # Sorting data in a table:Asending Order In Oracle select * from student order by roll; select * from student order by roll,name; In SQL Server select * from student order by roll; select * from student order by roll,name; In MYSQL select * from student order by roll; select * from student order by roll,name; Desending Order In Oracle select * from student order by roll desc; select * from student order by roll,name desc;
In SQL Server select * from student order by roll desc; select * from student order by roll,name desc; select * from student order by name,roll desc; In MYSQL select * from student order by roll desc; select * from student order by roll,name desc; select * from student order by name,roll desc; Note:- In descending the records are descended by the right hand side of the specified column;But in ascending the records are sorted by left hand side of the specified columns; ############################################ In SQL Server select roll,name,position= case roll when 1 then 'FIRST' when 2 then 'SECOND' when 3 then 'THIRD' else 'FAIL'
create table student5 as select roll from student; create table student9 as select (roll) from student create table student2 (roll,name) as select roll,name from student (not working) create table student4(roll_no) as select roll from student; (not working) NOTE(1) It will create a table as student where data is also transffered in another command (2) After select command the column name should not be in parenthesis if it contaion more than one column
insert into student select roll from student1; (Not Working, not enough values(because of no of columns)) In my sql insert into student select * from student1; insert into student select roll,name from student1; insert into student select roll from student1; (Not Working, not enough values(because of no of columns)) DELETE In oracle delete student1; delete from student1; delete student where roll=2; delete from student where roll=2; in sql server delete student1; delete from student1; delete student where roll=2; delete from student where roll=2; in mysql delete student1;(not working) delete from student1; delete student where roll=2;(not working) delete from student where roll=2;
In sql server alter table student add (address varchar(50));(not working due to parenthsessis) alter table student add address varchar(50); Note: - the column name must not be as add in alter command; as well as in create table command; In my sql alter table student add (address varchar(50)); alter table student add address varchar(50); Note: - the column name must not be as add in alter command; as well as in create table command;
Modify:In oracle
alter table student modify address varchar2(75);
alter table student modify (name varchar2(60)); note:-we can increase the size of a column but we cant decease the size if column is not empty. Note:-we cant modiy the datatype of column if column is not empty We cannot change the name of table and column, we canot drop a column with modify
In sql server
alter table employee alter column emp_name varchar(50) In mysql alter table student modify address varchar2(75) note:-we can not use parenthesis after modify clause note:-we can increase the size of a column but we can decease the size of column until the maximum data size entered in a column. Note:-we cant modiy the datatype of column if column is not empty We cannot change the name of table and column using ALTER with modify command,
Drop
In oracle
alter table student drop column sss; note:- column keyword should be used; note:-this sql will drop column in both conditions if data exists or not. note:- you cannot drop all columns in a table with alter table drop command. note:- you cannot drop more than one column in a single statement in a table with alter table drop command.
In sql server
ALTER TABLE student DROP COLUMN address
In mysql
alter table student drop column sss; alter table student drop sss; note:-this sql will drop column in both conditions if data exists or not. note:- you cannot drop all columns in a table with alter table drop command.
note:- you cannot drop more than one column in a single statement in a table with alter table drop command.
Renaming a Table
In oracle rename student to s1; note:-table keyword must not be used; in sql server sp_rename 'abc','student1' note :-abc is old object name and student1 as new object name; sp_rename renames all object in the data base; In my sql rename table student to s1; note:-table keyword should be used;
In Sql server drop table student1; In Mysql drop table student1; FINDING OUT THE ALL TBALE ACCESSED BY A USER IN ORALE select * from tab; NOTE:-TAB IS RESRVE KETYWORD IN SQL SERVER Sp_help IN MYSQL Show tables;
sp_help student; in mysql desc student; describe student; OPERATORS:Arithmetic operator Addition Multiplication Subtraction Division Exponentiation Enclosed Operation
Modulo
SQLServer + * / () %
Assignment operator Assignment Bitwise operator BITWISE AND BITWISE OR Bitwise EXCLUSIVE OR
<< >> ~ ~
Comparison operator Less Than Greater Than Equal To Not Equal Not Less Than Not Greater Than Greater Than Equal To Less than Equal to ANY BETWEEN EXISTS IN LIKE SOME IS NULL IS NOT NULL
>= <=
Y Y Y Y Y Y
NOT BETWEEN NOT IN NOT LIKE REGEXP NOT REGEXP Logical operator AND OR XOR NOT
Oracle Y Y Y
Oracle + -
Truncate table
In oracle
truncate table student; in sql server truncate table student; in mysql truncate table student; note:1.Truncate operation drop and recreate the table which is much faster than deleting rows one by one. 2.truncate operation are not transaction safe and generate error if and active transaction or an active table lock exitx. 3.the number of deleted rows are not returned; Drop table (Destroying table) In oracle drop table student; in sql server drop table student9; in mysql drop table student9 Grouping data from tables in SQl
In oracle select roll from student group by roll,name; select sum(roll) from student group by name; select sum(roll),name from student group by name; select sum(roll),name from student group by name having name='amit'; select sum(roll),name from student group by name having sum(roll)>5
In sql server
select sum(roll) from student group by name select sum(roll),name from student group by name select sum(roll),name from student group by name having name='amit'
In mysql
select sum(roll) from student group by name1; select sum(roll),name1 from student group by name1;
having clause:-
In oracle
select sum(roll),name from student group by name having name='amit';
In sql_server
select sum(roll),name from student group by name having name='amit'
In mysql
select sum(roll),name1 from student group by name1 having name1='amit';
1. Column listed in the select statement has to be listed in group by clause 2. Column listed in group by clause need not be listed in select statement 3. Only group function can be used in the having clause. 4. The group function listed in having clause needs not listed in select statement. Note:-function that act on the set of values is called group function ex-sum, count etc. ********************************* Group by rollup Group by cube
ALIAS
In oracle In sql_server
SELECT roll as 'ROLL',name as 'STUDENT' FROM STUD
SELECT roll 'ROLL',name 'STUDENT' FROM STUD SELECT roll "ROLL",name "STUDENT" FROM STUD
In mysql
CONSTRAINT
BUSINES RULES which are inforced on data being stored in a table are called constraints. Types of data constraints:1.input out put constraints. 2.business rules constraints.
primary key
a. b. c. d. e. f. g. h. i. j.
It defines column as maindatory column that is the column cant be left blank. as the not NULL attribute is active. Primary is a column ar a set of column that uniquely identify a column. its main purpose is to record uniqueness. Primary key will also not allow null value. Primary key helps to relating tables with one another. Primary key cant be long or long row data type, Only one primary key is allowed per table. Unique index is created automatically if there is a primary key. One table can combined up to 16 column in a composite column A single column primary key is called simple key. A multi column primary key is called a composite primary key.
create table testing_pk (roll int not null primary key, n int identity, name1 varchar(20))
Syntax:Primary key (<column name>,<column name>) create table testing_pk (id int not null , r_no int identity, name1 varchar(20), primary key (id,r_no)) Note:-table level uniqness depends on the combination of column values. correct/wrong insertion are:insert into class values('r3','c3','amit'); ->correct insert into class values('r3','c3','amit'); ->wrong insert into class values('r4','c3','amit'); insert into class values('r3','c4','amit'); insert into class values('r5','c5','amit'); ->correct ->correct ->correct
Unique key
(1) Unique key will not allow duplicate value. (2)Unique index created automatically. (3) A table can have more than one unique key which is not possible in primary key. (4)unique key can combined upto 16 columns in a composite unique key. (6)The unique key constraint permits one entry of NULL in to the column.
Foreign key
Foreign Key is a column(s) that references a column(s) of a table and it can be the same table also. Parent that is being reference has to be unique or primary key. Child may have duplicates and NULLs but unless it is specified. Foreign Key Constraints can be specified on child but not on parent. Parent record can be deleted provided no child records exists. Master table can not be updated if child record exists. Records can not be inserted into a detail table if corresponding record in a master table do not exists. Records of the master table can not be deleted if corresponding records in the detail table actually exists . We can not drop a table if it is referenced by other child table.
Syntax:<Column name> <data type> (<size>) references tablename(column name) create table room ( r_id int foreign key references student, room_id varchar(30) )
create table room ( r_id int foreign key references student(roll), room_id varchar(30) )
create table room ( r_id int references student(roll), room_id varchar(30))
On delete no action
It is by default setting.In this setting ca not delete a record in master table if it exists in detail table.
On update no action
It is by default setting.In this setting ca not update a record in master table if it exists in detail table.
On delete cascade
MASTER:
create table continent( c_id varchar(10) primary key, c_name varchar(20))
DETAILED: create table country( con_id varchar(10) references continent(c_id) on delete cascade, cry_id varchar(10), con_name varchar(20)) NOTE:- When a row of Master table is deleted all rows of detail table referencing the row of master table deleted.
On update cascade
create table continent( c_id varchar(10) primary key, c_name varchar(20)) create table country( con_id varchar(10) references continent(c_id) on update cascade, cry_id varchar(10), con_name varchar(20)) NOTE:- When a row of Master table is updated all rows of detail table referencing the row of master table updated.
Alter Constraints
alter table class1
add constraint abc primary key(roll),check(roll<10) alter table class1 add primary key(roll) alter table class1 drop constraint abc
insert into branch_master values('patna',1) insert into branch_master values('delhi',2) insert into branch_master values('gaya',3) select * from branch_master name patna delhi gaya branch_no 1 2 3
where b.branch_no=e.branch_no or select e.emp_no,e.fname,b.name,e.dept,e.desig from emp_master e inner join branch_master b on b.branch_no=e.branch_no emp_no 1 2 3 4 fname amit balram verma sanjay name patna patna delhi gaya dept computer computer computer bts desig programmer programmer programmer guide
Outer join
Table emp_master
create table emp_master( emp_no int not null, fname varchar(25), dept varchar(25), desig varchar(25), branch_no int) insert into emp_master values(1,'amit','computer','programmer',1) insert into emp_master values(2,'balram','computer','programmer',1) insert into emp_master values(3,'verma','computer','programmer',2) insert into emp_master values(4,'verma','computer','programmer',3) insert into emp_master values(5,'krisna','bialogy','teacher',4) insert into emp_master values(6,'babloo','math','reader',5) select * from emp_master Emp_no 1 2 3 4 fname amit balram verma verma dept computer computer computer computer design programmer programmer programmer programmer branch_no 1 1 2 3
5 6
krisna babloo
bialogy math
teacher reader
4 5
Table branch_master
create table branch_master( name varchar(10), branch_no int not null) insert into branch_master values('patna',1) insert into branch_master values('delhi',2) insert into branch_master values('gaya',3) insert into branch_master values('england',10) select * from branch_master name patna delhi gaya england branch_no 1 2 3 10
Left join
select e.fname,e.dept,b.name from branch_master b,emp_master e where e.branch_no*=b.branch_no Note:-In this syntax we will see all rows of emp_master because in where clouse emp_master field is left side. or select e.fname,e.dept,b.name from emp_master e left outer join branch_master b on
b.branch_no=e.branch_no Note:-In this syntax we will see all rows of emp_master because with from clouse emp_master field is left side. fname amit balram verma sanjay krishna babloo dept computer computer computer computer biology math name patna patna delhi gaya NULL NULL
Right join
select e.fname,e.dept,b.name from branch_master b,emp_master e where e.branch_no=*b.branch_no Note:-In this syntax we will see all rows of branch_master because in where clouse branch_master field is right side. or select e.fname,e.dept,b.name from emp_master e right outer join branch_master b on e.branch_no=b.branch_no Note:-In this syntax we will see all rows of emp_master because with from clouse emp_master field is left side. fname dept name patna patna delhi gaya england
amit computer balram computer verma computer sanjay computer NULL NULL
Full join
select e.fname,e.dept,b.name from branch_master b,emp_master e where e.branch_no*=b.branch_no union select e.fname,e.dept,b.name from branch_master b,emp_master e where e.branch_no=*b.branch_no / OR select e.fname,e.dept,b.name from emp_master e full join branch_master b on e.branch_no=b.branch_no fname amit babloo balram krishna sanjay verma NULL dept name
computer patna math NULL computer patna biology NULL computer gaya computer delhi NULL england
Cross join
Table--student;
create table student( roll int not null, name varchar(20))
roll name
1 amit
verma
Table-class
create table class( roll int, c_name varchar(20)) insert into class values(1,'nursery') insert into class values(2,'ukg')
roll
1 1 2 2
name
amit amit verma verma
c_name
nursery ukg nursery ukg 1 2 1 2
roll
SELF JOIN
TABLEEMPLOYEE
create table employee( employee_no varchar(25) not null, employee_name varchar(25), manager_no varchar(25)) insert into employee values('E01','BASU','E02') insert into employee values('E02','RUKMANI','E05') insert into employee values('E03','KAROL','E04') insert into employee(EMPLOYEE_NO,EMPLOYEE_NAME) values('E04','BAROS') insert into employee(EMPLOYEE_NO,EMPLOYEE_NAME) values('E05','IVAN') employee_no employee_name E01 E02 E03 E04 E05 BASU RUKMANI KAROL BAROS IVAN manager_no E02 E05 E04 NULL NULL
SELECT E.EMPLOYEE_NAME,M.EMPLOYEE_NAME "MANAGER" FROM EMPLOYEE E, EMPLOYEE M WHERE E.MANAGER_NO=M.EMPLOYEE_NO; EMPLOYEE_NAME MANAGER -------------------- -------------------BASU RUKMANI RUKMANI IVAN KAROL BAROS
NOTE:-In some situation it is necessary to join a table ot it self as though two separate tables this is referred as self join;
UNION
Retrive the name of all clients and sales man in the city of Mumbai from the tables client_master and sales_master.
TABLE CLIENT_MASTER
create table client_master( c_id varchar(20), c_name varchar(20), c_city varchar(20))
c_id c_name
C01 C02 C03 C04 C05 C06 ASRAF VISHAL AJAY ROHIT NALINI PREM
c_city
TABLE:-SALESMAN_MASTER create table salesman_master( s_id varchar(20), s_name varchar(20), s_city varchar(20))
S_NAME S_CITY MANISH MUMBAI KIRAN DELHI NITESH MUMBAI MAHESH KOLKATA
S_ID
C01 C03 C05 S01 S03
S_NAME
ASRAF AJAY NALINI MANISH NITESH
NOTE:1. 2. 3. NO OF COLUMN AND TYPES OF BOTH THE TABLES SHOULD BE SAME; UNION CANT BE USED IN SUB QUERIES; AGREEGATE FUNCTION CANT BE USED WITH UNION CLAUSE
INTERSECTION
Retrive the sales man name in Mumbai whose affords have resulted into at list one sale transaction.
create table salesman_master( s_id varchar(20), s_name varchar(20), s_city varchar(20)) TABLE-> salesman_master select * from salesman_master S_ID S01 S02 S03 S04 S_NAME MANISH KIRAN NITESH MAHESH S_CITY MUMBAI DELHI MUMBAI KOLKATA
create table sale_order( o_no varchar(10), o_date datetime, s_id varchar(20)) insert into sale_order values('o01','12-apr-97','s01') insert into sale_order values('o02','25-apr-97','s03')
insert into sale_order values('o03','03-oct-97','s01') insert into sale_order values('o04','18-june-97','s04') insert into sale_order values('o05','20-aug-97','s02') insert into sale_order values('o06','12-jan-97','s02') TABLE_>sale_order; O_NO o01 o02 o03 o04 o05 o06 O_DATE 1997-04-1200:00:00.000 1997-04-2500:00:00.000 1997-10-0300:00:00.000 1997-06-1800:00:00.000 1997-08-2000:00:00.000 1997-01-1200:00:00.000 S_ID s01 s03 s01 s04 s02 s02
SELECT DISTINCT s_id,s_name FROM salesman_master WHERE EXISTS (select sm.s_id,sm.s_name from salesman_master sm ,sale_order so where lower(sm.s_id)=lower(so.s_id)) or SELECT DISTINCT sm.s_id,sm.s_name FROM salesman_master sm INNER JOIN sale_order so ON sm.s_id = so.s_id order by sm.s_id S_id SO1 SO2 SO3 SO4 s_name MANISH KIRAN NITESH MAHESH
MINUS
Retrive all the product No of non moving item from the product_master table.
create table sales_order( o_no varchar(20), p_no varchar(20)) insert into sales_order values('o01','p01')
insert into sales_order values('o01','p04') insert into sales_order values('o01','p06') insert into sales_order values('o02','p02') insert into sales_order values('o02','p05') insert into sales_order values('o03','p03') insert into sales_order values('o04','p01') insert into sales_order values('o05','p04') insert into sales_order values('o06','p06')
insert into product_master values('p01','1.44 floppies') insert into product_master values('p02','monitor') insert into product_master values('p03','mouse') insert into product_master values('p04','1.22 floppies') insert into product_master values('p05','key board') insert into product_master values('p06','cd drive') insert into product_master values('p07','hdd') insert into product_master values('p08','1.44 drive') insert into product_master values('p09','1.22 drive')
select * from product_master p_no p01 p02 p03 description 1.44 floppies monitor mouse
1.22 floppies key board cd drive hdd 1.44 drive 1.22 drive
SELECT DISTINCT p_no FROM product_master WHERE not EXISTS (select * from sales_order where sales_order.p_no=product_master.p_no) Or SELECT DISTINCT p_no FROM product_master WHERE p_no NOT IN (SELECT p_no FROM sales_order where sales_order.p_no=product_master.p_no) P_no p07 p08 p09
BLOCK
The first block:begin declare end (1) begin declare @roll int declare @name varchar(20) end O/P (2) begin declare @roll int set @roll=100 print @roll end declare @roll int begin set @roll=100 print @roll end O/P 100
(4) begin declare @name varchar(20),@name2 varchar(20) set @name='amit' set @name2='verma' print @name print @name2 print @name + @name2 end O/P amit verma amitverma Note:-print is used to output the text or variable; Note:-+ is used to for concanate (3) begin insert into student values(10,'asd') print 'successfully entered' end O/P successfully entered Note:-we can insert values in the table like this
if <condition> <begin> <statement> <end> (4) begin declare @a int set @a=200 if @a=100 begin print 'a=100' end print 'a=?' end O/P a=? if <condition> <begin> <statement> <end> else <begin> <statement> <end> (5) begin declare @num1 int
declare @num2 int set @num1 = 100 set @num2 = 200 if @num1 > @num2 print 'num1 greater than num2' else print 'num2 greater than num1' print 'successfully executed' end O/P num2 greater than num1 successfully executed if <condition> <begin> <statement> <end> else if <condition> <begin> <statement> <end> else <begin> <statement> <end>
(6) begin declare @num1 int declare @num2 int set @num1=100
set @num2=200 if @num1>@num2 begin print 'num1 greater than num2' end else if @num1<@num2 begin print 'num1 less than num2' end else begin print 'num1 equal tO num2' end end O/p num1 less than num2
set @j=1 while @j <=2 begin print @j set @j=@j+1 end set @i=@i+1 end end O/P 1 2 1 2 1 2 (2)
Break:begin declare @i int ,@j int set @i=1 while @i<=3 begin set @j=1 while @j <=2 begin if @j=2 break print @j set @j=@j+1 end
Continue:begin declare @i int set @i=1 while @i<=10 begin if @i>3 and @i< 7 begin set @i=@i+1 continue end print @i set @i=@i+1 end end O/P 1 2 3 7 8 9 10
Commit
begin transaction insert into stud values(17,'raj') commit transaction This commits the transaction(insert)
Rollback
begin transaction insert into stud values(18,'raj') rollback transaction This rollbacks the transaction(insert) last commit.
SAVE POINT
begin transaction t1 insert into stud values(8,'raj') save transaction t1 insert into stud values(9,'raj') save transaction t2 insert into stud values(10,'raj') save transaction t3 rollback transaction t1
NOTE:-Save transaction is just lika a book mark in our TSQL,thats reference we can use to tell sql server to rollback transaction upto.
begin transaction t1 insert into stud values(18,'raj') save transaction t1 insert into stud values(19,'raj') save transaction t2 insert into stud values(10,'raj') save transaction t3 commit transaction NOTE:- It finally save the transaction in memory. begin transaction t1 insert into stud values(118,'raj') save transaction t1 insert into stud values(119,'raj') save transaction t2 insert into stud values(1110,'raj') save transaction t3 rollback transaction
ERROR TRAPPING
select * from sysmessages
Table sysmessages in master message shows all errors numbers with description (1) begin transaction MYTRNS declare @error int save transaction t1 insert into stud values(6,'raj') select @error=@@error IF @error <> 0 begin print 'ERROR OCCURED' rollback transaction T1 end ELSE BEGIN print 'INSERTION SUCCESS' commit transaction END (2) begin transaction MYTRNS declare @error int save transaction t1 insert into stud values(7,'raj') select @error=@@error IF @error = 2627 begin print 'ERROR OCCURED' rollback transaction T1 end IF @error =0 BEGIN print 'INSERTION SUCCESS' commit transaction
END
Function
SIMPLE FUNCTIO THAT EXCEPTS TWO PARAMETERS AND RETURN A VALUE
CREATE FUNCTION TEST_FUNC(@A INTEGER,@B INTEGER) RETURNS INTEGER AS BEGIN RETURN (@A+@B) END -------------------------------BEGIN DECLARE @C AS INTEGER EXECUTE @C=TEST_FUNC 1,2 PRINT @C END
Overloaded Function
ALTER FUNCTION TEST_FUNC(@A INTEGER=100,@B INTEGER=200) RETURNS INTEGER AS BEGIN RETURN (@A+@B) END -------------------------------BEGIN DECLARE @C AS INTEGER EXECUTE @C=TEST_FUNC PRINT @C END
STORED PROCEDURE
select * from student Roll 1 2 3 4 Name amit raj ruppu ajnabi
Without parameter
create procedure proc_stud as select * from student execute proc_stud Roll 1 2 3 4 Name amit raj ruppu ajnabi
3 4 5
With one input and one output parameter And Alter Procedure
alter proc proc_stud @rn int, @nm varchar(25) output as select @nm=name from student where roll=@rn DECLARE @name varchar(30) execute proc_stud @rn=4, @nm=@name output print @name
output
ajnabi alter proc proc_stud @rn int, @nm varchar(25) output as if @rn=1 begin select @nm=name from student where roll=1 end else begin select @nm=name from student where roll=@rn end DECLARE @name varchar(30) execute proc_stud @rn=3, @nm=@name output
print @name output ruppu create proc proc_logincheck @user_name varchar(25), @pass_word varchar(25), @flag int output as if exists(select * from tab_login where user_name=@user_name and pass_word=@pass_word) set @flag=1 else set @flag=0 DECLARE @abc int execute proc_logincheck @user_name='amit', @pass_word='verma', @flag=@abc output print @abc
output
i am amit 2
execute proc_stud
output
amit raj ruppu ajnabi basu basu
Trigger
Trigger on insertion create trigger stud_ins on stud for insert as declare @name varchar(20) select @name=name from inserted if @name='verma' begin print 'can''t insert the name verma' rollback print 'trigger fired' end Trigger on deletion alter trigger del_stud on stud for delete as declare @roll1 int declare @name1 varchar(30) select @roll1=roll,@name1=name from deleted if @name1 ='chintu' begin print 'can''t delete '
rollback end
note:-DELETED ,INSERTED are system table and we have to use these tables in trigger as when we insert any record first it goes in INSERTED table ,and when we delete the deleted record goes in DELETED table,and for update we have to use combination of INSERTED and DELETED table because in updation two actions takes place first DELETION then INSERT
DROP TRIGGER
drop trigger stud_ins
Cursor
In Access or Visual Basic we have worked on record set ,cursor is just like record set but it is server side.The cursor is set of rows to gather with a pointer that identify a current row.
Steps for cursor:1. 2. 3. 4. 5. Declare cursor Open cursor Fetch records Close cursor Deallocate cursor
declare cursorname cursor [ local | global ] [ forword_only | scroll ] [ Static | Keyset | dynamic | fast_forward ] [ Read_only | Scroll_Locks | optimistic] [ Type_warning] FOR select_statement [ For update [ of column_names ] ] Local:-The local keyword limits the use of the cursor to the batch ,stored procedure,trigger where it was declared. Global:-The global keyword makes the cursor available to any statement to the current connection. Forward_only :- Forward_only specifies that only the next option of the Fetch(keyword) statement is supported. Scroll:- Scroll specifies that the option of the Fetch (keyword) should be
supported like:- Fetch next | Fetch prior | Fetch First | Fetch Last.If you specify scroll you can not specify Fast_Forward..
Static:-Static causes the cursor to return a set of rows that reflects(shows) the state
of the data base when the cursor is opened and that is never updated. (The database will be updated not the cursor)
Fast_forward:Read_only:-It specifies Cursor should be read only. Scroll_Locks:-It specifies that update or deletion made thrugh the cursor should always succeed.Sql server ensures this by locking the rows as soon as they are read into the cursor. Optimistic:-Optimistic uses optimistic locking when you attempt to change a row through the cursor. Type_warning:- Type_warning tells sql server to send a warning if the selected cursor options can not all be ful filled For select statement:- The select statement argument is a standard T-SQL select statement that supply the rows for the cursor.This statement can not use the COMPUTE,COMPUTE BY,FOR BROWSE ,INTO.options FOR UPDATE:-FOR UPDATE specifies explicitly that the cursor should allow updating if you use update of with a list of column name only data in those columns can be updated.
@@cursor_rows
declare mycursor cursor local scroll static optimistic type_warning for select name from student open mycursor print @@cursor_rows close mycursor
deallocate mycursor
output 4 @@Cursor_rows :- may return one of the follwing values A Negative number indicates that the cursor is being populated asynchronously and shows the number of rows retrive sofar.The value -57, for example ,indicates that the cursor have 57 rows,but the sql server has not finished populating cursor. declare mycursor cursor local scroll dynamic optimistic type_warning for select name from student open mycursor print @@cursor_rows close mycursor deallocate mycursor output -1
The value -1 is a special case that is always returned for dynamic cursors because other users can be adding or deleting data,Sql server can not be sure about the number of rows in a dynamic cursor or whether it is fully populated.
Select * from student Roll 1 2 3 5 name amit verma raj ruppu ajnabi
@@FETCH_STATUS-returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection. Return value 0 -1 -2 Description FETCH statement was successful. FETCH statement failed or the row was beyond the result set. Row fetched is missing
forward_only,Fetch , @@FETCH_STATUS
DECLARE @name varchar(25) declare mycursor cursor local forward_only dynamic optimistic type_warning for select name from student open mycursor fetch next from mycursor into @name print @name while @@fetch_status=0 begin fetch next from mycursor into @name print @name end close mycursor deallocate mycursor
output
amit verma raj ruppu ajnabi ajnabi
scroll,Fetch, @@FETCH_STATUS
DECLARE @name varchar(25) declare mycursor cursor local scroll dynamic optimistic type_warning for select name from student open mycursor fetch next from mycursor into @name print @name while @@fetch_status=0 begin fetch next from mycursor into @name
output
amit verma raj ruppu ajnabi ajnabi
DECLARE @name varchar(25) declare mycursor cursor local scroll dynamic optimistic type_warning for select name from student open mycursor fetch next from mycursor into @name print @name while @@fetch_status=0 begin set @name=nULL fetch next from mycursor into @name if @name='raj' begin set @name='abc' end print @name end close mycursor deallocate mycursor output amit verma abc
ruppu ajnabi
DECLARE @name varchar(25) declare mycursor cursor local scroll dynamic optimistic type_warning for select name from student open mycursor fetch last from mycursor into @name print @name while @@fetch_status=0 begin set @name=nULL fetch prior from mycursor into @name print @name end close mycursor deallocate mycursor
output
ajnabi ruppu raj amit verma
static
DECLARE @name varchar(25) declare mycursor cursor local forward_only static optimistic type_warning for select name from student open mycursor insert into student values(9,'sohan')
fetch next from mycursor into @name print @name while @@fetch_status=0 begin set @name=null fetch next from mycursor into @name print @name end close mycursor deallocate mycursor
output
amit verma raj ruppu ajnabi kamal goldi krisna raju DECLARE @name varchar(25) declare mycursor cursor local forward_only static optimistic type_warning for select name from student open mycursor update student set name='rohan' where roll=4 fetch next from mycursor into @name print @name while @@fetch_status=0 begin set @name=null fetch next from mycursor into @name print @name end close mycursor deallocate mycursor
output
amit verma raj ruppu ajnabi rohan goldi krisna
raju
dynamic
DECLARE @name varchar(25) declare mycursor cursor local forward_only dynamic optimistic type_warning for select name from student open mycursor insert into student values(6,'goldi') fetch next from mycursor into @name print @name while @@fetch_status=0 begin set @name=null fetch next from mycursor into @name print @name end close mycursor deallocate mycursor
output
amit verma raj ruppu ajnabi golu goldi
keyset
DECLARE @name varchar(25) declare mycursor cursor local forward_only keyset
optimistic type_warning for select name from student open mycursor update student set name='rohan kumar' where roll=4 fetch next from mycursor into @name print @name while @@fetch_status=0 begin set @name=null fetch next from mycursor into @name print @name end close mycursor deallocate mycursor
output
amit verma raj ruppu ajnabi rohan kumar goldi krisna raju sohan
VIEW
SYNTAX:CREATE VIEW VIEWNAME AS SELECT-STATEMENT; Eg:
create view view1 as select * from student;
NOTE:(1) View created on a single table supports all DML(INSERT,UPDATE,DELETE,SELECT) operations, and will affect the base table as well. (2) If the user wants to insert with the help of the view then they primary key column and all the not null column must be included in the view. (3)Any DML operation on view need base table constraints to be followed
Update-> not allowed in both detail and master Delete->not allowed MULTIPLE TABLE WITHOUT RELATION BUT JOIN(without key field) ADD-> allowed in master ADD-> allowed in detail ADD->not allowed in both detail and master Update->can update in master Update->can update in detail Update-> not allowed in both detail and master Delete->can not delete from view in detail and master. MULTIPLE TABLE WITHOUT RELATION BUT JOIN(between unique key field) ADD-> allowed in master ADD-> allowed in detail ADD->not allowed in both detail and master Update->can update in master Update->can update in detail Update-> not allowed in both detail and master Delete->can not delete from view in detail and master.
NOTE:-After this observation we can make a concept that using view we can do insert,update opration on invidual tables of the view not on the both at a time.Delete operation is not supported using view .
To DROP A VIEW
drop view viewname
Creating Indexing
create index ind_stud on student (name)
DATEDIFF
Returns the number of date and time boundaries crossed between two specified dates.
Syntax
datepart Is the parameter that specifies on which part of the date to calculate the difference. The table lists dateparts and abbreviations recognized by Microsoft SQL Server. Datepart Year quarter Month dayofyear Day Week Hour minute second millisecond yy, yyyy qq, q mm, m dy, y dd, d wk, ww hh mi, n ss, s ms Abbreviations