You are on page 1of 30

Stored Procedures

Stored procedure - Th tc lu tr

Bao gm mt nhm cc lnh T-SQL, cc lnh ny s c thc thi khi SP c thc thi. Th tc lu tr c th c cc thnh phn sau:

Cc cu trc iu khin (IF, WHILE, CASE). Cc bin nh trong ngn ng lp trnh nhm lu gi cc gi tr tnh ton c, cc gi tr c truy xut c t c s d liu.

SP c th c gi thng qua tn SP, nhn cc tham s truyn vo, v thc thi cc lnh. Li ch ca SP: Nhanh, an ton
2

To th tc lu tr
C php CREATE PROCEDURE tn_th_tc [(danh_sch_tham_s)] [WITH RECOMPILE, ENCRYPTION] AS BEGIN <cc lnh> END

WITH RECOMPILE: yu cu SQL Server bin dch li SP mi khi gi. WITH ENCRYPTION: yu cu SQL Server m ha SP.

To th tc lu tr
V d CREATE PROCEDURE sp_Insertphong( @maphong nchar(5), @tenphong varchar(100), @diachi varchar(15)) AS insert into phong values(@maphong,@tenphong,@diachi) Gi th tc sp_Insertphong KTB', Ky thut cng ngh', 'Nha H'

Bin trong th tc lu tr
Dng lu tr gi tr: Khai bo: DECLARE @tn_bin kiu_d_liu V d: CREATE PROCEDURE sp_nv_nhieutuoinhat AS BEGIN DECLARE @maxtuoi int SELECT @maxtuoi = MAX(year(getdate())-year(ngaysinh)) FROM nhanvien SELECT manv, hoten,ngaysinh FROM nhanvien WHERE year(getdate())- year(ngaysinh)=@maxtuoi END

Gi tr tr v ca tham s

C 2 kiu bin: tham bin, tham tr.


Tham bin: Gi tr ca bin s khng thay i khi kt thc th tc. Tham tr: Gi tr ca bin tham chiu s thay i khi kt thc th tc: @a int, @b int, @c int ) AS SELECT @c = @a + @b

