You are on page 1of 194

Chng 1 :GII THIU TNG QUAN V SQL SERVER I.

Tng quan :
1.SQL SerVer la mt h qun tr CSDL quan h
A. C S D Liu Quan H : D liu c t chc lu tr thanh tng bng Mt bng dng lu tr thong tin ca mt i tng ngoai th gii thc Mt bng c to t dong va ct

I. Tng Quan : (tt)


Ct :Dung lu tr thuc tnh ca i tng Mt bng phi co toi thiu mt ct,Th t ct khng quan trng Mt cot co ba thuc tnh c bn Column Name :Ten ct,trong mt bng khong th co hai cot trung ten Data Type :Kiu d liu Length :chiu dai ca d liu

I:Tng Quan(tt)
Dong :tp hp d liu ca nhiu ct Trong mt bng khong the co hai dong trung thong tin Mot dong cho biet thong tin cu the cua mot oi tng lu tr trong bang Mt bng co th khong co dong nao

I.Tng Quan (tt)


Khoa ngoi (Foreign Key) : Tp hp ca mt hay nhiu ct trong bng,ma cac cot nay la khoa chnh ca bng khac D liu ti cac ct nay hoc rng,hoc phi ly t bng ma ct lam khoa chnh

I.Tng Quan(tt)
Khoa Chnh (Primary Key) : Tp hp ca mt hay nhiu ct trong bng D liu ti ct nay khac rng D liu ti ct nay la duy nht trong bng

I.Tng Quan(tt)
B.H Qun Tr CSDL Quan H : La mt h thng cac chng trnh co cac chc nng To va qun ly mt CSDL Quan h khai thac Mt CSDL Quan h Bo mt Mt CSDL Quan h To bng sao (Backup) Mt CSDL Quan h Phc Mt CSDL SQL Server hI(Restore) qun tr Quan h la mt h CSDL Quan h

Cac he thong SQL Server


He

Thong SQL Server co the trien khai cho mot he thong kieu ClientServer hoac trien khai cho mot he thong may n He thong c trien khai phu thuoc vao so ngi truy cap ong thi en CSDL e thc hien mot cong viec

Cac he thong SQL Server


Trong

mo hnh Client-Server ta co the trien khai theo mo hnh 2 lp hoac 3 lp

Cac he thong SQL Server

II.Cai t SQL Server


A.Yeu cu phn cng :

Phn cng CPU RAM a cng Mn hnh

Yu cu T Pentium III tc 600MHz tr ln T 512 MB tr ln Cn trng 1GB tr ln VGA c phn gii 1,024x768 tr ln

II.Cai t SQL Server


A.Yeu cu phn Mm:

Ten phan mem


Trnh duyt Internet

phien ban Microsoft Internet Explorer 6.0 SP1 tr ln IIS 5.0 tr ln

Internet Information Services

Microsoft Windows .NET Framework 2.0

II.Cai t SQL Server


A.Yeu cu phn Mm:

Phien ban SQL Server


SQL Server

H ieu hanh

2005 Enterprise Edition 4 Microsoft Windows SQL Server 2005 Developer Edition Server(nt,2000,Xp Server) SQL Server 2005 Standard Edition

SQL Server 2005 Workgroup Edition

II.Cai t SQL Server


A.Yeu cu phn Mm:

Phien ban SQL Server


SQL Server

2005 Enterprise Edition 4 SQL Server 2005 Developer Edition SQL Server 2005 Standard Edition SQL Server 2005 Workgroup Edition SQL Server 2005 Express Edition

II.Cai t SQL Server


A.Yeu cu phn Mm:

H iu hnh
Windows 2000 Windows 2000 Professional Edition Windows 2000 Server SP4

Phn mm SQL Server


Enterprise Developer Edition Edition Khng Khng Khng c Standard Workgroup Express Edition Edition Edition Khng C Khng c Khng C Evaluation Edition Khng c

II.Cai t SQL Server


A.Yeu cu phn Mm:

H iu hnh

Phn mm SQL Server


Enterprise Developer Edition Edition c Standard Workgroup Express Edition Edition Edition Khng Khng c Evaluation Edition Khng

Windows XP Khng Home Edition SP2 Windows XP Professional Edition SP2 Windows 2003 Server SP1 Khng

II.Cai t SQL Server


A.Yeu cu phn Mm:

Phien ban SQL Server


SQL Server

2005 Enterprise Edition 4 SQL Server 2005 Developer Edition SQL Server 2005 Standard Edition SQL Server 2005 Workgroup Edition SQL Server 2005 Express Edition

1. a a CD chng trnh vao ,man hnh sau xuat hien

II. Cai t Developer SQL Server

Chon

2.Man hnh sau xuat hien

II.Cai at Personal Edition SQL Server(tt)

Chn

Chn

II.Cai at Personal Edition SQL Server(tt)


3.Man hnh sau xuat hien

Chn

4.Man hnh sau xuat hien

II.Cai at Personal Edition SQL Server(tt)

Chn

II.Cai at Personal Edition SQL Server(tt)


5.Man hnh sau xuat hien

Chn

II.Cai at Personal Edition SQL Server(tt)


6.Man hnh sau xuat hien
Chn tt c cc la chn Nhn nt Advanced chn ci t cc CSDL mu

II.Cai at Personal Edition SQL Server(tt)

Chn

Chn

II.Cai at Personal Edition SQL Server(tt)


Chn

II.Cai at Personal Edition SQL Server(tt)

Chn

Chn

II.Cai at Personal Edition SQL Server(tt)


Chn

II.Cai at Personal Edition SQL Server(tt)

Chn

II.Cai at Personal Edition SQL Server(tt)

Chn

II.Cai at Personal Edition SQL Server(tt)

III.Cac tien ch cua SQL Server


1.Tien ch SQL Server Management Studio :Man hnh quan ly cac oi tng co trong SQL Server 2005

KHI ONG : START -> PROGRAMS-> MICROSOFT SQL SERVER 2005-> SQL SERVER MANAGEMENT

III.Cac tien ch cua SQL Server


Chc nng ca SQL Server Management Studio To,sa, xoa mot CSDL va cac oi tng trong CSDL Quan ly cac lch lam viec Hien th cac thong tin cua phien lam viec hien tai nh : ngi ang ang nhap,oi tng nao ang b khoa Quan ly bao mat cho he thong Khi tao va quan ly Database

III.Cac tien ch cua SQL Server


Chc nng ca SQL Server Management Studio Tao va quan ly t ien tra cu d lieu Quan ly cau hnh he thong Tao va quan ly cac d lieu tao bao cao

Khi ong tien ch SQL Server Management


Studio KHI ONG : START -> PROGRAMS-> MICROSOFT SQL SERVER 2005-> SQL SERVER MANAGEMENT STUDIO

Xuat hien man hnh Server type :Chon loai server e ket noi Server name : chon server ket noi Authentication : chon loai ang nhap theo Windows

III.Cac tien ch cua SQL Server


2>TIEN CH QUERY editor : dung xay dng
cac cau lenh T-SQL truy cap d lieu Click chuot vao nut New Query Hoac File ->New->New Query With Current Connection Khi ong :

III.Cac tien ch cua SQL Server


Chu y : muon xay dng cau truy van cho CSDL nao ta phai chon CSDL o trc khi tao mot query

III.Cac tien ch cua SQL Server


Chon cac che o hien th ket qua cua cau truy van

Chon

Ket qua

III.Cac tien ch cua SQL Server


Chon cac che o hien th ket qua cua cau truy van

Cho n

Ket qua

III.Cac tien ch cua SQL Server


Chon cac che o hien th ket qua cua cau truy van

Cho n

III.Cac tien ch cua SQL Server


3>Books Online : phan tr giup cua SQL 3> SerVer KHI ONG : START -> PROGRAMS-> MICROSOFT
SQL SERVER 2005-> DOCUMENTION AND TUTORIALS>SQL SERVER BOOK ONLINE

III.Cac tien ch cua SQL Server


SQL SERVER 2005-> CONFIGURATION-> SERVER CONFIGURATION MANAGER

4>The SQL Server Configuration Manager : cau hnh he thong ONG : START -> PROGRAMS-> MICROSOFT KHI

III.Cac tien ch cua SQL Server


5>SQL Server Business Intelligence Development Studio : tien ch
lap trnh tren SQL Server 2005: cung cap cac tien ch cho phep xay dng cac Services packages, thiet ke report. Khi ong SQL Server Business Intelligence Development Studio : Start -> programs ->Microsoft SQL Server 2005 -> 5>SQL Server 5> Business Intelligence Development Studio

III.Cac tien ch cua SQL Server


6> Tien ch : Performance Monitor : cho biet tnh trang s dung tai nguyen cua may chu trong khi SQL SerVer hoat ong Khi ong :

III.Cac tien ch cua SQL Server


