Вы находитесь на странице: 1из 26

session:-1

creating database
commands in database

create database practiceDb

use practiceDb

--1.DML---Data Manuplation Languages( Select, Insert, Update, Delete)


--2.DDL--- Data Definition Languages(create, alter, drop, truncate, Rename)
--3.DCL---Data Control Languages( Grant, Revoke)
--4.TCL---Transaction Control Languages (Commit, Rollback, Savepoint)
--5.DQL---Data Query Languages (
--Constraints (Primary Key, Foreign Key, Check, Unique, Default, NotNull)

DML
-------
Insert, update, Delete

insert--Insert is used for adding the record


update--update is used for modifing the existing records
Delete--It will delete records from table
(If you didn't use where clause then it will delete all records from the table)
Better use where clause it will delete specific conditional records.

DDL
----
Create, Alter Drop

--Create--We can create specific objects in database


(like:- Table, Functions, Database, Procedures..etc

--Alter---It is used for modifiying the meta data information of specific objectsin
database

---DROP:- it is use for deleting the entire objects with structure from database

DCL
----

Grant and Revoke

TCL
----
Commit, Rollback

By Default sql server auto commit the sql statements

commit:- It will commit the Data permenently in database after that we cont
rollback the data
Rollback-- It will re-load the previous data

DQL
---
Select--- To view the table data
Session:-2
----------

Create table Employee(empid)


For each column there is three properies
(name of the column
data type
size of the column)

int
varchar(100)---non unicode data type
1 characteer--1 byte
nvarchar(19)---unicode data type
float
decimal
char()
text
money

create table employee(empid int, empname varchar(50),salary money)


select * from employee

sp_help employee

select * from employee


insert into employee(empid, empname,salary)
values(1,'ABC',1000),(2,'ADC',3000),(4,'Jhon'3000)

update employee set empname='Raj' where empname='ABC'

Begin tran
Delete from employee

Rollback

Delete from employee where empid=2

Sp_help employee

Alter table employee alter column empname varchar(100)----(datatype changed)

sp_help employee

Alter table employee add Grade char(1)

select * from employee

Drop

create table student (name varchar(20),rollno int, salary money)


select * from student
insert into student values ('AAA',101,20000)
insert into student values ('BBB',102,30000)
insert into student values ('CCC',103,40000)

select salary from student where


select * from student where MARK>=200

--SQL Server operators:-


1)ARITHMETICAL OPEATIORS:
+ADD
-SUB
*MULT
/DIV
%MODULUS

--2)RELATIONAL OPERATORS:-

< > <= >= =(<> OR !=) NOT EQUAL TO


--3) LOGICAL OPERATOR:
AND , OR, NOT
--4) SPECICAL OPERATOR:-
IN, NOT IN, BETWEEN, NOT BEETWEEN, LIKE, NOT LIKE,IS , ANY, EXISTS
--5) SET OPERATORS;
UNION, UNION ALL, INTERSECT, EXCEPT

EXAMPLE;-

create table student (name varchar(20),rollno int, salary money)


select * from student
TRUNCATE TABLE STUDENT
insert into student values ('AAA',101,200)
insert into student values ('BBB',102,300)
insert into student values ('CCC',103,400)
insert into student values ('DDD',104,500)

SELECT * FROM STUDENT WHERE SALARY>=300


SELECT * FROM STUDENT WHERE SALARY IN(300,500)
SELECT * FROM STUDENT WHERE SALARY NOT IN(300,500)

SELECT * FROM STUDENT


SELECT * FROM STUDENT WHERE SALARY BETWEEN 200 AND 400
SELECT * FROM STUDENT WHERE SALARY NOT BETWEEN 200 AND 400
SELECT * FROM STUDENT WHERE NAME LIKE 'A%'
SELECT * FROM STUDENT WHERE NAME '%D'
SELECT * FROM STUDENT WHERE NAME 'D%'

DELETE FROM STUDENT WHERE ROLLNO


DELETE FROM STUDENT WHERE ROLLNO=101
SELECT * FROM STUDENT
DELETE * FROM STUDENT WHERE ROLLNO=102
SELECT * FROM STUDENT

TRUNCATE TABLE STUDENT


SELECT * FROM STUDENT DROP TABLE STUDENT

DROP TABLE STUDENT

ALTER TABLE EMPLOYEE ADD DEDUCTION MONEY


SELECT * FROM EMPLOYEE
SP_HELP 'EMPLOYEE'

ALTEER TABLE EMPLOYEE ALTER COLUMN ENAME VARCHAR(25)


ALTER TABLE EMPLOYEE DROP COLUMN ALLOWANCE

