Sie sind auf Seite 1von 14

DDL - Data Definition language

CREATE - Used to create DataBase, Tables,


StoredProcedures, Functions ....
To Create a DataBase
-------------------------Syn :- Create Database DatabaseName
Create Database db1
Default Location for SQL Server Databases.
-------------------------------------------C:\Program Files\Microsoft SQL Server\
MSSQL10_50.MSSQLSERVER\MSSQL\DATA
To Create Table
---------------Create Table TableName(Colname1 Datatype(Size),
colname2 Datatype(Size),.....)
Ex:CREATE TABLE Product
(PID INT, PNAME VARCHAR(70), Price int )
CREATE SCHEMA SALES
CREATE TABLE Sales.NewProduct1
(PID INT, PNAME VARCHAR(70), Price int )
create table PEmployee(
Eno int identity(1,1), Ename varchar(50))

ALTER - Used to Modify Tables,


StoredProcedures, Functions ....
to Add a new Column
Alter Table TableName add Colname DataType(Size)
Ex:
alter table Employee add Gender char(5)
to change the datatype of an existing column
ALter Table Tablename alter column Colname Datatype(size)
Ex:
alter table Employee alter column Gender int

to Remove a column from a table


Syn : alter table TableName Drop column Colname
ex: alter table Employee drop column Mangid

DROP

- Used to Parmanently remove DataBase, Tables,

StoredProcedures, Functions ....


Drop Table Tablename

Data Integrity
====================
Ensuring The Accuracy of data in the dataBase
DomainIntegrity EntityIntegrity ReferentialInterity
Integrity can be implemented at DB Level by Using Constraints
* A constraint will Enforces the Business Rules on the data,
Constraints
NOT NULL
- Will never Allows NULL Values
Ex : create table PEmployee(
Eno int NOT NULL , Ename varchar(50))
UNIQUE
- Will not allow Duplicate values
- Can aloow one NULL Value..
create table PEmployee(
Eno int UNIQUE , Ename varchar(50)
)
PRIMARYKEY = NOT NULL + UNIQUE
* Implements Entity Integrity
Will not allows Null Values and Duplicate values
Ex:
Create Table PEmployee(
Empno int Constraint PK Primary key ,
EmpName varchar(50),
Sal int)

FOREIGN KEY
* Referantial Integrity
* References Parent table , Allows values into
ChildTable only when the value is
present in the parent table
* On Delete Cascade, On Delete No Action
On Delete set null
* The column refered in the parent table
e a Primary key column
Ex:
Create Table PEmployee(
eno int,
ename varchar(50),
deptid int ,
Constraint fk foreign key(deptid)
references Department(DeptID)

should b

CHECK
* Domain Integrity
Create Table WEmp(
eno int ,
ename varchar(50),
sal int, constraint ck check(sal >=1500)
)

DML
INSERT

to Perform Bulk Insert Operation


--------------------------------1) Create a text file in c drive
2)add following data into the text file
110,Ravi,10,1; 111,Rajesh,10,1; 112,Rasi,10,1;
3)in Sql Command Prompt
Bulk insert db1.dbo.Employee
From 'c:\Data\Mydata.txt'
With(DATAFILETYPE='char',
FIELDTERMINATOR=',',ROWTERMINATOR=';')

Copy Data from another table


* Empbackup table should be created .
ex: insert into empbackup select * from employee
UPDATE
to Update the data in the table
Update tableName set colname = value where Condition
* if where condition not used , all the rows in the table will get updated..

DELETE
delete from empbackup where empno =108

DRL
SELECT
DCL
GRANT
REVOKE
vIEW
==========
view is a VIRTUAL TABLE , Refers to the data of a table.
*
*
*
*

view does not contain any data


used to show appropriate data only
DML Operations on View will refelect on the original table
Insert , Update , Delete Operations are not recommended on a view as the view
is having columns from more than one table.

* while creating views , should not use


* Order by clause, unless there is also a top clause
* Include the into keyword
* Include compute or compute by clauses
* Reference a temporary table or a table variable
* cannot associate after triggers with views, only
of triggers.

Syn : create view viewName