Xuat hien man hnh

III.Cac tien ch cua SQL Server


7>Tien ch Profiler :lu vet cac x ly tren Server Khi ong :

III.Cac tien ch cua SQL Server


Ket noi vao Server

III.Cac tien ch cua SQL Server


at ten cho tap tin lu vet

Chng II: Xay dng mot CSDL trong SQL Server


Mt (CSDL) ca SQL Server l tp hp cc i tng bng (Table):Cha d liu bng o (View):cha d liu ly t Bng th tc ni ti (Stored Procedure): Cha cc lnh thao tc vi D liu Hm (Function) :Ging ttnt nhng tr v gi tr

Chng II: Xay dng mot CSDL trong SQL Server


Trigger :Cha cc lnh thao tc vi D liu,kim tra rng buc t ng Constraint :Cha cc rng buc d liu Mt CSDL do mt hoc nhiu ngi to nhng c th c nhiu ngi truy cp Trong SQL Server c th to c 32767 CSDL khc nhau

Chng II: Xay dng mot CSDL trong SQL Server


Cu trc lu tr ca mt CSDL : Mt CSDL trong SQL Server ti thiu s dng hai tp tin vt l lu tr d liu: Mt dng lu tr d liu (Data file) Mt dng lu tr cc vt giao tc (Transaction log file)

Chng II: Xay dng mot CSDL trong SQL Server


Thng c t chc lu tr trong 3 tp tin :
CSDL

Data Files Primary DataFile (*.MDF) Secondary Data Fie (*.NDF)

Log Files Log file (*.LDF)

Chng II: Xay dng mot CSDL trong SQL Server


To mi mt CSDL trong SQL Server Cch 1: S dng tin ch Management Stdio :Click chut phi vo i tng Databases chn New Database

Chng II: Xay dng mot CSDL trong SQL Server


Xut hin hp thoi

Nhp vo tn CSDL

Chng II: Xay dng mot CSDL trong SQL Server

Database Files: Logicalname :Tn tp tin Data Files Path: V tr lu tr Initial size(Mb) :Kch thc ban u Automatically grow file: T ng tng kch thc In megabytes : tng bao nhiu mB By percent :Tng theo phn trm Maximun file size : kch thc ti a ca CSDL Unrestricted file growth :Khng gii hn kch thc Restrict file growth(MB) :gii hn Tng t cho Transaction Log

Chng II: Xay dng mot CSDL trong SQL Server


To csdl bng lnh : CREATE DATABASE Accounting ON (NAME = Accounting, FILENAME = c:\Program Files\Microsoft SQL Server\ MSSQL.1\mssql\data\AccountingData.mdf, SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5)

Chng II: Xay dng mot CSDL trong SQL Server


LOG ON (NAME = AccountingLog, FILENAME = c:\Program Files\Microsoft SQL Server\ MSSQL.1\mssql\data\AccountingLog.ldf, SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB) GO

Chng II: Xay dng mot CSDL trong SQL Server

Cc kiu d liu trong SQL Server


Kiu d liu Kch thc 4 bytes 2 bytes 1 byte 1 byte Min gi tr d liu lu tr

> Cc kiu d liu dng s nguyn Int SmallInt TinyInt Bit Decimal, Numeric Float Real t-2,147,483,648n +2,147,483,647 t -32768 n +32767 t 0 n 255 0, 1 hoc Null

> Cc kiu d liu dng s thp phn 17bytes t -10^38 n +10^38

> Cc kiu d liu dng s thc 8 bytes 4 bytes t -1.79E+308 n +1.79E+308 t -3.40E+38 n +3.40E+38

Chng II: Xay dng mot CSDL trong SQL Server


> Cc kiu d liu dng chui c di c nh Char N bytes t 1 n 8000 k t, mi k t l mt byte( char(n)) t 1 n 8000 k t, mi k t l 1 byte t 1 n 2,147,483,647 k t, mi k t l 1 byte > Cc kiu d liu dng chui c di bin i VarChar Text N bytes N bytes

> Cc kiu d liu dng chui dng font ch Unicode NChar 2*N bytes t 1 n 4000 k t, mi k t l 2 bytes

NVarChar 2*N bytes t 1 n 4000 k t, mi k t l 2 bytes NText 2*N bytes t 1 n 1,073,741,823 k t, mi k t l 2 bytes

Chng II: Xay dng mot CSDL trong SQL Server


> Cc kiu d liu dng tin t Money SmallMoney 8 bytes 4 bytes t -922,337,203,685,477.5808 +922,337,203,685,477.5807 n t -214,748.3648 n + 214,748.3647

> Cc kiu d liu dng ngy v gi DateTime SmallDateTime 8 bytes 4 bytes t01/01/1753n31/12/9999 t01/01/1900n06/06/2079

> Cc kiu d liu dng chui nh phn (Binary String) Binary VarBinary Image N bytes N bytes N bytes t 1 n 8000 bytes t 1 n 8000 bytes t 1 bytes n 2,147,483,647

Chng II: Xay dng mot CSDL trong SQL Server


To bng Cc thuc tnh c

bn ca Mt Bng

Tn bng (Table Name) di<= 128 k t. Tn bng

phi duy nht bn trong phm vi ca ngi to ra n trong mt CSDL

Tn ct (Column Name): l tn ca cc ct bn trong bng,

tn ca cc ct bn trong bng phi duy nht.

Kiu d liu (Data Type):qui nh kiu d liu m ct s

lu tr bn trong bng.

Chng II: Xay dng mot CSDL trong SQL Server


di d liu (Data Length): dng qui nh

di d liu m ct s lu tr i vi cc kiu d liu dng chui.

S k s lu tr (Precision): l s k s ti a m

cc kiu d liu dng s c th lu tr c.

S l lu tr (Scale): l s l ti a m cc kiu d

liu dng s thp phn dng lu tr.

Chng II: Xay dng mot CSDL trong SQL Server


Ct nh danh (Identity): Gi tr ca ct nh

danh l s nguyn khng trng lp do h thng Microsoft SQL Server t ng cp pht. Cc kiu d liu ca ct nh danh : Int, SmallInt, TinyInt, Decimal , Numeric Thuc tnh Identity Seed :S u tin Thuc tnh Identity Increment :gi tr tng Mt bng ch c c mt ct c thuc tnh Identity

Chng II: Xay dng mot CSDL trong SQL Server


Cho php trng d liu (Allow

Null): qui nh d liu c th c php trng hay l phi nhp Gi tr mc nh (Default Value): l gi tr mc nhin s c gn vo ct d liu khi ngi s dng thm mi mt mu tin nhng li trng gi tr ti ct d liu .

Chng II: Xay dng mot CSDL trong SQL Server


To Bng trong Sql

Server

Cch 1: S dng tin ch

Management Studio

M CSDL Click chut phi trn i tng Tables, chn chc nng New Table... trong thc n tt.

Chng II: Xay dng mot CSDL trong SQL Server

Mn hnh sau xut hin :


Column Name :Nhp tn Ct Data Type : chn kiu d liu Allow Nulls : d liu ca ct c c rng hay khng

Chng II: Xay dng mot CSDL trong SQL Server

Trong hp thoi Column Properties : Default Value or Binding :gi tr mt nh ca ct Identity Specification : d liu ca ct c t tng ? Is Identity : t tng Identity Increment : gi tr bt u Identity Seed : gi tr tng

To bng bng lnh trong mn hnh Query Edittor

Chng II: Xay dng mot CSDL trong SQL Server


To cu trc bng n gin C php: CREATE TABLE Tn_bng ( Tn_ct_1 Kiu_d_liu [NOT NULL] , Tn_ct_2 Kiu_d_liu [NOT NULL] [ , ...] ) Trong : + Tn bng, tn ct v kiu d liu c m t trn + T kha NOT NULL ch nh khng cho php d liu ti ct c php b trng.

To cu trc bng c gi tr mc nh C php: CREATE TABLE Tn_bng ( Tn_ct_1 Kiu_d_liu DEFAULT Gi_tr|Hm , Tn_ct_2 Kiu_d_liu [NOT NULL] [ ,...] ) Trong : + Gi tr: l gi tr c th s c gn vo ct. + Hm: l tn hm cng vi cc tham s (nu c), tuy nhin kiu d liu m hm tr v phi l cng vi kiu d liu m ct s lu tr.

Chng II: Xay dng mot CSDL trong SQL Server

Chng II: Xay dng mot CSDL trong SQL Server

To bng bng lnh trong mn hnh Query Elyzer


V d 1
CREATE TABLE VATTU ( MAVTU CHAR(4) NOT NULL, TENVTU VARCHAR(100) NOT NULL, DVTINH VARCHAR(10) NOT NULL, PHANTRAM REAL DEFAULT 20 )