TRUNCATE COMMAND:
IT IS USED TO DELETE ALL RECORDS

DROP COMMAND:-

IT IS USED TO DELETE WHOLE TABLE

TRUNCATE TABLE EMPLOYEE


SELECT * FROM EMPLOYEE

DROP TABLE EMPLOYEE


SELECT* FORM EMPLOYEE

create table employee(e_id int Not Null, e_name varchar(20),e_salary int,e_age


int,e_gender varchar(20),
e_dept varchar(20), primary key(e_id))

select * from employee

insert into employee values (1,'sum',95000,45,'Male','Operations',0);


insert into employee values (2,'Bob',80000,21,'Male','Support',0);
insert into employee values (3,'Anne',125000,25,'Female','Analytics',0);
insert into employee values (4,'Jula',73000,30,'Female','Analytics',0);
insert into employee values (5,'Mett',159000,33,'Male','Sales',0);
insert into employee values (6,'Jeff',112000,27,'Male','Operations',0);

select distinct e_gender from employee ----(distinct is used o select only distinct
values from our column)
exam:-

select distinct e_gender from employee

------Where claues (Where clause is used to to extract records which satisfy a


condition(Letss filter records with wheree claues))
------ (select column1, column2 columnN from tablename WHERE(condition))

Example:-
select * from employee where e_gender='female'
select * from employee where e_age=30;
select * from employee Where e_salary>100000;