as
Select Statement
ex:
create VIEW vw_Joinemp
as
select e.Empno ,e.EmpName ,d.DeptName
from employee e
join Department d
on e.DeptID = d.DeptID
select * from vw_JoinEmp
Partioned View
====================
Retrives the data from More than one server.
Joins the data Horizontally
create
as
select
select
select

view vw_TotEmp
* from Cust_table1 union all
* from server2.db1.Cust_table2 union all
* from server3.db3.Cust_atble3

instead

Index
==============
Index is used to increase the performance of a query.
Can create index on a column which is frequently querying
1) Clustered Index
* Automatically Sorts the data
* Internally Binary tree will be formed
* one Clusterd Index is allowed per table
* Will be created automatically when primary key is created
* if no primary key , we can create manually
Syn : - Create clustered index indexName on Tablename(Colname)
create Clustered index indx on STudent(sno)
* not suitable for Frequently Updated column

2) non Clustered Index


* can have 999 NCIndexs on a table
* Works as Preface Index on textBook
Create Create clusterd index indexName on Tablename(Colname)
3) Unique Non Clustered
* Will not allows duplicate values
* can be applied on more than one column
Create unique non clusterd index indexName on Tablename(Colname1, colname2)

Declaring Variable
---------------------declare @varname dataype
Ex : declare @a int
declare @c int ;
select @c = COUNT(*) from Orders where CustID = 101
declare @r int
set @r = 5-@c
print @r
Constructs at Sql Server
==============================

* IF ELSE
* CASE
* WHILE
IF ELSE - used to evaluate a conditon and perform either
True Stmts or False Stmts
Syn : if Condition
True stmts
else
false stmts
Ex :
declare @c int ;
select @c = COUNT(*) from Orders where CustID = 101
declare @r int
set @r = 5-@c
if @r > 0
print 'Can Place Orders...'
else
print 'Can not place orders ...'

CASE : -------------To Execute only one option when there are many options
Syn :
CASE ExprissionValue
When val1 then
stmts
when val2 then
stmts
Esle
stmts
End
select Empno , empname ,
case Gender
when 1 then 'M'
when 2 then 'F'
else 'NA'
end
as 'Gender'
from Employee

WHILE Construct :
---------------------Used to repeat a set of stmts for no.of times
Syn :

While (Condtion)
Begin
STmts
Stmts
stmts
End

Ex :
while ((Select AVG(SAL) from Employee) < 3000)
Begin
update Employee set Sal = SAL+1
end
Batch : --------------A single group of stmts sent to the server
* Use Go Keyword
* If any compilation error , no Stmt will be processed
* if any Runtime Error , All stmts before that err stmt will got executed , and
the remaining will be blocked
syn :
stmt1
stmt2
stmt n
go

Storeprocedures
-----------------its a DBO , Which contains preCompiled Sql Stmts.
Adv :
Share application logic
Shield database schema details
Provide security mechanisms
Improve performance
Reduce network traffic
Syn :
Create Procedure ProcedureName Parameters
as
Begin
stmts
stmts
stmts

end
to Execute a stored Procedure
Syn : Exec ProcedureName ParamValues

Ex :
create procedure prc_GetEmpDept
as
begin
select e.EMpno , e.EMpname, d.deptname
from Employee e join Department d
on e.DeptID = d.DeptID
end
to Execute the procedure : exec prc_GetEmpDept

to Drop a procedure
---------------------drop procedure ProcedureName
Parameters to StoredProcedure
-----------------------------Create Procedure ProcedureName @varname Datatype(Size), ...
as
begin
----------------end
Create procedure pr_GetEmpByNum @num int
as
begin
select * from employee where empno = @num
end

exec pr_GetEmpByNum 106


to alter the procedure Body
---------------------------------alter procedure pr_GetEmpByNum @name varchar(50)
as
begin
select * from employee where empname = @name
end

exec pr_GetEmpByNum 'Haritha'

To return values from a procedure


-------------------------------------* use Output Keyword in the parameters list , as well as while Executing the Pro
cedure
* should use return keyword in the body of procedure

create procedure PrcdrName @var1 type , @var2 type output


as
begin
sql stmts
return 0
end
Ex :
Create procedure pr_getOrders @num int , @c int output
as
begin
select @c = COUNT(*) from orders where custid = @num
return
end
to execute Procedure
declare @n int
exec pr_getOrders 101 , @n output
print @n
exec sp_helptext prc_GetEmpDept - Will gives the code of the
Procedure.