V d 2
CREATE TABLE DONDH ( SODH CHAR(4) NOT NULL, NGAYDH DATETIME DEFAULT GETDATE(), MANHACC CHAR(3) NOT NULL )

Chng II: Xay dng mot CSDL trong SQL Server

To cu trc bng c ct nh danh


C php: CREATE TABLE Tn_bng ( Tn_ct_1 Kiu_d_liu_s IDENTITY [(S_bt_u, Ch_s_tng)] , Tn_ct_2 Kiu_d_liu [NOT NULL] [ ,...] ) Trong mt bng ch c ti a mt ct c ch nh lm ct nh danh S bt u: l s m SQL Server s dng cp pht cho mu tin u tin. Mc nh l 1. Ch s tng: l ch s m SQL Server cng ln cp pht cho tng mu tin kt tip. Mc nh l 1.

Chng II: Xay dng mot CSDL trong SQL Server


Tnh ton vn d liu trong c s d liu : cc rng buc trong SQL Server c qun l bI hai I tng :CONSTRAINT v TRIGGER Constraint : qun l cc rng buc nh : Rng buc d liu duy nht Rng buc d liu tn ti Rng buc min gi tr Trigger :Qun l cc rng buc phc tp,lin quan n d liu trn nhiu bng

Chng II: Xay dng mot CSDL trong SQL Server


Xy dng cc Constraint A>Kim tra

duy nht d liu :c hai loi Primary Key (kho chnh ) :d liu khc rng v duy nht

Unique : d liu c th rng v d liu tn ti duy nht

Chng II: Xay dng mot CSDL trong SQL Server


nh ngha rng buc kho chnh :

[CONSTRAINT PK_Tn_bng_TenCot ] PRIMARY KEY (Danh_sch_ct_kha_chnh)

Chng II: Xay dng mot CSDL trong SQL Server


nh ngha ct c gi tr tnh ton t cc ct khc Ten_cot as BieuThuc

Chng II: Xay dng mot CSDL trong SQL Server


nh ngha rng buc d liu duy nht :

[CONSTRAINT UQ_Tn_bng_Tn_ct] UNIQUE (Danh_sch_cc_ct)

Trong mt bng ch nh ngha mt rng buc kho chnh nhng c th nh ngha nhiu rng buc d liu duy nht

Chng II: Xay dng mot CSDL trong SQL Server


V d : CREATE TABLE VATTU ( MAVTU varchar(4) not null, TenVtu varchar(100), Constraint PK_Vattu_Mavtu primary key(Mavtu), constraint UQ_Vattu_tenvtu unique(tenvtu) )

Chng II: Xay dng mot CSDL trong SQL Server


B>Kim tra tn ti D liu :nh ngha kho ngoi

[CONSTRAINT FK_Tn_bng_Tn_ct] FOREIGN KEY (Danh_sch_ct_kha_ngoi) REFERENCES Tn_bng_tham_chiu Trong mt bng c th nh ngha nhiu kho ngoi (Danh_sch_ct_tham_chiu)

Chng II: Xay dng mot CSDL trong SQL Server


B>V d :
CREATE TABLE CTHOADON ( SOHD Varchar(3) not null , MAVTU Varchar(3) not null, Soluong int, Dongia float, CONSTRAINT FK_CTHOADON_SOHD FOREIGN KEY (SOHD) REFERENCES HOADON(SOHD), CONSTRAINT FK_CTHOADON_MAVTU FOREIGN KEY (MAVTU) REFERENCES VATTU(MAVTU) )

Chng II: Xay dng mot CSDL trong SQL Server


C>Kim tra rng buc min gi tr : C php :

[CONSTRAINT CK_Tn_bng_Tn_ct] CHECK (Biu_thc_lun_l)

Chng II: Xay dng mot CSDL trong SQL Server


B>V d :