---AND(operator)--(And operator displays records if all the condition separated by


AND Are TRUE
select column1, column2, columnN from tablename WHERE (condition)AND(condition),AND
(condition)

ex-
select * from employee where e_gender='Male' AND e_age<30;
select * from employee where e_dept='operations' AND e_salary>100000;

---OR(operator)(OR operator displays records if any of the condition separated by


OR is TRUE)
---letes impose Multiple conditions with "OR"
select * from employee where e_dept='operations' OR e_dept='Analytics';
select * from employee where e_salary>100000 OR e_age>30;

---NOT Operator(Not operator displays a recors if the condition is 'NOT TRUE"

select * from employee where not e_gender='female';


select * from employee where not e_age<30;

---LIKE(operator Like operator is used to extract records where a particular


pattern is present
---Wild Cardd character
%--->percantage symbal--> represents zero, one or multiple character
_--->underscore symbol--> Represents a single characteer

LIKE operator synt :-let's extract recordds where the pattern matches
--select l_list from table_name WHERE Column_N like

select * from employee where e_name like'J%';


select * from employee where e_age like'3_';

--BETWEEEN (operator)(Between operator is used to select values within a given


range
---lets extract values b/w a given range
select col_list from tablename where columnN between vale1 and vale2;

select * from employee where e_age Between 25 and 35;


select * from employee where e_salary Between 90000 and 120000;

--FUNCTIONS
MIN(min()function give you the smallest values

select min(e_age)as minimumage from employee;


select min(e_salary) from employee;

---MAX(max function gives you the largest value


select max(e_age) from employee
select max(e_salary) from employee

---COUNT(Count function returns the number of rows that match a specfic creteria
ex;-

select * from employee

select count(*) from employee where e_gender='male';


select count(*) from employee where e_dept='Analytics';

---SUM()Sum function gives the total sum of a numeric column

ex;-
select sum(e_salary)from employee;

---AVG() Avg function gives the average values of numeric column


ex;-
select avg(e_age)from employee;

---------------STRING FUNCTION;-

LTRIM()---->Removes blanks on the leftside of the character expression


LOWER()---->Converts all characters to lower case letters
UPPER()----> converts all character to uppercase letters
REVERSE()-----> Reverses al the characters in the string
SUBSTRING()----> Gives a substring from the original string

select ascii('z')---a-97 ...z--122


select char(90)----65--A....90--Z
select CHARINDEX('or','corporation')---2.. used to find the first occurance of
strings within string from the given position
select SUBSTRING('prasad',2,5)--rasad
select LEFT('prasad',4)---pras
select right('prasad',4)---asad
select REVERSE('prasad')---dasarp
select LEN('prasad')---6
select ltrim(' prasad')--prasad
select RTRIM('prasad ')---prasad
select STUFF('prasad',1,3,'ni')---nisad
select LOWER('PRASAD')---prasad
select UPPER('prasad')---PRASAD

Date functions:

select GETDATE()---2017-04-12 06:21:17.570

select DATEPART(DD,GETDATE())---29--today date


select DATEPART(MM,GETDATE())---9--This month
select DATEPART(WW,GETDATE())---39 weak of year
select DATEPART(QQ,GETDATE())---3 Quater of year
select DATEPART(yy,GETDATE())---2019
select DATEPART(MI,GETDATE())---26 minits

select DATENAME(mm,getdate())---September ...it's show this month

select DATENAME(DW,getdate())---Wednesday...today e varam aneydi

select DATEDIFF(dd,'2000-01-04',getdate())--7205

select DATEDIFF(ww,'2000-01-04',getdate())--1029

select DATEDIFF(yy,'2000-01-04',getdate())--19

select DATEADD(dd,5,getdate())--2019-10-01 09:48:41.640


select DATEADD(MM,5,getdate())--2020-02-26 09:49:02.957

select DATEADD(MM,-3,getdate())---2019-06-26 09:49:23.737

--STRING FUNCTIONS

select ascii('z')---a-97 ...z--122


select char(90)----65--A....90--Z
select CHARINDEX('or','corporation')---2.. used to find the first occurance of
strings within string from the given position
select SUBSTRING('prasad',2,5)--rasad
select LEFT('prasad',4)---pras
select right('prasad',4)---asad
select REVERSE('prasad')---dasarp
select LEN('prasad')---6
select ltrim(' prasad')--prasad
select RTRIM('prasad ')---prasad
select STUFF('prasad',1,3,'ni')---nisad
select LOWER('PRASAD')---prasad
select UPPER('prasad')---PRASAD

--> LTRIM()

select' avulavenkatareddy'
select LTRIM(' avulavenkatareddy')

--->LOWER
Select 'THIS IS VENKATAREDDYYY'
Select Lower('THIS IS VENKATAREDDYYYY')

UPPER

select 'heloo ravikumar'


select UPPER('heloo ravikumar')

REVERSE()

Select 'I love India'

select reverse('I love India')

SUB STRING

SELECT 'THIS IS SPARTA'

SELECT SUBSTRING('this is sparta')


SELECT SUBSTRING ('this is sparta',9,6)\

---ORDER BY;- Order by is used to sort the data in ascending or descending order
ASCENDING DESCENDIG
-- Let's soft the records with order by clause
--select column list from tablename ORDERBY Col,Cole---ASC/DESC

select * from employee ORDER BY e_salary;


select * from employee ORDER By e_salary DESC;
select * from employee ORDER BY e_id asc;
select * from employee order by e_dept asc;

---TOP ClAUSE;- Top is used to fetech the TOP N records


--let' s get the top N records
select top 3 * from employee
select top 3 * from employee order by e_age DESC;

----GROUP BY;- (Group by is used to get aggregate result with respect to group
----Let'ss group the data
-->
select avg(e_age),e_dept from employee GROUP BY e_dept ORDER BY Avg(e_age)DESC;

----(HAVING CLAUSE);-
Having clause is used in combination with GROUP BY to impose conditions on groups
--> let's impose conditions on groups with the having clause
ex-
select e_dept,avg(e_salary) as avg_salary from employee group by e_dept

select e_dept,avg(e_salary) as avg_salary from employee group by e_dept having


avg(e_salary)>100000

UPDATE STATEMENT;-(Update is modify the existing recordds in a table )


ex;-
update employee set e_age=42 where e_name='sam';

select * from employee

update employee set e_dept='tech' where e_gender='Female';

select * from employee

update employee set e_salary=500000;

select * from employee

DELETE STATEMENT:-delete statement is used to delete existing records in the table

delete from employee where e_age=33;


select * from employee
Delete from employee where e_name='sam';
Truncate table employee;

create table department (d_id int NOT Null,d_name varchar(20),d_location


varchar(20))
insert into department values (1,'content','Newyork'),(2,'support','Chickago'),
(3,'Analytics','Newyork'),(4,'Sales','Borton'),
(5,'tech','Dallas'),(6,'Finance','Chicago')

JOINS:-

INNER JOIN;-(INNER JOIN RETURNS RECORDS THAT HAVE MATCHING VALUES IN BOTH THE
TABLES. IT IS ALSO KNOW AS SIMPLE JOIN.
syntax:-
select column from table,
Inner join table2 ON table1.column_x=table2,column_z

select * from employee


select * from department
select employee. e_id, employee.e_dept,department.d_name,department.d_location
From employee
Inner Join
department On employee.e_id=department.d_id

select employee. e_name, employee.e_dept,department.d_name,department.d_location


From employee
Inner Join
department On employee.e_dept=department.d_name

2) Left Join:(left join returns all the records from the lift table, and the
matched recordds from the right table)
ex;-

select * from employee


select * from department

select employee.e_name,employee.e_dept,department.d_name,department.d_location from


employee
left join department
On employee.e_dept=department.d_name;

3)Right Join:- Right join return all the records from the right table, and the
matched recordds from the left table

select employee.e_name,employee.e_dept,department.d_name,department.d_location From


employee
Right Join department
On employee.e_dept=department.d_name;

4) Full Join
(It returns all rows from the left table and the Right table with Null values
inplace where the Join condtion is not met)

select employee.e_name, employee.e_dept, department.d_name,department.d_location


From employee
Full Join department On employee.e_dept=department.d_name;

UPDATE THE JOIN:-

update employee
set e_age=e_age+10
from employee
join department on employee.e_dept=department.d_name
where d_location='Newyork'

DELETE THE JOIN:-

Delete employee
from employee
join department on employee.e_dept=department.d_name
where d_location='Newyork'

UNION OPERATOR:-
union operator is used to combine the result-set of two or more select statement

create table studentdetails1 (s_id int,s_name varchar(20),s_marks int)


insert into studentdetails1 values(1,'sam',45),(2,'Bob',87),(3,'Anne',73),
(4,'Julia',92)

create table studentdetails2 (s_id int,s_name varchar(20),s_marks int)

insert into studentdetails1 values(3,'Anne',73),(4,'Julia',92),(5,'Mats',65)

select * from studentdetails1


select * from studentdetails2

ex:-
select * from studentdetails1
union
select * from studentdetails2

UNION ALL:- (union all operators gives all the rows from both the tables including
the duplicates

select * from studentdetails1


union all
select * from studentdetails2

EXCEPT OPERATOR:-
Expect operator combines two select statements and returns unique records from the
left query which are not party
of the right query,

ex;-

select * from studentdetails1


Except
select * from studentdetails2

INTERSECT OPERATOR:-
Intersect operator helps to combine two select statements and returns the records
which are common to both the select statements.
ex;-

select * from studentdetails1


intersect
select * from studentdetails2

VIEW:- view is a virtual table based on the result of on sql statement

select * from employee

create view female_employees AS select * from employee where e_gender='Female';

select * from female_employees

DROP VIEW:-

drop view female_employees;

select * from female_employees;

ALTER TABLE:- Alter table statement is used to add, delete, or modify column in a
table

syntax

Alter table table_name


Add column_name datatype;

ex;-
Alter table employee Add e_dob date;

select * from employee


ALTER TABLE--DROP COLUMN

Alter table table_name


Drop column column_name;
ex;-
alter table employee
drop column e_dob

MERGE:--(Merge is the combination of insert, delete and update statements)

create table empsourcetable (e_id int,e_name varchar(20),e_salary int,e_age


int,e_gender varchar(20),e_dept varchar(20))

insert into empsourcetable values(1,'sam',93000,40,'Male','Operation'),


(2,'Bob',80000,21,'Male','Support'),
(3,'Anne',130000,25,'Male','Support'),(6,'Jeff',112000,27,'Male','Analytics'),
(7,'Adam',100000,28,'Male','Operation'),
(8,'Priya',85000,'37','Female','Tech')

create table emptargettable (e_id int,e_name varchar(20),e_salary int,e_age


int,e_gender varchar(20),e_dept varchar(20))

insert into emptargettable values(1,'sam',95000,45,'Male','Operation'),


(2,'Bob',80000,21,'Male','Support'),
(3,'Anne',125000,25,'FeMale','Analysis'),(4,'julia',73000,30,'Female','analytics'),
(5,'matt',159000,33,'Male','Sales'),
(6,'Jeff',112000,27,'Male','Operation')

select * from empsourcetable


select * from emptargettable

Merge(target)As T
using (source)AS S
on(join condition)
When Matched
Then (update statement)
When Not Matched by Target
Then (insert statement)
When Not Matched by source
Then(delete statement);

Ex;-

Merge emptargettable As T
using empSourcetable As S
ON T.e_id=s.e_id
When matched
Then update set T.e_salary=S.e_salary,T.e_age=S.e_age
When Not Matched by Target by Target
Then insert (e_id,e_name,e_salary,e_age,e_gender,e_dept)
values(S.e_id,S.e_name,S.e_salary,S.e_age,S.e_age,S.e_gender,S.e_dept)

When Not Matched by source

Then delete;
--> select * from emptargettable

TYPES OF USER DEFINED FUNCTIONS:-


-->Scalar valued funcations
-->Table Valued Funcation

SCALAR VALUED FUNCATION:-

scalar valued funcation always returns a scalar value

syntax:-
create funcation funcation_name(@param1 datatype,@param2 datatype..)
Returns return_datatype
AS
BEGIN
----Function body
Return value
End

Ex;-

Create function add_Five(@num as int)


Returns int
AS
BEGIN
RETURN (
@ num+5
)
end

select dbo.add_five(100)

STORED PROCEDURE IN SQL:-

SP IS A PREPARED Sql code which can be saved and reused


--Stored Programs

--Stored programs are the sub progrmas that are permanently stored in database.
--Stored programs are excuting will be fast when compared with individuaal sql
statements.

--SQL STATEMENT----->PARSING---->EXECUTION PLAN GENERATION------>COST


ESTIMATION---->EXECUTION PLAN WITH LOW COST--->EXECUTE
-- .
-- .
-- .
-- IT WILL CHECK SYNTAX
-- OBJECT AVAILABILITY
-- SECURITY
-- DATATYPE COMPATABILITY

--STORED PROGRAM:

-- COMPILED--->EXECUTION PLAN WITH LOW COST FOR EVERY STATEMENT---DATABASE

-- When you are creating a stored subprogram then during creation itself parsing,
-- execution plan generation and cost estimation will be done for every statement
-- in the stored program and exection plan with low cost for every statement will
-- be saved peanently in database . as execution plan readily available ,
-- execution will be fast and will increase performence.

-- Default arguments:

-- While creating the procedure if you initialize the parameters .

create procedure sum(@A int,@B int,@C int=0,@D int=0)


as
begin
print @A+@B+@C+@D
end

--To call the procedure:

Exec sum 55,55


--or

Exec sum 55,55,55,55

--DROP PROC EMPLOYEE_DETAILS

CREATE PROCEDURE EMPLOYEE_DETAILS


AS
BEGIN
UPDATE A SET A.SAL=B.SAL,
A.comm=B.comm
FROM EMP A JOIN RAW_TABLE B
ON A.dept=B.dept
END

ALTER PROCEDURE EMPLOYEE_DETAILS


AS
BEGIN
UPDATE A SET A.SAL=B.SAL,
A.comm=B.comm
FROM EMP A JOIN RAW_TABLE B
ON A.dept=B.dept

INSERT INTO EMP


SELECT * FROM RAW_TABLE A WHERE NOT EXISTS (SELECT dept FROM EMP B
WHERE A.dept=B.dept)
END

EXEC EMPLOYEE_DETAILS

SP_HELPTEXT 'EMPLOYEE_DETAILS'
sp without parameter;-

create procedure procedure_name


AS
SQL_statement
Go

Ex:-

Create procedure employee_age


AS
BEGIN
Select * from employee where e_id=5
END
go
alter procedure employee_age
AS
BEGIN
Select * from employee where e_id=6
END
go
Exec employee_age

create procedure employee_details


AS
select* employee
go

Exec employee_details

SP WITH PARAMETER SYNTAX:-


Syntax
create procedure procedure_name
@param1 data-type @param2 data-type
AS
Sql-statement
Go

ex:-

create procedure employee_gender@gender varchar(20)


AS
select * from employee
where e_gender=@gender
Go

exec employee_gender='Male'

exec employee_gender @gender='Female'

Declare @a int,@b int ,@c int


set @a=10
set @b=20

select @c=@a+@b
select @c
--or
--Print @c

--FUNCTIONS;

--User defined functions are the stored subprograms that can be return a value with
return statement.

--Functions are classified into 2 types


--Scalar functions : It can return a single value with return statement.
Ex: Create function addition(@a int ,@b int)
Returns int
As
Begin
return @a+@b
end

--Calling function using select statement or Print

select dbo.addition(1,2)

--Table valued functions: It can return rows and columns


--These are 2 type

-->Inline table valued functions


-->Multistatement table valued functions

--Inline table valued functions -->Multistatement table valued


functions
----------------------------
------------------------------------------------------------
--Returns rows and columns -- It Returns rows and columns
--Use only select statement -- It will use n number of
statements
--No need to use of -- We should use
--Begin Begin
--End statements End statements
--No need to provide structure of the table. We need to provide structure of
the table.

--Ex: Inline table valued functions

ALTER function getdetails(@EID int)


Returns table
As
return(select * from EMPLOYEE where E_ID=@EID)

--Calling function
select * from getdetails(5)

--EX: Multistatement table valued functions


create function getdetails1(@dept int)
returns @company table (dept int, sal int)
as
begin
insert into @company
select dept,sal from emp where dept=@dept

return
end

--Calling function
select * from getdetails1(2)

EXEC getdetails1

--Built in Functions

--Which are called as predifined functions.

--They are

--1.Scalar functions
--2.Aggregte functions
--3.Ranking functions

--Scalar functions: Operats on single value


--They are

-->Numeric functions
-->String functions
-->Date functions

--Numeric functions:Operate on numeric type of data

--Theyare:

select ABS(99.90)--99.90
select RADIANS(30.00)---0.523598775598298790---convert degress to radians
select DEGREES(0.523598775598298790)---29.999999999999996000---convert radians to
degress
select SIN(RADIANS(30.00))---0.5
select COS(RADIANS(30.00))--0.866025403784439
select TAN(RADIANS(30.00))--0.577350269189626
select LOG(2)---0.693147180559945
select LOG10(2)---0.301029995663981
select EXP(3)---20.0855369231877----e raised to the power of n
select CEILING(56.354)---57 -----nearest integer >=n
select FLOOR(56.354)-----56 -----nearest integer <=n
select ROUND(75.467,2)---75.4600
select ROUND(75.437,2)---75.440
select SQUARE(25)---5
select POWER(5,2)--25
--STRING FUNCTIONS

select ascii('z')---a-97 ...z--122


select char(90)----65--A....90--Z
select CHARINDEX('or','corporation')---2.. used to find the first occurance of
strings within string from the given position
select SUBSTRING('prasad',2,5)--rasad
select LEFT('prasad',4)---pras
select right('prasad',4)---asad
select REVERSE('prasad')---dasarp
select LEN('prasad')---6
select ltrim(' prasad')--prasad
select RTRIM('prasad ')---prasad
select STUFF('prasad',1,3,'ni')---nisad
select LOWER('PRASAD')---prasad
select UPPER('prasad')---PRASAD

--Date functions:

select GETDATE()---2017-04-12 06:21:17.570

select DATEPART(DD,GETDATE())---12--today date


select DATEPART(MM,GETDATE())---4--This month
select DATEPART(WW,GETDATE())---15 weak of year
select DATEPART(QQ,GETDATE())---2 Quater of year
select DATEPART(yy,GETDATE())---2017
select DATEPART(MI,GETDATE())---26 minits

select DATENAME(mm,getdate())---April

select DATENAME(DW,getdate())---Wednesday

select DATEDIFF(dd,'2000-01-04',getdate())--6308

select DATEDIFF(ww,'2000-01-04',getdate())--901

select DATEDIFF(yy,'2000-01-04',getdate())--17

select DATEADD(dd,5,getdate())--2017-04-17 06:31:44.520


select DATEADD(MM,5,getdate())--2017-09-12 06:32:20.990

select DATEADD(MM,-3,getdate())---2017-01-12 06:32:55.230

--Coversion Functions:

CONSTRAINST

CREATE TABLE PART_SAMPLE


(PART_NMBR INT PRIMARY KEY,
PART_NAME CHAR(30),
PART_WEIGHT DECIMAL(6,2),
PART_COLOR CHAR(15)
)

CREATE TABLE cust_sample


(
cust_id int PRIMARY KEY,
cust_name char(50),
cust_address char(50),
sal money check (sal>1000),
sub varchar(10) default('SQL')
)

CREATE TABLE ORDER_PART


(ORDER_NMBR INT,
PART_NMBR INT
FOREIGN KEY REFERENCES PART_SAMPLE(PART_NMBR),

QTY_ORDERED INT
)

CREATE TABLE FACTORY_PROCESS


(EVENT_TYPE INT,
EVENT_TIME DATETIME,
EVENT_SITE CHAR(50),
EVENT_DESC CHAR(1024),
CONSTRAINT EVENT_KEY PRIMARY KEY (EVENT_TYPE, EVENT_TIME) )

ALTER TABLE PRODUCTS


ADD CONSTRAINT PK_PRODUCTS_PID PRIMARY KEY(PRODUCTID)
GO
--ALTER STATEMENT TO DROP PRIMARY KEY

ALTER TABLE PRODUCTS


DROP CONSTRAINT PK_PRODUCTS_PID;
GO

ALTER TABLE PRODUCTSALES


ADD CONSTRAINT FK_PRODUCTSALES_PID FOREIGN KEY(PRODUCTID)REFERENCES
PRODUCTS(PRODUCTID)
GO
--ALTER TABLE STATEMENT TO DROP FOREIGN KEY

ALTER TABLE PRODUCTSALES


DROP CONSTRAINT FK_PRODUCTSALES_PID;

--ALTER TABLE STATEMENT TO ADD DEFAULT CONSTRAINT

ALTER TABLE CUSTOMER


ADD CONSTRAINT DF_CUSTOMER_ADD DEFAULT 'UNKNOWN' FOR CUSTOMERADDRESS
GO
--ALTER TABLE TO DROP DEFAULT CONSTRAINT

ALTER TABLE CUSTOMER


DROP CONSTRAINT DF_CUSTOMER_ADD
GO

CURSORS
--CURSOR: IS USED TO READ or EXECUTING THE DATA FROM THE TABLE ROW BY ROW.

--FOLLOW THE BELOW STPES FOR CRATING CURSOR


--------------------------------------------
--1>DECLARE CURSOR
--2>OPEN CURSOR
--3>FETCH CURSOR

-- 0--READ DATA
-- 1--THERE IS NO DATA
-- 2--DELETED
-- -1--COME OUT OF LOOP

--4>CLOSE CURSOR
--5>DEALLOCATE CURSOR

--.

--NOTE:SELECT @@CURSOR_ROWS---HOW MANY ROWS IN CURSOR


-- SELECT @@FETCH_STATUS

DECLARE @VAR VARCHAR(40)


DECLARE CURSOR_NAME CURSOR
FOR SELECT dept FROM EMP
OPEN CURSOR_NAME
FETCH NEXT FROM CURSOR_NAME INTO @VAR
WHILE (@@FETCH_STATUS=0)
BEGIN
PRINT @VAR
FETCH NEXT FROM CURSOR_NAME INTO @VAR
END
close CURSOR_NAME
DEALLOCATE CURSOR_NAME

DECLARE MYCUR SCROLL CURSOR


FOR SELECT dept FROM EMP
OPEN MYCUR
FETCH NEXT FROM MYCUR
FETCH PRIOR FROM MYCUR
FETCH FIRST FROM MYCUR
FETCH LAST FROM MYCUR
CLOSE MYCUR
DEALLOCATE MYCUR

--SCROLL---EVERY OPTION IN THE FETCH IS WORK


--SELECT DEPT FROM EMP

IDENTITY:-

--Identity Column:Generate the sequnce of values.


--Sytax:Identity(seed,increment)
--Delete the rows from the table It wont resent the values from the starting number
--Trunate the rows from the table It will resent the values from the starting
number
--------------
create table #2(id int identity(1,1),
name varchar(50))

alter table #2 alter column name nvarchar(20)


insert into #2(name)
values('venkat'),
('raja'),
('rani')

select * from #2
delete from #2
insert into #2(name)
values('venkat'),
('raja'),
('rani')
select * from #2
truncate table #2
select * from #2

insert into #2(name)


values('venkat'),
('raja'),
('rani')
select * from #2

INDEXES

--Indexes: Are used to make the data retreval fast.

--Table Scan:Scanning of each and every row in the table for the given codition.

--Types:
--Clustered index: when you create clustered index on a column then the rows in the
table will be physically stored in memory in
--sorted order in memory.
--Draback: Insert and update will be slow.
--overcome: by clustered index specify the FillFactor.

--NonClustered index: Will not be arranged insorted order.


--in SQL SERVER 2005-249
-- SQL SERVER 2008-999

-- SYNTAX:
-- CREATE [CLUSTERED/NON-CLUSTERED]
-- INDEX <INDEX NAME> ON <TABLE NAME>
-- (<COLUMN NAME>)

--NON-CLUSTERED:
CREATE INDEX ID_IDX ON EMP(empno)

--DROP INDEX <INDEX NAME> ON <TABLE NAME>

drop index ID_IDX ON EMP

--CLUSTERED:
CREATE CLUSTERED INDEX ID_IDX ON EMP(empno)

--USE WITH FILLFACTOR:


CREATE CLUSTERED INDEX ID_IDX ON EMP(empno)
WITH (FILLFACTOR = 80);

PREDICATES

--Predicates
--.............

--Every operater that is used within the condtion in where class is called as
Predicates.

--They are as follows


--......................
--Between ... And
--In
--Like
--Isnull

--Between ... And: This is used to verify whether the given value is available
within the given range of values.
--................
--Ex: Find the employees where salary is more than or equal to 2000 and less than
are equal to 3000

select * from emp where sal>=2000 and sal<=3000


--Or

select * from emp where sal between 2000 and 3000

--In: This is used to check whether the given value is with in the given list of
values.
---

select * from emp where sal in(2000,3000)

Like: This is used to search for a particular pattern within a given column.
----
We can use two wild card characters
%---Multiple characters
_ A single Character

Ex:
Find the employees whose name starts with the alphabet 'S'

select * from emp where nmae like 'S%'

Find the employees whose name ends with the alphabet 'S'

select * from emp where nmae like '%S'

Find the employees whose name contain alphabet 'S' any where in their name
select * from emp where nmae like '%S%'

Find the employees whose name contain the alphabet 'L' as 2nd letter in their name

select * from emp where nmae like '_L%'

Find the employees whose name contain the alphabet in the range of 'A' to 'K' as
but one char in their name.

select * from emp where nmae like '%[A-K]_'

Isnull:Used to search for null in a column

select * from emp where comm is null

SUBQUERIES

--Sub Queries
--A query that was written within another query is called sub query.

--They are 2 types

--Single row sub query


--Multi row sub query

--Single row sub query-- It returns a single row.

--Find the employees working in sales dept.

select * from emp where dept=(select did from dept where dname='sales')

--Multi row sub query--It returns more than one row.

--Find the employees who are drawing highest salary dept wise.

select * from emp where sal in(select max(sal) from emp group by dept)

--Find the employees whose salary is more than the avg salary of sales dept.

select * from emp where sal>(select avg(sal) from emp where dept=
(select did from
Dept where dname='sales'))

--Co-Related sub queries:

--A sub query that refers to a column of main query within its where class.

--Find the employees whose salary is more than avg salary of same dept in which
employee working.

select * from emp e where sal>(select avg(sal) from emp s where s.dept=e.dept)
--Note: Co-Related sub query executed multiple times once for each row of the main
query.

--find the highest salary employees dept wise.

select * from emp e where sal=(select max(sal) from emp s where s.dept=e.dept)

TRIGGERS

--Triggers:
--Triggers are execute automatically whenever action is occure.
--WE CAN ALTER ,DROP TRIGGERS.

--2Types
--......
--DML TRIGGERS:USED AT DATA BASE LEVEL
--DDL TRIGGERS:USED AT SERVSER LEVEL

--DML TRIGGERS: 2 TYPES


--............

--AFTER TRIGGERS INSTED OF TRIGGERS


--................ ...................
--ONLY TABLE LEVEN TABLE AND VIEW LEVEL
--AFTER EXECUTION OF THE ACTION FUNCTIONALITY WILL BE EXECUTED

--FUNCTIONALITY WILL BE EXECUTE. INSTED OF ACTION THAT AS BEEN TAKEN.


-- WE CAN'T CREATE IDENTITY
COLUMN,COMPUTTED COLUMN
-- AND TIME STAMP
DATA TYPE.

--ACTION CLASSES:
--INSERT
--UPDATE
--DELETE

--AFTER TRIGGERS:
--CREATE TRIGGER NAME
-- ON EMP <ACTION>INSERT---> FUCTIONALITY
-- --MAINLY USED FOR AUDIT PURPOSE.

--DROP TRIGGER trgAfterInsert

CREATE TABLE Employee_Test


(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test VALUES ('Anees',1000);


INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);
--SELECT * FROM Employee_Test

CREATE TABLE Employee_Test_Audit


(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)

--TRUNCATE TABLE Employee_Test_Audit


--SELECT * FROM Employee_Test_Audit

CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test]


AFTER INSERT
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

select @empid=i.Emp_ID from inserted i;


select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;
set @audit_action='Inserted Record -- After Insert Trigger.';

insert into Employee_Test_Audit


(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());

PRINT 'AFTER INSERT trigger fired.'


GO

insert into Employee_Test values('Chris',1500);

--SELECT * FROM Employee_Test


--SELECT * FROM Employee_Test_Audit

VIEWS

--Views
--A view is like window through which use can access the data from the table.
--Not: Restrict access to only specific rows in the table

--2 types views

--Simple view
--Complex view

--Simple view:
--Create the view on single table is called Simple view.

--Complex view:
--Create the view on morethan one table is called complex view.

--EX: Simple view:


--Create a view that provides access to only the employees working in dept 20

Create view Emp_View


as
select * from emp where dept=20

--Emp_View is the view name , we can give any name

--Once the view is created we can use it like a table and perform
--select ,
--insert ,
--update and
--delete same as on a table

--view doesn't contain any data it contain only select command

insert into Emp_View


values(102,'venkat','sw',12,'2017-04-19',20000,250,10,10)

--drop view Emp_View

--Complex view: view is created from multiple tables using joins.

create view Emp_View1


as
select a.ename,a.job,a.sal,b.dname
from emp a inner join Dept b
on a.dept=b.did

select * from Emp_View1

--Note:By default column names in the view are same as column names in the view
--If you want to different names in the view we can write like below

create view view_name(Ename,Job,Salary,Dname)


as
select a.ename,a.job,a.sal,b.dname
from emp a inner join Dept b
on a.dept=b.did

--Schema binding: When the view is created with schema binding option ,then
--it will not be possible to alter the view until the view is deleted.

create view emp_viw2


with schemabinding
as
select ename,job from dbo.Emp

--Note:Here table schema name should be call dbo.

alter table emp alter column ename nvarchar(20)

--The above command is not execute because the view is created with schemabinding
--We can't change the main table schema untill you drop the schemabinding
--Noote: * is not allowed in view with schemabinding

--IMP: Can't create index on view because the view is not a schemabinding

--Getting source code of view:


sp_helptext 'view_name'

Вам также может понравиться