User Defined FUnctions


=============================
*can not work with DDL oprns
* Limited Scope
* Can be used directly with select statement
1) Scalar 2) TableValued
Scalar UDF
Syn

- which can have only one param and one

return value

Create function Functioname @varname type


returns type
as
begin
------------------return @var
end

Ex :
create function fn_getDiscount (@stid int )
returns float
as begin
declare @d float
select @d = discount from Discounts where stor_id = @stid
return @d
end
to call the function
select dbo.fn_getDiscount(7066)
declare @m float
set @m = dbo.fn_getDiscount(7066)
print @m

Inline Table-Valued Function


-----------------------------* returns a table or Multiple Rows
* can not contain Begin and End stmts

create function fn_GetDisc( @d float )


returns table
as
return (
select * from discounts where discount > @d)
execute the function
select * from pubs.dbo.fn_GetDisc(10)

Multi StatementTableValuedFunction
------------------------------------* Returns table type
* the table can be from multiple statements in side the body
* begin and End should be there
* need to specify the structure of the return table
Create Function fn_multv(@d float)
returns @t table(StoreID int , Discount float)

as
begin
insert @t
select stor_id, Discount from discounts where discount > @d
return
end
to Execute the Function
-------------------------select * from dbo.fn_multv(4)

Cursor
-------------To iterate among the records in a result set
Can do modification on the temprory Result set which will not reflect on the ori
ginal Table
* The keywords COMPUTE, COMPUTE BY, FOR BROWSE, and INTO are
in select statement
of a cursor declaration.
to Implement Cursors
---------------------Declare Cursor
Open Cursor
Fetch the records into cursor
Perform Stmts
Close Cursor
Deallocate Cursor

Static Cursor - Result set will be placed into TempDB

to Declare a cursor
------------------declare cursorname CURSOR
FOR - to specify the Command for the result set
Fetch - Fetch the records into the curosr
fetch_status

- indicates whether a row is fetched or not


into the cursor
Returns an integer

not allowed with

to Open Cursor
----------------Open CursorName
to Close the cursor
-------------------Close CursorNAme
to Dealloacte Cursor
-----------------------Deallocate CursorName

Example to iterate on Employee Names fromEmployee table


ex:
Declare @nm varchar(30)
Declare cur cursor
for
select empname from employee
open cur
Fetch next from cur into @nm
while @@FETCH_STATUS =0
begin
Update Employee set Empname = upper(@nm) where current of cur
Fetch next from cur into @nm
end
close cur

Update using Cursor


------------------------Declare cur Cursor
for
select empname From Employee
for Update of Empname
Open Cur
Fetch next from cur
while @@FETCH_STATUS = 0
begin
Update Employee set empname = upper(empname) where CURRENT of
Cur
Fetch next from cur
end
Close cur
Deallocate cur

Stored Procedures For Cursors


================================
Sp_cursor_list
Returns a list of cursors currently visible on

Sp_describe_cursor
Describes the attributes of a cursor, such as whether it is a forward-only or sc
rolling cursor
Sp_describe_cursor_columns
Describes the attributes of the columns in the cursor result set
Sp_describe_cursor_tables
Describes the base tables accessed by the cursor

Trigger
-----------is a special type of strored procedure
* will execute automatically when specified Event occured
Syn :
Create trigger trgName on Tablename
after/for/instead of SqlCommand
as
begin
Sql Stmts
sql stmts
End

Update trigger
-------------create trigger trg_update on Employee
for update
as
begin
select * from deleted
select * from inserted
end

Delete Instead of trigger


--------------------------create trigger trg_delete on employee
instead of delete
as
begin
print 'Deletion Cannt be Done....'
end
to enable a trigger
--------------------alter table tablename enable trigger trgName
ex :

alter table employee enable trigger trg_delete

to disable trigger
----------------------alter table tablename disable trigger trgName
ex :
alter table employee disable trigger trg_delete

Referentail trigger Ex
------------------------create trigger trg_refdelete on department
for delete
as
begin
declare @n int
select @n = deptid from deleted
delete from employee where deptid = @n
end

to Drop trigger
------------------drop trigger trg_refdelete

Das könnte Ihnen auch gefallen