V d: create procedure sp_tong(

Gi th tc:
Declare @tong int set @tong = 0 sp_tong 100, 200, @tong select @tong Kt qu l 0.

Gi tr tr v ca tham s
s dng tham tr phi khai bo bin vi t kha OUTPUT <@tn_tham_s> <kiu_d_liu> [OUTPUT] V d: create procedure sp_tong ( @a int, @b int, @c int output ) AS SELECT @c = @a + @b Gi th tc:

Declare @tong int set @tong = 0 sp_tong 100, 200, @tong output select @tong Kt qu l 300

S dng lnh RETURN


Tng nh nh vic s dng tham s OUTPUT, cu lnh RETURN tr v gi i tng thc thi SP. V d:
create procedure sp_tongnv as begin declare @tong int select @tong = count(manv) from nhanvien return @tong end

Thc thi th tc lu tr
declare @a int exec @a = sp_tongnv select @a

Tham s vi gi tr mc nh
Gi tr mc nh ca tham s c s dng khi khng truyn i s cho tham s khi c li gi n th tc. C php: @<tn_tham_s> <kiu_d_liu> = gi_tr_mc_nh V d:

create procedure sp_nhanvienkta13 @manv nchar(5) = KTA13 AS begin select * from nhanvien where masv = @manv end

Thc thi th tc: sp_nhanvienkta13


9

Sa i v xa th tc
Sa SP: ALTER PROCEDURE <tn_th_tc> [(danh_sch_tham_s)] [WITH RECOMPILE|ENCRYPTION] AS <cc lnh> Xa th tc: DROP PROCEDURE <tn_th_tc> Gi th tc: c th dng t kha EXEC.

10

V d
/* Vit th tc lu tr thm 1 nhn vin vi tham s MANV, HOTEN, NGAYSINh, MAPHONG v trnh ting Anh ca nhn vin Thc hin li gi th tc vi MANV =KTA12 HOTEN =Nguyn Vn An NGAYSINH 1/13/1990 MAPHONG = KTA Trnh ting Anh: C */
11

V d
create procedure sp_insert_ttnv( @manv char(5), @hoten NVarchar(20), @ns char(10),

@mp char(3),
@tdo_ta char(1) ) AS BEGIN declare @ngaysinh datetime set @ngaysinh = CONVERT(datetime, @ns) insert into NHANVIEN (MANV, HOTEN, NGAYSINH, MAPHONG) VALUES (@manv, @hoten, @ngaysinh, @mp) -- Thm trinh Ting Anh cho nhn vin declare @mann char(2) select @mann = mann from DMNN where TENNN ='Anh' insert into TDNN VALUES (@manv, @mann,@tdo_ta) END ---goi thu tuc, tham s thc s co th thay i theo d liu ngi dung EXEC sp_insert_ttnv 'KTA13','Pham thanh An','1/2/1990','HCA', 'A'

12

Trigger

13

Trigger

Trigger l mt dng c bit ca th tc lu tr. c thc thi t ng khi c s thay i d liu (do tc ng INSERT, UPDATE, DELETE). Trigger chia thnh 2 loi INSTEAD OF v AFTER:

INSTEAD OF l loi trigger m hot ng ca s kin gi trigger s b b qua v thay vo l cc lnh trong trigger c thc hin. AFTER trigger l loi ngm nh, loi trigger ny s thc hin cc lnh bn trong sau khi thc hin xong s kin kch hot trigger.

14

Trigger

S dng khi cc bin php bo m ton vn d liu khc khng bo m c. Khi CSDL cha c chun ha th c th xy d tha d liu. Khi xy ra thay i dy chuyn d liu gia cc bng vi nhau.

15

Lnh to Trigger
CREATE TRIGGER <tn_trigger> ON <tn_bng|tn_view> FOR {[INSERT][,][UPDATE][,][DELETE]} AS [IF UPDATE(tn_ct) [AND UPDATE(tn_ct)| OR UPDATE(tn_ct)] ...] <Cc lnh ca trigger>

16

Trigger

Khi s dng Trigger, chun SQL cung cp 2 bng logic INSERTED v DELETED. Cu trc ca 2 bng tng t vi cu trc ca bng m trigger tc ng. D liu trong hai bng ny tu thuc vo cu lnh tc ng ln bng
Bng INSERTED d liu c insert d liu trc khi cp nht d liu trc khi cp nht Bng DELETED khng c d liu d liu trc khi cp nht d liu trc khi cp nht

Hot ng INSERT DELETE UPDATE


17

Lnh to Trigger

V d:
create trigger t_Checktennv on nhanvien for insert as declare @lengthOfName int select @lengthOfName = len(inserted.hoten) from inserted if @lengthOfName <=3 print N'Tn khng hp l' rollback tran Go

Thc thi:
insert into nhanvien values(KTA16', NNG,3/2/1990, Nu', KTA) Li: Tn khng hp l
18

Check trigger tn ti
if exists (select name from sysobjects where name = 't_Checktennv' and type = 'TR') print N't_Checktennv tn ti V d:
if exists (select name from sysobjects where name = 't_Checktensv' and type = 'TR') drop trigger t_Checktennv go create trigger t_Checktennv on nhanvien for insert as declare @lengthOfName int select @lengthOfName = len(inserted.hoten) from inserted if @lengthOfName <=1 print N'Tn khng hp l' rollback tran go
19

Trigger

20

Trigger
if exists (select name from sysobjects where name = 't_DecreaseQuantityOfItemForSale') drop trigger t_DecreaseQuantityOfItemForSale go create trigger t_DecreaseQuantityOfItemForSale on SALE for insert as update ITEMSFORSALE set itemsforsale.quantity = itemsforsale.quantity - inserted.salequantity from itemsforsale inner join inserted on itemsforsale.itemid = inserted.itemid go

21

Trigger
if exists (select name from sysobjects where name = 't_DecreaseSumQuantityOfItemForSale') drop trigger t_DecreaseSumQuantityOfItemForSale Go create trigger t_DecreaseSumQuantityOfItemForSale on SALE for update As if update(salequantity) update ITEMSFORSALE set itemsforsale.quantity = itemsforsale.quantity - (select sum(inserted.salequantity - deleted.salequantity) from deleted inner join inserted on deleted.saleid = inserted.saleid where inserted.itemid = itemsforsale.itemid) where itemsforsale.itemid in (select inserted.itemid from inserted) Thc hin cp nht cho bng SALE: update sale set salequantity = salequantity + 10 22 where itemid = 1

Trigger vi ct

L trigger c kch hot khi c thao tc thay i d liu trn mt s ct. S dng mnh IF UPDATE trong trigger. ( tr DELETE)
if exists (select name from sysobjects where name = 't_DecreaseSumQuantityOfItemForSale') drop trigger t_DecreaseSumQuantityOfItemForSale Go create trigger t_DecreaseSumQuantityOfItemForSale on SALE for update AS if update(salequantity) UPDATE ITEMSFORSALE SET itemsforsale.quantity = itemsforsale.quantity (SELECT SUM(inserted.salequantity - deleted.salequantity) FROM deleted INNER JOIN inserted ON deleted.saleid = inserted.saleid WHERE inserted.itemid = itemsforsale.itemid) WHERE itemsforsale.itemid in (select inserted.itemid from inserted)

23

Tng kt mt s hm trong SQL

Cc hm lm vic vi kiu d liu s:


Hm isNumeric kim tra mt gi tr c phi thuc kiu d liu s hay khng? ROUND ( s_lm_trn , _di_lm_trn ): tr v mt gi tr s, c lm trn theo mt i ch nh V d: select ROUND(123.4545, 2),ROUND(123.45, -2)

24

Cc hm lm vic vi kiu d liu chui

Hm LEFT tr v mt chui k t c chiu di c ch nh tnh t bn tri ca chui. V d: select left('Nha Trang', 5) Hm RIGHT: tng t LEFT, tnh t bn phi SUBSTRING (chui_ban_u, v_tr_bt_u, chiu_di_chui_con): ly ra 1 xu con Hm LEN tr v chiu di mt chui LEN(123456) Hm REPLACE thay th mt chui bi mt chui khc: Select replace(Nha Trang, Nha, MAI). Hm STUFF thay th mt s lng xc nh cc k t trong mt chui bng mt chui khc bt u t mt v tr c ch nh.VD select stuff('Nha Trang', 2, 3, '***'). Hm LOWER/UPPER LTRIM/RTRIM
25

Cc hm lm vic vi kiu d liu Thi gian


Hm GETDATE tr v ngy gi lc thc hin cu truy vn. DAY/ MONTH/ YEAR (1 gi tr kiu datetime) DATEPART(yu_cu_trch_xut, gi_tr_trch_xut). Datename (yu_cu_trch_xut, gi_tr_trch_xut).

gi_tr_trch_xut l mt gi tr thuc kiu datetime. yu_cu_trch_xut: ngy, thng, nm, qu,.

26

Cc hm lm vic vi kiu d liu Thi gian

V d: select datepart(yyyy, ngaysinh)as namsinh FROM tbl_sinhvien


27

CAST (biu_thc/gi_ tr AS kiu_d liu [_di_kiu_d_liu ]) CONVERT ( kiu_d liu [_di_kiu_d_liu ] , biu_thc/gi_ tr [ ,kiu_nh_dng] )

28

29

Bi tp

Vit trigger bo li khi nhp 2 phong c tn ging nhau. Vit th tc ly danh sch nhanvien ca mi phng theo bin tn phng

30

You might also like