CREATE TABLE CTHOADON ( SOHD Varchar(3) not null , MAVTU Varchar(3) not null, Soluong int, Dongia float, CONSTRAINT CK_CTHOADON_SOLUONG CHECK (Soluong>0), CONSTRAINT

Chng II: Xay dng mot CSDL trong SQL Server


d>Thm Costraint vo bng c C php chung: ALTER TABLE Tn_bng ADD [ CONSTRAINT Tn_Constraint ] LOI Cc_tham_s [ , ...]

Chng II: Xay dng mot CSDL trong SQL Server


C php chi tit tng loi constraint PRIMARY KEY ALTER TABLE Tn_bng ADD [ CONSTRAINT PK_Tn_bng ] PRIMARY KEY (Danh_sch_ct_kha_chnh)

Chng II: Xay dng mot CSDL trong SQL Server


UNIQUE ALTER TABLE Tn_bng ADD [ CONSTRAINT UQ_Tn_bng_Tn_ct ] UNIQUE (Danh_sch_cc_ct)

Chng II: Xay dng mot CSDL trong SQL Server


FOREIGN KEY ALTER TABLE Tn_bng ADD [ CONSTRAINT FK_Tn_bng_Tn_ct ] FOREIGN KEY (Danh_sch_ct_kha_ngoi) REFERENCES (Danh_sch_ct_tham_chiu) Tn_Bng

Chng II: Xay dng mot CSDL trong SQL Server


Kim tra min gi tr : ALTER TABLE Tn_bng ADD [ CONSTRAINT CK_Tn_bng_Tn_ct ] CHECK (Biu_thc_lun_l)

Chng II: Xay dng mot CSDL trong SQL Server


Thm gi tr mc nh : ALTER TABLE Tn_bng ADD [ CONSTRAINT DF_Tn_bng_Tn_ct ] DEFAULT Gi_tr_mc_nh FOR Tn_ct

Chng II: Xay dng mot CSDL trong SQL Server


Hy mt Constraint : ALTER TABLE Tn_bng DROP CONSTRAINT Tn_constraint [ , ...] Tt cc Constraint : ALTER TABLE Tn_bng NOCHECK CONSTRAINT ALL| Tn_constraint [ , ...] Bt cc Constraint : ALTER TABLE Tn_bng CHECK CONSTRAINT ALL| Tn_constraint [ , ...]

Chng II: Xay dng mot CSDL trong SQL Server


Xa cu trc bng DROP TABLE Danh_sch_tn_cc_bng Thay i cu trc bng a. Thm mt ct mi trong bng ALTER TABLE Tn_bng ADD Tn_ct Kiu_d_liu [ , ... ] b. Hy b ct hin c bn trong bng ALTER TABLE Tn_bng DROP COLUMN Tn_ct [ , ...]

Sa i kiu d liu ca ct

Chng II: Xay dng mot CSDL trong SQL Server


ALTER TABLE Tn_bng ALTER COLUMN Tn_ct Kiu_d_liu_mi

i tn ct

EXEC SP_Rename Tn_bng.Tn_ct ,Tn_mi,C OLUMN

i tn bng

Chng II: Xay dng mot CSDL trong SQL Server


EXEC sp_rename Tn_bng,Tn_mi

Ch :Mun thay i cu trc ca ct phi xo tt c cc Constraint lin quan

Chng II: Xay dng mot CSDL trong SQL Server


To m hnh quan h Diagram -Click chut phi vo i tng DiaGram trong CSDL -> New Diagram -> xut hin mn hnh 1( chn Next) -> Xut hin mn hnh 2 : chn cc bng to m hnh quan h -> nhn Next -> Ok

Chng II: Xay dng mot CSDL trong SQL Server


Trong m hnh quan h ny ta c th :
Xem Trang in : click chut phi vo m hnh chn view pages

break
Hin th chui tn cc rng but : click chut phi chn

Show relationships label


Hin th cc rng but min gi tr ca cc bng : click chut

phi vo bng chn Properties -> chn trang check constraint -> xem v sa cc rng but ny

BI 3: Bngo(view)
1>nh Ngha :
Bng o l mt i tng cha cu lnh Select ly d liu

T cc bng trong csdl - Khi truy cp vo CSDL ,ngi s dng khng phn bit c Bng o v Bng Tht - View gip ngi s dng d dng truy cp d liu, gip ngi qun tr bo mt CSDL 2> To View Create view Ten_view As Cu lnh Select

Cu trc cu lnh Select


2>Cu

trc cu lnh Select

Select[Ten_Bang.]Ten_Cot[,] From Ten_Bang1 <Lin kt > Ten_Bang2 Where <iu kin> Group by <cc ct gom nhm> HaVing <iu kin lc nhm> Order by [Ten_Bang.]Ten_cot [asc/desc,] Compute Hm thng k [By Ten_cot]

Cu trc cu lnh Select


Mnh Select :cha cc ct,cc hm mun hin th Nu ct tn ti trong hai bng trong mnh From ta phi ghi r :Tn_Bng.Tn_Ct Nu ly tt c cc ct trong bng : Ten_Bang.* Trong mnh Select ta c th dng cu trc lnh Case When iu kin 1 Then Gi tr 1 When iu kin 2 then Gi tr 2

Else Gi tri n End hin th d liu

Cu trc cu lnh Select


Mnh from : cho bit d liu trn cu truy vn c ly t cc bng no nu d liu ly t nhiu bng th cc bng ny phi c quan h vi nhau:

Cu trc cu lnh Select


Inner Bng 1 Left Right full

Join Bng 2 on Bng 1.tn ct= bng 2.tn ct

Nu hai bng lin kt vi nhau qua mnh inner join -> kt qu tr v l nhng dng ca hai bng c gi tr bng nhau ti ct lin kt Nu hai bng lin kt vi nhau qua mnh Left join(Right join) -> kt qu tr v l nhng dng ca hai bng c gi tr bng nhau ti ct lin kt v tr v nhng dng ca bng bn tri( bn phi) c d liu khng bng d liu ca ct lin kt trong bng kia Nu hai bng lin kt vi nhau qua mnh Full join -> kt qu tr v l nhng dng ca hai bng c gi tr bng nhau ti ct lin kt v cc dng d liu ca c hai bng khng bng nhau ti ct lin kt

Cu trc cu lnh Select


Mnh Where : mnh lc d liu tr v hoc gom nhm Nu c nhiu iu kin lc th cc iu kin ny phi kt vi nhau bng ton t and( v ) or(hoc) Trong mnh Where c th s dng cc ton t : Like tm chui gn ng +% Thay th 1 chui +_(Gch di) thay th 1 k t
Ton t BETWEEN Gt1 AND GT2

Mnh OrDer By : Mnh sp xp d liu C php Order by [Ten_bang.]Ten_Cot [asc/Desc] [,]

Cu trc cu lnh Select

Mnh Group by : mnh gom nhm d liu


Mnh ny phi c khi trong cu truy vn c s dng

hm thng k v trn mnh Select c ly cc gi tr khng s dng hm thng k C php : Group By Danh sch ct,Biu thc Vi Danh sch ct,Biu thc :c ly trn mnh Select khng s dng hm thng k, b qua cc nhn : as ten_nhan Cc Hm thng k: Sum(Ten_Cot) :tnh tng vi ct c kiu s Count(Ten_Cot/*) :tnh tng s dng AVG(Ten_Cot) :tnh gi tr trung bnh kiu s Max(Ten_cot) : gi tr ln nht Min(Ten_Cot) :gi tr nh nht)

Cu trc cu lnh Select

Mnh HaVing : mnh Lc nhm d liu


Mnh ny ch tn ti khi iu kin lc d liu c hm

thng k Ch : trong cu truy vn c hai mnh lc d liu l Where v having

Where :lc d liu to nhm ( c iu kin khng s dng hm thng k) Having :lc nhm( cc iu kin c thng k)

Cu trc cu lnh Select


Mnh OrDer By : Mnh sp xp d liu C php Order by [Ten_bang.]Ten_Cot [asc/Desc] [,] Mnh Compute /Compute .. By : l mnh to gi tr thng k cui kt qu hoc thng k theo ct C php Compute Hm thng k : to thng k cui kt qu Compute Hm thng k By [Ten_Bang.]Ten_cot :thng k theo ct,d liu phi c sp xp theo ct ny Ch : Trong View khng c mnh ny

Cu trc cu lnh Select


Cc ton t dng trn mnh Select

C php : Select Ton t Vi cc ton t : Distinct: loi b cc dng d liu trng Top n : ly n dng u tin Top n with ties : ly nhng dng thuc n cp u tin theo gi tr ca ct c sp xp Top n PERCENT : ly N % s dng tr v

Ton

t UNION : dng ni kt qu ca hai cu truy vn thnh mt vi iu kin :


S ct tr v ca hai cu truy vn ging nhau Cc ct tng i mt phi cng kiu d liu

Cu trc cu lnh InSert into


Insert into : dng thm d liu vo bng,c 2 dng

Thm mt dng C php : Inser into Ten_bang(Ten_cot1,Ten_cot2[,]) Values(Gia_Tri1,) vi gi tr : kiu chui : nm trong hai du v d Trn thanh nht Kiu Ngy : yyyy-mm-dd v d :1982-02-29 Thm nhiu dng C php : Inser into Ten_bang_Dich(Ten_cot1,Ten_cot2[, ])

Select Ten_bang_nguon.ten_cot,giatri,bieuthuc from

Cu trcnht d liu ca mt bng cu lnh UpDate UpDate : dng cp


D liu Update ch trn mt Bng : C php : UpDate Ten_Bang Set Ten_Cot= Gi tr/Biu thc [Where iu kin] D liu Update trn nhiu Bng : C php : UpDate Ten_Bang Set Ten_Cot= Gi tr/Biu thc From [Where iu kin] Ch : gi tr cp nht khng c dng hm thng k

Cu trcnht d liu ca mt bng cu lnh UpDate UpDate : dng cp


D liu Update ch trn mt Bng : C php : UpDate Ten_Bang Set Ten_Cot= Gi tr/Biu thc [Where iu kin] D liu Update trn nhiu Bng : C php : UpDate Ten_Bang Set Ten_Cot= Gi tr/Biu thc From [Where iu kin] Ch : d liu cp nht c th l mt gi tr thng k tr v t cu truy vn con C th dng cu trc Case trong lnh cp nht Trong cu truy vn update khng s dng hm thng k

Cu trc cu lnh Delete


Delete : dng xa d liu ca mt bng

D liu xa ch trn mt Bng : C php : delete Ten_Bang [Where iu kin] D liu delete trn nhiu Bng : C php : delete Ten_Bang From [Where iu kin] Ch : khi xa d liu trn bng quan h 1 m d liu ny c bn bng quan h nhiu -> c li

Cu trc cu lnh Select .. into


Select .. into : dng to mt bng c cu trc v d liu ly t

cc bng c trong CSDL

C php : Select [Ten_Bang.]tenCot [,] Into Ten_Bang_Moi From ..

Cu truy vn Con (Sub Query)


Sub Query :l cu truy vn m kt qu tr v l iu

kin so snh,gn gi tr cho cu truy vn khc t im :


Ch tr v 1 ct d liu Nu tr v 1 dng : iu kin so snh gia cu truy vn chnh v cu truy vn con l cc ton t :=,>,<,<>,>=,<= Nu tr v nhiu dng : iu kin so sch : in (nm trong) hoc Not in(khng nm trong),>ALL,>=ALL( ln hn tt c)

Cu truy vn Con (Sub Query)


create view vw_DonDH_MAVTU_TONGSLNHAP as select dondh.sodh,ngaydh,vattu.mavtu,tenvtu,sldat,sum(slnhap) as tongsldn from (((dondh inner join ctdondh on dondh.sodh=ctdondh.sodh) inner join vattu on vattu.mavtu=ctdondh.mavtu) inner join ctpnhap on ctpnhap.mavtu=vattu.mavtu) inner join pnhap on pnhap.sopn=ctpnhap.sopn and pnhap.sodh=dondh.sodh group by dondh.sodh,ngaydh,vattu.mavtu,tenvtu,sldat --d liu tr v ch ly nhng CTDONDH c nhp hng

Cu truy vn Con (Sub Query)


Create view ten_view[(danh sach cot)] As cau lenh select

Cu truy vn Con (Sub Query)


-- nu ly tt c nhng CTDONDH create view vw_DonDH_MAVTU_TONGSLNHAP as select dondh.sodh,ngaydh,vattu.mavtu,tenvtu,sldat, (select sum(slnhap)from ctpnhap inner join pnhap on pnhap.sopn=ctpnhap.sopn where pnhap.sodh= dondh.sodh and ctpnhap.mavtu=vattu.mavtu) as tong_sl_Nhap from (dondh inner join ctdondh on dondh.sodh=ctdondh.sodh) inner join vattu on vattu.mavtu=ctdondh.mavtu

Cu truy vn Con (Sub Query)


create view vw_DonDH_TONGSLDat_Nhap as select sodh,sum(sldat) as tongsldat, (select isnull(sum(slnhap),0)from ctpnhap inner join pnhap on pnhap.sopn=ctpnhap.sopn where pnhap.sodh= ctdondh.sodh ) as tong_sl_Nhap from ctdondh group by sodh

Bi 4: Lp trnh vi SQL SerVer


I>Bin

v cc cu trc lnh trong SQL Server A>Bin :

1> Bin cc b : l bin do ngi lp trnh khai bo,Bin c th c khai bo trong th tc ni ti,hm, trong mt l lnh
L Lnh : l tp hp cc lnh c kt thc bng t

Go C php khai bo bin :

Declare @Tn_Bin Kiu_D_Liu


Tn Bin :Lun bt u bng k t @,khng c khong trng,k t t bit,k t s ng u

Bi 4: Lp trnh vi SQL SerVer


I>Bin

v cc cu trc lnh trong SQL Server Gn gi tr cho bin:

Gn bng 1 gi tr : Set @tn_bin=gitr/hm hoc Select @tn_bin=Gitr/hm Gn bng kt qu tr v ca cu truy vn Select @tn_Bin=Tnct/Hm ..from ..

Bi 4: Lp trnh vi SQL SerVer


2> Bin h thng : l bin do SQL Server cung cp,Cho bit trng

Tn Bin

thi ca h thng,Bin h thng lun bt u bng hai k t @@,Ch c Mt s cc bin thng dng

ngha

@@Error @@Rowcount @@Fetch_Status

Cho bit lnh trc c li hay khng,nu c li @@Error <>0 Cho bit s dng b tc ng bi cu truy vn gn nht Tr v <>0 nu lnh duyt CurSor gy li

Bi 4: Lp trnh vi SQL SerVer


B>Cc cu trc lnh 1>lnh iu khin IF .. Else C php :

If iu kin Begin <tp Lnh 1> end else Begin <tp Lnh 2> End Nu iu kin ng : tp Lnh 1 thc hin, ngc li tp lnh 2 thc hin Nu tp hp lnh 1 ,lnh 2 ch c 1 lnh th khng cn Begin .. End

Bi 4: Lp trnh vi SQL SerVer


2>Cu trc lp :While

While Biu thc iu kin Begin <Tp lnh> end Tp lnh s c thc hin n khi biu thc iu kin tr v False -c th dng lnh Break thot khi vng lp

Bi 4: Lp trnh vi SQL SerVer


3>Cc hm c bn trong SQL SerVer A>Cc hm chuyn i kiu d liu :thng dng chuyn d liu t s,ngy sang chui Trong SQL Server ta th ni cc kiu d liu nh chui, ngy, s li vi nhau, mun ni ta phi chuyn tt c thnh kiu chui Hm Cast : chuyn mt kiu d liu sang kiu bt k C php :Cast(Biu_Thc as Kiu_D Liu) V d : Cast (@tong as varchar(10)) Hm CONVERT : chuyn t ngy chui C php :Convert(Kiu_d_Liu,Biu_Thc[,nh_Dng]) V d : Convert(char(10),Getdate(),105)

Bi 4: Lp trnh vi SQL SerVer


Mt s nh dng thng dng

nh dng nm(YY) nh dng nm(YYYY)Hin th d liu 1 3 5 12 21 101 103 105 112 121 Mm/dd/yyyy Dd/mm/yyyy Dd-mm-yyyy Yyyymmdd Yyyy-mm-dd

Bi 4: Lp trnh vi SQL SerVer


Hm Str :chuyn s thnh chui C php :STR(s thc,S k t[,s l]) V d Str(12.345,5,2)->12.35 Ch : khi ni chui vi s,ngy ta phi chuyn cc gi tr ny sang chui,sau s dng du + ni

B>Cc hm ngy gi

Bi 4: Lp trnh vi SQL SerVer


yy, yyyy qq, q mm, m dy, y Dw dd, d wk, ww hh mi, n ss, s

Bng m t cc nh dng trong cc hm thi gian Gi tr nh dng Nm Qu Thng Ngy trong nm Ngy trong tun Ngy trong thng Tun Gi pht giy

Bi 4: Lp trnh vi SQL SerVer


Hm DateAdd : dng cng mt s vo gi tr ngy v tr v mt gi tr ngy C php : DateAdd(nh dng,S,Ngy)->Ngy mi V d declare @ngaymoi datetime set @ngaymoi=dateadd(mm,5,getdate()) print convert(char(10),@ngaymoi,105) Hm DateDiff: tr v khong cch ca hai ngy C php :Datediff(nh dng,ngy_1,ngy_2)->s nguyn V d :print Datediff(mm,getdate(),@ngaymoi) ->5

Bi 4: Lp trnh vi SQL SerVer


Hm DateName: tr v chui thi gian C php : Datename(nh dng, Ngy)->chui V d print datename(dw,getdate())->monday Hm DatePart: tr v mt gi tr ca ngy C php :Datepart(nh dng,ngy)->s nguyn V d :print datepart(qq,getdate())->2 Hm Getdate() ->Tr v ngy hin hnh Hm Day(),Month(),Year()-> tr v ngy,thng,nm

Bi 4: Lp trnh vi SQL SerVer


Hm Round :hm lm trn s C php :Round(s,s ch s thp phn) v d : round(12.3456,2)->12.35 Left(chui ngun,s k t) ->ct chui t tri sang ly s k t Right(chui ngun,s k t)-> ct chui t phi sang ly s k t Substring(chui,v tr,s k t) -> ct chui t v tr sang tri ly s k t Hm Exists(Cu truy vn Select)=True nu cu truy vn c gi tr tr v

Bi 4: Lp trnh vi SQL SerVer


3>CurSor :l i tng dng cha d liu ly t CSDL ,ging i tng recordset trong VB C php khai bo bin Cursor : Declare Tn_Bin CURSOR [phm vi] [di chuyn][trng thi][x l] For cu lnh Select [For update [OF danh sch ct]] Trong : Phm vi : LoCal :ch s dng trong phm vi khai bo(mc nh) Global :s dng chung cho c kt ni

Bi 4: Lp trnh vi SQL SerVer


Di chuyn : ForWard_Only :ch di chuyn mt hng t trc ra sau(mt nh) Scroll : di chuyn ty Trng thi Static : d liu trn Cursor khng thay i mt d d liu trong bng ngun thay i(mt nh) Dynamic :d liu trn Cursor s thay i khi d liu trong bng ngun thay i KeySet :ging Dynamic nhng ch thay i nhng dng b cp nht

Bi 4: Lp trnh vi SQL SerVer


X l : Read_Only :ch c(mt nh) Scroll_Lock : c/ghi Cu lnh select :khng cha cc mnh Into,Compute,Compute by Danh sch ct cp nht : l danh sch cc ct s thay i c M CurSor: Open tn_Bin_Cursor c v x l d liu trong cursor C php : FETCH Hng di chuyn From Tn_bin_Cursor Into Danh sch bin

Bi 4: Lp trnh vi SQL SerVer


Trong : Hng di chuyn : NEXT: Di chuyn v sau PRIOR : Di chuyn v trc FIRST : Di chuyn v u LAST : Di chuyn v cui ABSOLUTE n : di chuyn n mu tin th n tnh t mu tin u tin ,nu n<0 : tnh t mu tin cui RELATIVE n :di chuyn n mu tin th n tnh t mu tin hin hnh

Bi 4: Lp trnh vi SQL SerVer


Trong qu trnh di chuyn kim tra vic di chuyn c thnh cng hay khng ta kim tra bin h thng @@FETCH_STATUS nu <>0 tht bi ng Cursor :Close Tn_Bin Gii phng CurSor khi b nh :DEALLOCATE Tn_Bin Ch :th t cc thao tc khi x l d liu trn CurSor 1. nh ngha bin Cursor 2. M Cursor 3. Duyt v x l d liu trn Cursor 4. ng v gii phng Cursor

Bi 4: Lp trnh vi SQL SerVer


Tnh tn kho cho cc vt t trong thang 1 nm 2005 Ly tt c d liu trong bng Vt t a vo Cursor Duyt qua Cursor ly t vt t, tnh Tng s lng nhp trong thng 1 nm 2005 Tng s lng xut trong thng 1 nm 2005 Ly tn u ca vt t trong thng 1 nm 2005 Tnh tn cui=Tng slnhp+tn u Tng sl Xut Cp nht vo bng tn kho

Bi 4: Lp trnh vi SQL SerVer


V d declare Cur_Vattu CurSor for select Mavtu,tenvtu from Vattu open Cur_Vattu declare @mavtu char(4),@tenvtu varchar(100) while 0=0 begin fetch next from Cur_vattu into @mavtu,@tenvtu if @@fetch_status<>0 break print 'M vt t :' + @mavtu +' Tn Vt t :' + @tenvtu end close Cur_Vattu deallocate Cur_Vattu

Bi 5: Th tc ni Ti(Stored procedure)
1>Th tc ni ti l g ? l Chng trnh con ca Sql SerVer Trong th tc ni ti c th cha cc cu lnh truy vn, cc lnh T-SQL Th tc ni ti c th c cc tham s vo, tham s ra v c th tr v kt qu Ta c th gI th tc ni ti trong SQL hay trong cc ng dng c xy dng bng VB,VB.NET Cc x l xy dng trong th tc ni ti s chy nhanh hn khi xy dng ngoi ng dng, v tp trung ti server nn d qun l Theo m hnh lp trnh client-server tt c cc x l u tp trung ti server, trong sql server cc x l ny nm trong ttnt

Bi 5: Th tc ni TI(Stored procedure)
2>c php xy dng ttnt Create Proc Ten_Thu_Tuc [(Cc tham s)] As cc cu lnh Trong : Cc tham s : chia lm hai loI Tham s vo : nhn gi tr t ngI dng gI vo cho ttnt x l C php : @Ten_bien Kiu_d_liu [=gi tr mt nh] Tham s ra :nhn kt qu tr v t Ttnt v hin th cho ngI dng C php : @Ten_bien Kiu_d_Liu OutPut

Bi 5: Th tc ni TI(Stored procedure)
GI thc hin ttnt Exec Ten_Thu_Tuc [ @ten_Tham_so_vao= gia_tri[,..] @ten_Tham_so_ra=@ten_Bien output] LNH Return trong TTNT: Trong th tc nt ta c th dng lnh Return tr v kt qu hoc thot khI th tc C php : Return gi tr :thot khI th tc v tr v kt qu l gi tr Hoc Return : Thot khI th tc,tr v 0 GI th tc c gi tr tr v Exec @ten_bien=Ten_thu_Tuc [ @ten_Tham_so_vao= gia_tri[,..] @ten_Tham_so_ra=@ten_Bien output]

Bi 5: Th tc ni TI(Stored procedure)
3>Cc dng th tc ni ti : A. Th tc hin th d liu: Loi th tc ny c th c tham s vo Trong n cha cu lnh Select

Bi 5: Th tc ni TI(Stored procedure)
B.Th tc Tnh Ton : Loi th tc ny c th c tham s vo,tham s ra, gi tr tr v Trong n cha cu lnh T-SQL kim tra ,tnh ton gi tr tr v

Bi 5: Th tc ni TI(Stored procedure)
C>Th tc Thm d liu vo bng: Loi th tc ny c tham s vo l tn cc ct c trong bng, tr cc ct c kiu d liu t tng (identity) Tham s ra,gi tr tr v :c th c, cho bit vic thm d liu c thnh cng hay khng Trong n cha cu lnh T-SQL : Kim tra rng but d liu duy nht(primary key,unique) c php : if Exists (Select * from Ten_Bang where Ten_Cot=@ten_cot) begin print thng bo li set @bien_tra_ve= gi tr lI Hoc Return gi tr li Return End

Bi 5: Th tc ni Ti(Stored procedure) Kim tra rng but kha ngoi (Foreign Key)
C php if not Exists (Select * from Ten_Bang1 where Ten_Cot=@ten_cot) begin print thng bo li

set @bien_tra_ve= gi tr lI Hoc Return gi tr li Return End if Kim tra rng but Min gi tr (Check) if @ten_cot khng nm trong min gi tr begin print thng bo li set @bien_tra_ve= gi tr lI Hoc Return gi tr li Return

Bi 5: Th tc ni TI(Stored procedure)
Ghi d liu vo bng C php Insert into Ten_Bang(Ten_cot1[,]) values( @Ten_cot1[,]) Cp nht d liu vo cc bng lin quan C php Update Ten_Bang Set Ten_Cot= Giatri where <iu kin>

Bi 5: Th tc ni TI(Stored procedure)
d>Th tc Cp nht d liu ca bng: Loi th tc ny c tham s vo l tn cc ct c trong bng, Tham s ra,gi tr tr v :c th c, cho bit vic Cp nht d liu c thnh cng hay khng Trong n cha cu lnh T-SQL : Kim tra d liu cp nht c tn ti hay khng c php : if not Exists (Select * from Ten_Bang where Ten_Cot_khoa_chinh=@ten_cot_khoa_chinh) begin print thng bo li set @bien_tra_ve= gi tr lI Hoc Return gi tr li Return End

Bi 5: Th tc ni TI(Stored procedure)
Kim tra rng buc kha ngoi Kim tra rng buc min gi tr Cp nht d liu vo bng C php Update Ten_Bang Set ten_cot=@tencot [,..] Where ten_cot_khoa_chinh=@ten_cot_khoa_chinh Ch : khng cp nht ct lm kha chnh v ct c thuc tnh identity Cp nht d liu ca cc bng lin quan

Bi 5: Th tc ni TI(Stored procedure)
E>Th tc xa d liu ca bng: Loi th tc ny c tham s vo l cc ct lm kha chnh trong bng, Tham s ra,gi tr tr v :c th c, cho bit vic xa d liu c thnh cng hay khng Trong n cha cu lnh T-SQL : Kim tra d liu xa c tn ti trong bng nhiu hay khng c php : if Exists (Select * from Ten_Bang_nhieu where Ten_Cot_khoa_ngoai=@ten_cot_khoa_chinh) begin print thng bo li return End

Bi 5: Th tc ni TI(Stored procedure)
xa d liu khi bng C php Delete Ten_Bang Where ten_cot_khoa_chinh=@ten_cot_khoa_chinh lnh cp nht d liu ca cc bng lin quan

Bi 5: Th tc ni TI(Stored procedure)
Giao tc :(Transaction): L tp hp cc lnh s c thc hin nu tt c u thnh cng, nu c mt lnh tht bi ,th s khng c lnh no c thc hin V d : giao tc chuyn tin ca ngn hng : chuyn s lng N t ti khon A sang ti khon B, cc cng vic c thc hin : TaiKhoanA=TaiKhoanA-N TaiKhoanB=TaiKhoanB+N Hai cng vic ny s c thc hin nu khng c lnh no gy li

Bi 5: Th tc ni TI(Stored procedure)
C php xy dng 1 giao tc trong SQL Server Lnh Bt u 1 Giao tc : Begin Tran Lnh kt thc thnh cng 1 giao tc : Commit Tran Lnh kt thc tht bi 1 giao tc : Rollback Tran kim tra cc lnh thc hin c thnh cng hay khng :truy cp n gi tr ca bin @@Error, nu @@Error<>0 : tht bi

Bi 5: Th tc ni TI(Stored procedure) C php :


Begin Tran < lnh> If @@error<>0 begin print giao tac that bai Rollback tran Return End Commit tran

V d thm d liu vo Ctdondh v cp nht ct Tongsldat trong Dondh declare @co int Begin Tran update dondh set tongsldat=tongsldat+10 where sodh='d001 If @@error<>0 set @co=1 insert into ctdondh(sodh,mavtu,sldat) values('d001','tv00',10) If @@error<>0 set @co=1 if @co=1 rollback tran else Commit tran

Bi 5: Th tc ni TI(Stored procedure)

Bi 5: Th tc ni TI(Stored procedure) Th tc ni ti tr v Cursor :Th tc tr v mt Cursor cha cc


dng d liu tha iu kin C php truyn tham s tr v kiu Cursor : @Ten_bien Cursor Varying Output Cc x l : Bn trong th tc : Gn gi tr cho Cursor, c php : Set @Ten_Bien=CurSor [phm vi] [di chuyn][trng thi][x l] For cu lnh Select M Cursor :Open @ten_Bien

Bi 5: Th tc ni TI(Stored procedure) Ngoi th tc :


Duyt v x l d liu trong Cursor ng v gii phng Cursor V d : xy dng th tc ni ti truyn vo maNhacc v tr v mt Cursor cha danh sch cc ndh ca nh cc create proc Danh_Sach_Dondh(@manhacc char(3), @Cur_Kq cursor varying output) as set @cur_Kq= cursor for select * from dondh where manhacc=@manhacc open @cur_Kq

Bi 5: Th tc ni TI(Stored procedure) --ngoi th tc


declare @Cur cursor exec Danh_Sach_Dondh @manhacc='c02', @cur_kq=@Cur output declare @sodh char(4), @ngaydh datetime,@manhacc char(4), @tongsldat int while 0=0 begin fetch next from @Cur into @sodh, @ngaydh,@manhacc, @tongsldat if @@fetch_Status<>0 break print @sodh + ' ' + convert(char(10),@ngaydh ,103)+ @manhacc + str(isnull(@tongsldat,0)) end close @Cur deallocate @cur

Bi 6:Hm Do Ngi Dng nh Ngha


1>Khi Nim: L i tng mi c b sung vo SQL Server 2000 Mang y tnh cht ca mt hm :c th c tham s vo, x l v tr v kt qu Cc loi hm : Hm xc nh (deter-ministic) : lun tr v 1 gi tr khi nhn cc gi tr truyn vo nh nhau Hm khng xc nh (non-deterministic) : cho gi tr khc nhau ty thi im gi nh hm Getdate()..

2>Xy dng Hm:

Bi 6:Hm Do Ngi Dng nh Ngha

A> hm tr v mt gi tr : gi tr tr v c kiu d liu l mt trong cc kiu ca SQL Server C php : Create Function Ten_Ham[(Cc tham s)] Returns Kiu_d_liu_tr_v as Begin <cc x l> Return ket_qua end

Xy dng hm truyn vo Sodh,Mavtu -> tr v tng SLnhp

Bi 6:Hm Do Ngi Dng nh Ngha

create function Tinh_Tong_Slnhap(@sodh char(4),@mavtu char(4)) returns int as begin declare @tongslnhap int select @tongslnhap= isnull(sum(slnhap),0) from ctpnhap inner join pnhap on ctpnhap.sopn=pnhap.sopn where sodh=@sodh and mavtu=@mavtu return @tongslnhap end

Gi hm :

Bi 6:Hm Do Ngi Dng nh Ngha

declare @kq int set @kq =dbo.Tinh_Tong_Slnhap('d001','dd01') print @kq Gi trong cu truy vn : select Dondh.sodh,convert(char(10),ngaydh,103) as ngaydh,vattu.mavtu,tenvtu,sldat, dbo.Tinh_Tong_slnhap(dondh.sodh,Vattu.mavtu) as tongsldanhap from dondh inner join ctdondh on dondh.sodh=ctdondh.sodh inner join vattu on ctdondh.mavtu=vattu.mavtu

S dung ham trong lenh tao bang V du : xay dng ham create function lay_ngaydh(@sodh char(4)) returns datetime as begin declare @ngay datetime

Bi 6:Hm Do Ngi Dng nh Ngha

select @ngay= ngaydh from dondh where sodh=@sodh return @ngay end

Ta co the s dung ham nay trong constraint check trong lenh tao bang phieu nhap create table pnhap ( sopn char(4) not null, sodh char(4) not null, ngaynh datetime,

Bi 6:Hm Do Ngi Dng nh Ngha

constraint chk_pnhap_ngaynh check(ngaynh>dbo.lay_ngaydh(sodh )) )

Bi 6:Hm Do Ngi Dng nh Ngha


B>hm tr v d liu c ly t cc bng trong CSDL:ging nh view nhng c tham s vo C php : Create Function Tn_Hm[(cc tham s vo)] Returns Table as Return(Cu lnh select) Gi th tc loi ny ging nh view

Bi 6:Hm Do Ngi Dng nh Ngha


v du : xay dung ham truyen vao sodh tra ve ctdondh create function lay_ctdondh(@sodh char(4)) returns table as return (select sodh,tenvtu,sldat from vattu inner join ctdondh on vattu.mavtu=ctdondh.mavtu where sodh= @sodh) --goi select * from dbo.lay_ctdondh('d002')

C> hm to bng : to v tr v mt bng, trong hm c th cha tt c cc lnh T-SQL C php : Create Function Ten_Ham[(cc tham s)] Returns @Ten_Bang_tr_v Table (Tn_ct Kiu_d_liu[,] )as Begin <cc lnh T-SQL> Insert into @ten_bang_tra_ve .. Return end

Bi 7:Trigger
1>Tng quan: Trigger l mt dng t bit ca th tc ni ti nhng : Trigger khng c tham s Khng gi thc hin bng lnh Exec, m t ng kch hot khi d liu trn bng c lin quan n Trigger c cp nht Mt Trigger c to cho mt bng v dng kim tra cc rng but ton vn phc tp hoc cp nht d liu ca cc bng lin quan

Bi 7:Trigger
2>xy dng Trigger: C php Create Trigger Ten_trigger on Ten_Bang/Tn View For/Instead of Insert[,Update,Delete] AS <Tp lnh T-SQL>

Bi 7:Trigger
Trong : Tn bng/view : l bng/view m trigger c to Nu Trigger c khai bo vi t kha For :trigger ny s c kch hot sau khi d liu cp nht vo bng Nu Trigger c khai bo vi t kha Instead of :trigger ny s c kch hot trc khi d liu cp nht vo bng, thng c dng kim tra d liu cp nht trn View, trong trigger loi ny ta phi vit cc cu lnh cp nht tng ng vi hnh ng Insert,Update,Delete : Trigger c kch hot ng vi hnh ng thm,sa ,xa d liu trong bng Th t kim tra cc rng buc ton vn d liu trong bng : Trigger Instead of->constraint-> trigger For

Bi 7:Trigger
3>Hai bng tm Inserted v Deleted: Khi thm d liu vo bng, d liu c thm vo s a vo bng tm Inserted Khi xa d liu ra bng, d liu xa s a vo bng tm Deleted Thao tc cp nht c x l : Xa dng d liu c (d liu c s a vo bng Deleted) Thm dng d liu mi(d liu mi s a vo bng inserted) ly d liu va mi cp nht vo bng ta truy cp vo bng tm Deleted hoc Inserted ,ch truy cp c hai bng ny trong Trigger

Bi 7:Trigger
4>Cc lnh s dng trong trigger: Thng bo li trong Trigger : thng bo li trong trigger ta dng hm : Raiserror(Chui thng bo li,16,1) Khng cho thay i d liu : Rollback Tran

Bi 7:Trigger
A>Cc x l trong Trigger kim tra khi thm d liu vo bng Khai bo bin : trong bng c bao nhiu ct tng ng khai bo by nhiu bin Dng cu lnh Select ly d liu t bng Inserted gn cho cc bin ny Kim tra rng but ton vn ging th tc ni tai thm dl

B>Cc x l trong Trigger kim tra khi Sa d liu vo bng Kim tra khng cho php cp nht cc ct If Update(Ten_Cot) Begin Raiserror(khng thay i d liu ct Ten_Cot,16,1) Rollback Tran return end Khai bo cc bin ly d liu kim tra Dng cu lnh Select ly d liu mi c cp nht t bng Inserted , ly d liu trc khi cp nht t bng Deleted

Bi 7:Trigger

Bi 7:Trigger
C>Cc x l trong Trigger kim tra khi xa d liu Khai bo cc bin ly d liu kim tra Dng cu lnh Select ly d liu mi xa t bng Deleted Kim tra rng but ton vn ging th tc ni tai xa dl

Bi 8 :K thut lp trnh Vb vi SQL


Server
I. A. Lin k t d li u VB v SQL Server C php

Ging nh vic lin kt d liu gia VB v Access, vic lin kt gia Vb v SQL Server cng c thc hin thng qua i tng ADODB.Connection nh gi tr ca chui kt ni - ConnectionString ConnectionString = "Provider=SQLOLEDB.1;Initial Catalog=Tn_CSDL; " & _ "Data Source=Tn_My_Tnh;User Id=Tn_Ti_Kho n;Pwd=M t_Kh u"

Bi 8 :K thut lp trnh Vb vi SQL


Public Sub LinkSQL_DB() On Error GoTo LoiLienKet: If cnSQL Is Nothing Then Set cnSQL = New ADODB.Connection cnSQL.ConnectionString = "Provider=SQLOLEDB.1; Initial Catalog=QL_Ban_Hang;Data Source=ADMIN; User Id=sa;Pwd=" cnSQL.CursorLocation = adUseClient cnSQL.Open End If Exit Sub LoiLienKet: MsgBox "loi lien ket" End Sub

Server

Bi 8 :K thut lp trnh Vb vi SQL


Server
i tng Command :l i tng dng gi thc thi mt th tc ni ti trong SQL Server Cc thuc tnh : ActiveConnection : i t ng connection CommandText : tn th t c CommandType : ki u l adCmdStoredProc Execute :G i th c hi n N u th t c n i t i ch a cu truy v n, th ph ng th c execute c a command tr v m t recordset ch c

Bi 8 :K thut lp trnh Vb vi SQL


Server
Vo module xy dng hm c bng Public Function Doc_Bang(Ten_Thu_Tuc As String) As ADODB.Recordset LinkSQL_DB Dim Lenh As ADODB.Command Set Lenh = New ADODB.Command Set Lenh.ActiveConnection = cnSQL Lenh.CommandText = Ten_Thu_Tuc Lenh.CommandType = adCmdStoredProc Set Doc_Bang = Lenh.Execute End Function

Bi 8 :K thut lp trnh Vb vi SQL


Server
i tng Parameter : dng truyn tham s vo ,tham s ra, nhn gi tr tr v trong ttnt Khai bo v khi to : Dim p As ADODB.Parameter p= cmd.CreateParameter("tents",kieudl,kieuthamso,kich thuoc,giatri) Trong : tn tham s : l tn ca tham s trong ttnt Kiu d liu :l kiu ca tham s adDate :kiu ngy adBSTR :kiu chui adInteger :kiu s

Bi 8 :K thut lp trnh Vb vi SQL


Server
Kiu tham s : adParamReturnValue : gi tr tr v adParamInput : tham s vo adParamOutput : Tham s ra Kch thc : nu tham s c kiu chui (Char,VarChar) th mi truyn kch thc Gi tr : nu tham s l tham s vo mi truyn gi tr Th t truyn tham s :Tham s nhn gi tr tr v phi truyn vo u tin, sau ti th t cc tham s trong th tc ni ti a tham s vo th tc : Ten_Bien_Command. Parameters.Append Ten_Bien_Parameter

CREATE proc Proc_Vattu_Them(@mavtu char(4),@tenvtu varchar(100),@phantram float,@dvtinh varchar(10)) as if exists(select * from vattu where mavtu=@Mavtu) return 1 if exists(select * from vattu where tenvtu=@tenvtu)return 2 if @phantram<0 or @phantram>100 return 3 insert into vattu values(@mavtu,@tenvtu,@dvtinh,@phantram) return 0 GO

Bi 8 :K thut lp trnh Vb vi SQL


Server
To bo co vi Crystal Report 1. To bo co: B c 1: Ch n As a Blank Report trong h p tho i Welcome to Crytal Reports

Bi 8 :K thut lp trnh Vb vi SQL


Server
Bc 2: Chn Microsoft SQL Server trong hp thoi More Data Sources

Bi 8 :K thut lp trnh Vb vi SQL


Server
B c 3: i n y thng tin cho mn hnh ng nh p

nh tn Server vo y!

Bi 8 :K thut lp trnh Vb vi SQL


Server
B c 4: Ch n cc b ng c n thi t cho bo co, nh n nt Add, sau nh n Close

Bi 8 :K thut lp trnh Vb vi SQL


Server
Kiu tham s : adParamInput : tham s vo adParamOutput : tham s ra adParamReturnValue : gi tr tr v Chiu di : i vi kiu d liu chui( char, varchar..) ,ta phi truyn vo chiu di ca d liu Gi tr : i vi cc tham s vo ta phi c gi tr truyn vo a tham s vo comman cmd.Parameters.Append tn_tham_so Th t truyn tham s : tham s tr v,cc tham s theo th t c khai bo trong ttnt

Bi 8 :K thut lp trnh Vb vi SQL


Server
Cc thnh phn trong Report ReportHeader : hin th mt ln trn u bo co ReportFootter : hin th mt ln cui bo co Page Header : hin th trn u mi trang Page Footer : hin th cui mi trang Details : phn hin th d liu chi tit ca Report Ngoi ra nu bo co c phn nhm s c thm cc phn : Group Header : hin th u nhm Group Footer : hin th cui nhm

Bi 8 :K thut lp trnh Vb vi SQL


Cch thit k bo co :

Server

Nhp chui vo bo co : click chuc vo biu tng ab trn thanh cng c -> v vo bo co a cc ct d liu hin tr trn bo co : trong hp thoi dataexplorer chn DataBase File -> chn ct v ko th vo v tr thch hp trn bo co C hai dng bo co : Danh mc : hin th d liu ging nh trong cu truy vn Phn nhm : d liu hin th theo dng : D liu nhm D liu chi tit D liu nhm

Bi 8 :K thut lp trnh Vb vi SQL


Server
Nu bo co c phn nhm : a nhm vo bo co : insert ->group -> chn ct gom nhm (thng chn ct lm kha chnh trong bng nhm) Trong hp thoi Field Explorer : Database Field : cha cc ct c trong view ngun, chn v ko cc ct t vo v tr thch hp trn bo co Running Total field : cha cc gi tr thng k trn bo co gi tr thng k l gi tr tnh ton tng cng nm u nhm, cui nhm, hay report cch to : click chut phi vo Running Total field chn New -> xut hin hp thoi

Bi 8 :K thut lp trnh Vb vi SQL


Server
RunningTotalName : tn gi tr thng k Summary : Field To Summarize : chn ct thng k Type of Summary : chn hm thng k Evaluete : chn cch thng k Foreach Record : thng k theotng dng On Change of field : thng k khi d liu ca ct thay i On change of Group : thng k khi thay i nhm Use a fomula : thng k theo iu kn

Bi 8 :K thut lp trnh Vb vi SQL


Server
Reset : khi ng li gi tr thng k Never : khng khi ng li On Change of field : khi ng li khi d liu ca ct thay i On change of Group : khi ng li khi thay i nhm Use a fomula : khi ng li theo iu kn

Bi 8 :K thut lp trnh Vb vi SQL


Server
M bo co trong VB : Bc 1 : a iu khin Crystal report vo form : project -> components -> nh du chn vo Crystal report -> Ok -> xut hin iu khin Crystal Report trn ToolBar -> chn v v vo form, t tn DK_IN Cc thuc tnh ca Crystal Report control Connect = "DSN=admin;Uid=sa;pwd=;dsq=Ql_ban_hang" ReportFileName = ng dn+Tn bo co Destination = hng xut c cc hng xut sau : crptToWindow : xut ra mn hnh crptToPrinter : xut ra my in crptToFile : xut ra tp tin

Bi 8 :K thut lp trnh Vb vi SQL


Server
crptToFile : xut ra tp tin PrintFileName : tn tp tin s cha bo co PrintFileType : loi tp tin SelectionFormula = iu kin lc d liu c dng "{Ten_Cu_Truy_Vn.Tn_Ci}='" & Gi tr & "' Nu ct c kiu ngy : "{Ten_Cu_Truy_Vn.Tn_Ci}=#" & format(Gi tr,mm/dd/yyyy) & # Action = 1 : m bo co

Bi 8 :K thut lp trnh Vb vi SQL


Server
V iu khin Crystal report t tn Bao_Cao, m bo co Report1.rpt ra mn hnh Window theo Loi ha n hn hnh Bao_cao.DataFiles(0) = App.Path & "\du_lieu\Ql_Ban_Hang.mdb" Bao_cao.ReportFileName = App.Path & "\Bao_cao\Report1.rpt" Bao_cao.Destination = crptToWindow Bao_cao.SelectionFormula = "{qrbc.Loai_Hoa_Don}='" & Bang_hoa_don("Loai_Hoa_Don") & "'" Bao_cao.Action = 1

Bi 8 :K thut lp trnh Vb vi SQL


Server
Mt s chc nng m rng : 1>to s th t cho d liu trong phn Detail To mt gi tr Running total field : Type of Sumary : count Evalute : Foreach Record Reset : On change of group

Bi 8 :K thut lp trnh Vb vi SQL


Server
Mt s chc nng m rng : 2>to s th t cho nhm To mt gi tr Running total field : Type of Sumary : count Evalute : For change of group Reset : never

Bi :K thut lp trnh Vb.NET vi SQL


1.To kt ni :

Server

ng nhp vo SQL Server theo window Ket_Noi = New SqlConnection("Data Source=Ten_Server;" & _ "Integrated Security=SSPI;Initial Catalog=Ten_CSDL") ng nhp vo SQL Server theo Username v password ca SQL Server Ket_Noi = New SqlConnection(" data source=Ten_Server;persist security info=False; initial catalog=Ten_CSDL; user id=Ten_ND;Pwd=Mat_Khau )

2.i SQL Server thc hin C php :

Server gi cc th tc ni ti trong tng Command : l i tng dng

Bi :K thut lp trnh Vb.NET vi SQL

Dim Lenh As SqlCommand Lenh = New SqlCommand(Ten_Thu_Tuc", Ket_Noi) Lenh.CommandType = CommandType.StoredProcedure gi thc hin : ty theo th tc ta c th gi cc phng thc ca Command

Server tc ni tai ta dng i tng truyn gi tr cho cc tham s trong th


Parameter Th t truyn tham s :lun truyn tham s tr v trc, sau truyn theo th t trong th tc C php : Truyn tham s tr v : Dim p As SqlParameter p = New SqlParameter("@Trave", SqlDbType.Int) p.Direction = ParameterDirection.ReturnValue Lenh.Parameters.Add(p)

Bi :K thut lp trnh Vb.NET vi SQL

Bi :K thut lp trnh Vb.NET vi SQL


Truyn tham s tr vo :

Server

p_Thamso = New SqlParameter("@Ten", kiu Dl[, chiu di]) p_Thamso.Direction = ParameterDirection.Input p_Thamso.Value = Gia_Tri Lenh.Parameters.Add(p_Thamso) Truyn tham s ra P_ThamSo = New SqlParameter("@ten_thamso", kiu DL[,chiu di]) p_Thams.Direction = ParameterDirection.Output Lenh.Parameters.Add(p_Thamso)

Xy dng bo co vi Crystal Report

Bi 4: Xy dng bo co vi Crystal Report

Bc 1 : xy dng cu truy vn cha tt c d liu hin th trn Bo co ngoi tr d liu thng k hay s th t Bc 2 : to mi mt bo co : c1 : khi ng Crystal Report chn Blank report c2 : chn File -> new report -> chn Blank report Trong hp thoi data explorer chn Database File -> Find darabase -> Xut hin hp thoi-> chn CSDL lm ngun cho bo co-> chn cu truy vn lm ngun cho bo co