Chuong 2_ NNLT T- SQL Nangcao

Embed Size (px)

Citation preview

  • Ngn ng lp trnh Transaction SQL

  • Ni dung bi hc

    1. Enterprise Application Architechter

    2. Bin v cc kiu d liu

    3. Ton t

    4. Hm

    5. Cc cu lnh iu khin

    6. Cc cch s dng cc lnh T-SQL

    7. Stored Procedure

    8. Trigger

  • Thit k Enterprise Application Architecture

    Xc nh cc lp logical (Logical Layers)

    Thit k cc lp vt l (Physical Layers)

    Truy xut d liu

  • Logical Layers

  • Data presentation Layer

    c xem l user service and cho php user xem v thao tc ln data: web browser and cc Microsoft Windows applications

    S dng cc service m application logic layer cung cp

  • Application Logic Layer Cha application logic, nh ngha cc rules v

    processes gip cho user khng cn truy xut trc tip vo database

    Clients kt ni vo business service kt ni vo data server. Business service l cc custom-built components hoc integrated applications v services, v d nh Web services.

    Application logic layer cha cc components to thnh transaction services, messaging services, hoc object v connection management services.

  • Data Services Layer

    Data services bao gm data access logic v data storage.

    Bao gm cc SQL Server stored procedures qun l data traffic v integrity trn the database server.

  • Thit k cc lp vt l

  • Truy xut d liu

  • Khai bo bin

    Dng t kho declare khai bo bin

    DECLARE {@local_variable data_type} [,...n]

    Gn gi tr cho bin

    SET @local_variable_name = expression

  • V d

    DECLARE @vLastName char(20),

    @vFirstName varchar(11)

    SET @vLastName = 'Dodsworth

    SELECT @vFirstName = FirstName

    FROM Northwind.Employees

    WHERE LastName = @vLastName

    PRINT @vFirstName + ' ' + @vLastName

    Gn gi tr cho

    bin bng t kho set

    hoc bng cu lnh select

  • Data Type (1) Integers

    Bigint: 8 bytes Int: 4 bytes Smallint: 2 bytes Tinyint: 1 byte, t 0 -> 255.

    bit Bit: 1 hoc 0 value.

    decimal and numeric Decimal t -10^38+1->10^38 1. Numeric: ging decimal.

    money and smallmoney Money: 8 bytes Smallmoney: 4 bytes

    Approximate Numerics Float: t -1.79E + 308 -> 1.79E + 308. Real: t -3.40E + 38 -> 3.40E + 38.

  • Data Type (2) datetime and smalldatetime

    Datetime: t 1/1/1753-> 31/12/9999.

    Smalldatetime t 1/1/1900, -> 6/6/2079.

    Character Strings

    Char: Fixed-length non-Unicode character,

  • Ton t (operators)

    Cc loi ton t

    S hc: *, /, %, - , +

    So snh: =, , >, >=,

  • Th t u tin cc ton t

  • Functions (1)

    Aggregate functions: tnh ton trn mt nhm v tr v mt gi tr. V d:

    SELECT AVG(UnitPrice) FROM Products

    Products

    28.8663

    (1 row(s) affected)

  • Functions (2)

    Scalar functions: Tc ng ln mt gi tr v tr v mt gi tr. C th s dng hm trong cc biu thc.

    Chng ta c th nhm cc scalar function theo nhm sau:

    Configuration Tr v cc thng tin v configuration

    Cursor Tr v cc thng tin v Cursor

    DateTime Hm tc ng ln gi tr dateTime nhp vo v tr v mt gi tr l string, numeric, hoc datetime

    Mathematical Hm s hc

    Metadata Thng tin v database

    String Cc hm chui

  • Functions (3)_ V d

    SELECT DB_NAME() AS 'database'

    Database

    Northwind

    (1 row(s) affected)

    SET DATEFORMAT dmy

    GO

    DECLARE @vdate datetime

    SET @vdate = '29/11/00'

    SELECT @vdate

    2000-11-29 00:00:00.000

  • Mathematical Functions

    ABS DEGREES RAND

    ACOS EXP ROUND

    ASIN FLOOR SIGN

    ATAN LOG SIN

    ATN2 LOG10 SQUARE

    CEILING PI SQRT

    COS POWER TAN

    COT RADIANS

  • Aggregate Functions

    AVG MAX

    BINARY_CHECKSUM MIN

    CHECKSUM SUM

    CHECKSUM_AGG STDEV

    COUNT STDEVP

    COUNT_BIG VAR

    GROUPING VARP

  • DateTime functions Function Determinism

    DATEADD Deterministic

    DATEDIFF Deterministic

    DATENAME Nondeterministic

    DATEPART Deterministic except when used as DATEPART (dw, date). dw, the weekday datepart, depends on the value set by SET DATEFIRST, which sets the first day of the week.

    DAY Deterministic

    GETDATE Nondeterministic

    GETUTCDATE Nondeterministic

    MONTH Deterministic

    YEAR Deterministic

  • String functions

    ASCII NCHAR SOUNDEX

    CHAR PATINDEX SPACE

    CHARINDEX REPLACE STR

    DIFFERENCE QUOTENAME STUFF

    LEFT REPLICATE SUBSTRING

    LEN REVERSE UNICODE

    LOWER RIGHT UPPER

    LTRIM RTRIM

  • Cast v Convert

    CAST ( expression AS data_type )

    CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

  • Control-of-Flow Language

    1. BEGIN...END : nh ngha mt khi lnh

    BEGIN sql_statement | statement_block

    END

  • 2. If .. else IF Boolean_expression

    { sql_statement | statement_block } [ ELSE { sql_statement | statement_block } ]

    if (select count(*) from customers where country='canada') > 0

    begin

    print There are many Canada customers'

    end

    else

    print Welcome'

  • V d lnh If. Else USE Northwind

    IF EXISTS (SELECT OrderID FROM Orders

    WHERE CustomerID = 'Frank')

    PRINT '*** Customer cannot be deleted ***'

    ELSE

    BEGIN

    DELETE Customers WHERE CustomerID = 'Frank'

    PRINT '*** Customer deleted ***'

    END

  • 3. While WHILE Boolean_expression

    { sql_statement | statement_block } [ BREAK ] { sql_statement | statement_block } [ CONTINUE ]

    BREAK: thot ra khi vng while

    CONTINUE: restart li vng lp, b qua cc lnh sau CONTINUE.

  • GOTO

    GOTO LabelName

    IF (SELECT SYSTEM_USER()) = 'payroll'

    GOTO calculate_salary

    -- Other program code would appear here.

    -- When the IF statement evaluates to TRUE,

    -- the statements between the GOTO and

    -- the calculate_salary label are ignored.

    -- When the IF statement evaluates to FALSE the

    -- statements following the GOTO are executed.

    calculate_salary:

    -- Statements to calculate a salary would appear after the label.

  • Row .Level Simple CASE function: CASE input_expression

    WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END

    Searched CASE function:

    CASE WHEN Boolean_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END

  • V d SELECT ProductID, 'Product Inventory Status' =

    CASE

    WHEN (UnitsInStock < UnitsOnOrder AND Discontinued = 0)

    THEN 'Negative Inventory - Order Now!'

    WHEN ((UnitsInStock-UnitsOnOrder) < ReorderLevel AND Discontinued = 0)

    THEN 'Reorder level reached- Place Order'

    WHEN (Discontinued = 1) THEN '***Discontinued***'

    ELSE 'In Stock'

    END

    FROM Products

  • Kt qu cu lnh

  • p dng trong database QLVT

    Lit k cc chi tit ho n ca ho n HD01 gm cc thng tin: M vt t, SL, Gi bn, KM vi

    KM = 0 nu SL =10

    KM = (SL*giaban) * 0.2 nu SL >=100

  • Comments Inline comments SELECT ProductName,

    (UnitsInStock + UnitsOnOrder) AS Max, -- Calculates inventory

    SupplierID

    FROM Products

    SELECT

    Block comments /*

    ** This code retrieves all rows of the products table

    ** and displays the unit price, the unit price increased

    ** by 10 percent, and the name of the product.

    */

    SELECT UnitPrice, (UnitPrice * 1.1), ProductName FROM Products

  • Lnh RAISERROR

    Tr v mt thng bo li do user nh ngha

    C php:

    RAISERROR ( { msg_id | msg_str }

    { , severity , state } ) [ WITH option [ ,...n ] ]

  • Tham s

    msg_id l m li c lu trong sysmessages table.

    msg_str: l chui thng bo li c nh dng ging nh lnh printf trong lp trnh C

    Severity: mc nghim trng ca li. C gi tr t 0->18 c dng bi user, t 19 -> 25 c dng bi sysadmin (dng vi WITH LOG).

    State: s nguyn t 1 ->127 m t mc cn thit ca li.

  • Cc cch thc hin cc lnh T-SQL

    Cc lnh c cu trc ng

    Dng Batch

    Dng Scripts

    Dng Transactions

    Dng XML

  • Dng cu trc lnh ng

    Dng lnh EXECUTE vi cc hng chui v bin

    S dng khi ta phi gn gi tr cho bin ti thi im execute

    Cc bin v table tm ch tn ti trong thi gian thc thi lnh.

    DECLARE @dbname varchar(30), @tblname varchar(30)

    SET @dbname = 'Northwind'

    SET @tblname = 'Products'

    EXECUTE

    ('USE ' + @dbname + ' SELECT * FROM '+ @tblname)

  • S dng khi (batch)

    Mt hoc nhiu lnh T- SQL c submit cng lc vi nhau.

    S dng lnh GO kt thc mt khi

    Cc bin khng th tham chiu sau lnh GO

    Khng th dng cc lnh sau y trong batch:

    CREATE PROCEDURE

    CREATE VIEW

    CREATE TRIGGER

    CREATE RULE

    CREATE DEFAULT

  • V d lnh khi lnh batch hp l

    CREATE DATABASE ...

    CREATE TABLE ...

    GO

    CREATE VIEW1 ...

    GO

    CREATE VIEW2 ...

    GO

  • CREATE DATABASE ...

    CREATE TABLE ...

    CREATE TRIGGER ...

    CREATE TRIGGER ...

    GO

  • S dng script

    Script l mt tp tin c phn m rng l .sql, c ni dung l cc lnh T-SQL, c to bi bt k mt Text editor no.

    c thc hin trong cng c SQL Query Analyzer hoc osql Utility

    c dng li khi cn.

  • Dng Transactions

    c x l ging mt Batch Bo m tnh ton vn d liu Ton b cc lnh trong transaction s thnh cng hoc khng

    thnh cng Mt transaction c th c nhiu batch Transaction c bt u bng lnh BEGIN TRANSACTION V kt thc bng lnh COMMIT TRANSACTION Hoc ROLLBACK TRANSACTION

  • V d transaction trong database QLVT

    BEGIN TRANSACTION insert into chitiethoadon values ('hd001','vt03',50,null,30000) IF @@ERROR 0 BEGIN RAISERROR ('Transaction not completed.', 16, -1) ROLLBACK TRANSACTION END update vattu set slton = slton-50 where mavt='vt03' IF @@ERROR 0 BEGIN RAISERROR ('Transaction not completed.', 16, -1) ROLLBACK TRANSACTION END COMMIT TRANSACTION

  • Dng XML

    Cho php Client Browser nh dng d liu:Dng mnh FOR XML trong lnh SELECT tr kt qu dng XML

    Dng FOR XML AUTO

    Hoc FOR XML RAW

    Khi dng mnh FOR XML trong lnh SELECT, ta khng th dng: Lnh SELECT lng nhau

    Mnh INTO .

    Mnh COMPUTE BY.

    Dng Stored procedures m c gi trong lnh INSERT

    nh ngha view hoc user-defined function tr v mt rowset.

  • V d dng XML (1) Use QLVT

    SELECT makh, tenkh FROM khachhang

    FOR XML AUTO

  • Dng XML (2) Use QLVT

    SELECT makh, tenkh FROM khachhang

    FOR XML RAW

  • Dng database QLVT Vit mt on m lnh cho bit tng tr gi ca tt c cc ho

    n ca khch hng c m l KH01 trong nm 2000 vi kt qu tr v

    Khch hng KH01 c tng tr gi cc ho n l

    Nu Khch hng khng c ho n no th in ra chui:

    Khch hng ny khng mua hng trong nm 2000

    declare @tg int

    select @tg=sum(sl*giaban)

    from chitiethoadon as cthd, hoadon as hd

    where cthd.mahd = hd.mahd and hd.makh='kh01 and year(ngay)=2000

    if @tg>0

    print 'Khach hang kh01 co tong tri gia ' + str(@tg,10)

    else

    print 'Khach hang chua mua hang'

  • Dng database QLDIEM

    Lit k danh sch cc sinh vin gm cc thng tin: MASV, HOTEN, NGAYSINH, PHAI (NU hoc NAM) ca nhng sinh vin c tui ln hn hoc bng 20.

  • Khai bo mt bin n cha s lng cc chi tiet ho n c trong table cthd ca ho n hd001. Nu n=0 th xo ho n c m l hd001 trong table ho n, ngc li th xut ra thng bo li Hoa don nay khong xoa duoc

  • Hy thc hin cc lnh xo mt ho n c m hd l hd001. nu ho n hd001 c chi tit ho n th phi xo cc chi tit ho n ca hd ny trc. Cc lnh ny phi hon thnh hon ton.

  • Ly ra danh sch cc ho n c tng tr gi ln nht

    Ly ra cc khch hng mua nhng mt hng m khch hng kh01 mua.

  • Tnh s lng ho n ca 2 khch hng KH01 v KH02 v in ra kt qu so snh 2 s lng ho n ny

  • Stored Procedure

  • Mc tiu bi hc

    Hiu c stored procedure l g, procedure hot ng nh th no.

    Qun l procedure: To, xo, sa v thc thi

    Tham s trong store procedure

    Bi tp p dng

  • Ni dung bi hc

    1. Gii thiu Stored procedures

    2. To, thc thi, cp nht v xo stored procedures

    3. Bi tp thc hnh

    4. Truyn tham s trong stored procedures

    5. iu khin li

    6. Mt s lu

  • Gii thiu Stored Procedure (1)

    Stored procedure l mt tp cc lnh Transact SQL c t tn v lu tr trong database server

    C th nhn tham s vo v tham s tr gi tr v

    Tr v trng thi thc thi ca procedure l thnh cng hay khng thnh cng

  • Gii thiu Stored Procedure (2)

    C 5 loi stored procedure: System (sp_): c trong master database, c truy xut t bt k

    mt database no, nhm cung cp cc thng tin system catalog hoc thc hin cc nhim v ca administration.

    Local : c to t user

    Temporary: c tn bt u bng # (local) hoc ## (global). Khng cn tn ti sau khi SQL Server shutdown

    Remote: gii hn vic thc hin mt stored procedure trn remote SQL Server

    Extended (xp_) c implement bi cc ngn ng khc v c gi l cc DLL. Sau khi vit xong extended stored procedure, sysadmin ng k extended stored procedure vi SQL Server v sau gn quyn cho users khc thc hin. Extended stored procedures ch c c trong master database.

  • X l Stored procedure (1)_Initial

    Delayed Name Resolution: cho php stored procedure tham chiu n cc i tng cha tn ti trong lc procedure c to. Delayed Name resolution c thc hin trong lc procedure c thc hin

    Creation: Cc lnh trong procedure s c phn tch c php theo c php ca T-SQL. Nu thnh cng, tn ca stored procedure c lu trong SysObjects table, cn text ca procedure lu trong SysComments.

    Execution: Khi ln th nht m procedure c thc hin hoc khi procedure phi recompile, query processor s c procedure trong process c gi l resolution.

    Sau giai on resolution, SQL Server s to ra mt s thc hin v t s ny trong procedure cache

  • X l stored procedure (2)_ Subsequent

  • Li ch ca stored procedure

    Cho php lp trnh theo hng modular (modular programming)

    Thc thi nhanh hn, gim c vic chim dng ng truyn mng

    Bo mt.

    X l cc chc nng v chia s vi cc ng dng khc

  • C php to procedure

    CREATE PROCEDURE procedure_name [ { @parameter data_type } [ VARYING ] [ = default ] [ OUTPUT ] ] [ ,...n ]

    [ WITH { RECOMPILE | ENCRYPTION | RECOMPILE ,

    ENCRYPTION } ] AS

    sql_statement [ ...n ]

    procedure_name: tn stored procedure

    @parameter: tham s, c ti a 2.100 parameters trong mt rpocedure data_type : kiu d liu ca

    tham s, bao gm tt c kiu d liu trong SQL Server.

    VARYING: ch nh kt qu ca tham s tr v l mt result set. Ch c p dng cho cursor parameters.

    default: gi tr mc nhin, nu tham s c gi tr mc nhin th khi thc hin procedure, c th user khng cn truyn tham s vo khi thc thi

    OUTPUT : ch nh rng y l output parameter

    RECOMILE: procedure s c dch li mi khi thc thi

    ENCRYPTION: m ho m lnh ca lnh create procedure khi lu vo table syscomment

  • V d: CSDL Northwind

    To procedure P1 lit k danh sch tt c cc products

    Create procedure

    To procedure P2 cp nht ga cho cc sn phm tng 10%

    Create procedure

  • Lu

    C th tham chiu n cc tables, view, procedure khc cng nh cc temporary table

    to mt procedure, user phi c quyn CREATE PROCEDURE (sysadmin, hoc database owner)

    Kch thc ca procedure ti a l 128 MB

    C th lng 32 cp procedure

    Dng procedure sp_helptext hin th ni dung text ca stored procedure m user to

    Khng th kt hp lnh create procedure vi cc lnh SQL khc to thnh mt b lnh (batch)

    Ch c th to procedure trong database hin hnh.

  • Thc thi procedure

    Lnh thc thi mt stored procedure:

    EXECUTE

    [ @return_status = ] procedure_name

    [ [ @parameter = ] { value | @variable

    [ OUTPUT ] | [ DEFAULT ] ]

    [ ,...n ]

    [ WITH RECOMPILE ]

    Ch nh rng ly gi tr tr v ca tham s

    Ch nh rng ly gi tr default ca tham s

    Ch nh rng procedure phi recompile trc khi thc hin

  • V d Thc thi procedure P1 v P2:

    Execute P1

    go

    Execute P2

    go

  • V d 2:

    Create procedure Mexico_Customers

    as

    select * from customers

    where country=Mexico

    go

    Execute Mexico_customers

  • Procedure c tham s create proc CustomerListOfCountry

    @country varchar(40)

    as

    select customerid, CompanyName from customers where country=@country

    go

    execute CustomerListOfCountry Canada

    Hoc truyn tham s vi gi tr khc

    execute CustomerListOfCountry USA

    Nu khng truyn tham s:

    Execute CustomerListOfCountry ????????

  • Procedure c tham s c gi tr default

    create proc CustomerList @country varchar(40)='canada'

    as

    select customerid, CompanyName from customers where country=@country

    go

    Gi thc thi c : execute CustomerList Mexico

    Gi thc thi khng truyn tham s:

    Execute CustomerList

  • Procedure dng output parameter To Procedure tr v s lng khch hng c gi tr country l

    tham s truyn vo:

    create proc P2

    @country varchar(40) = '%', @total integer OUTPUT

    AS

    SELECT @total = count(*) FROM customers WHERE country like @country

    Go

    Thc thi procedure P2

    declare @sluong integer

    Execute P2 'canada', @sluong output

    SELECT 'The total customers of canada is ' +str(@sluong,4)

    go

  • Tham s c kiu l cursor

    Ch dng cho tham s OUTPUT.

    Nu kiu ca tham s l cursor th VARYING v OUTPUT l bt buc.

    Nu VARYING c ch nh cho mt tham s th kiu d liu ca tham s phi l cursor v t kho OUTPUT phi c ch nh.

  • Kiu d liu Cursor (1)

    c dng trong procedure hoc trigger

    Cha result set column, record

    X l cursor: Khai bo bin kiu cursor cha d liu tr v

    Kt hp cursor vi cu lnh select bng lnh DECLARE CURSOR

    Dng lnh OPEN m cursor

    Dng lnh FETCH INTO mt record hin hnh vo cc bin tng ng vi tng column.

    Dng lnh CLOSE ng cursor

  • Kiu d liu Cursor (2)

    sp_cursor_list ly ra danh sch cc cursor hin c

    sp_describe_cursor, sp_describe_cursor_column v sp_describe_cursor_tables xem c tnh ca cursor

    Sau khi cursor m, hm @@CURSOR_ROWS tra v s lng record

    Sau lnh FETCH, hm @@FETCH_STATUS phn nh trng thi fetch sau cng (0,-1)

  • System stored procedure Description

    sp_cursor_list Returns a list of cursors currently visible on the connection and their attributes.

    sp_describe_cursor Describes the attributes of a cursor, such as whether it is a forward-only or scrolling 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.

  • 75

    SCROLL: Cursor c th di chuyn hai chiu

    Local: Bin c phm vi local

    C php khai bo cursor

    DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] FOR select_statement [ FOR UPDATE [ OF column_name [ ,...n ] ] ]

    Cursor_name: tn bin cursor

    Global: Bin c phm vi Global, c th truy xut trong bt k procedure hoc b lnh no

    FORWARD_ONLY: Cursor ch di chuyn mt chiu t dng u n dng cui

    Static: nh ngha mt cursor l static

    DYNAMIC: nh ngha mt cursor phn nh tt c cc thay i ca d liu trong result set.

    FAST_FORWARD: ch nh FORWARD_ONLY, READ_ONLY cursor. FAST_FORWARD khng th c ch nh vi SCROLL hoc FOR_UPDATE

    KEYSET: cc thnh phn v th t cc dng trong cursor c nh khi cursor c m. Tp cc kho trong cursor c lu trong mt table trong database tempdb gi l keyset.

    READ_ONLY: khng cho php cp nht thng qua cursor

    OPTIMISTIC: SQL Server khng lock cc dng nu nh chng c c vo cursor.

    FOR UPDATE [OF column_name [,...n]]: nh ngha cc ct c th cp nht trong cursor.

    SCROLL_LOCKS: kho cc d liu m c c vo cursor

  • V d 1

    DECLARE customer_cursor CURSOR

    FOR SELECT * FROM customers

    OPEN customer_cursor -- m cursor

    FETCH NEXT FROM customer_cursor

  • V d 2 (1)

    DECLARE @customerId varchar(11), @CompanyName varchar(30), @message varchar(80)

    PRINT "-------- Customer report --------

    DECLARE customer_cursor CURSOR

    FOR SELECT customerid, companyName FROM customers WHERE country = "USA"

    OPEN customer_cursor

    FETCH NEXT FROM customer_cursor INTO @customerid, @companyName

  • V d 2 (2) While @@FETCH_STATUS = 0

    begin

    print Customer ID: + @customerID

    print Company Name: + @companyName

    Fecth next from customer_cursor into @customerid, @companyName

    end

    Close customer_cursor

    Deallocate customer_cursor

    go

  • S dng OUTPUT cursor parameter USE northwind

    CREATE PROCEDURE customer_cursor @customer_cursor CURSOR VARYING OUTPUT AS

    SET @customer_cursor = CURSOR FORWARD_ONLY STATIC

    FOR

    SELECT * FROM CUSTOMERS

    OPEN @customer_cursor

    GO

  • S dng tham s cursor tr v

    DECLARE @MyCursor CURSOR

    EXEC customer_cursor @customer_cursor = @MyCursor OUTPUT

    WHILE (@@FETCH_STATUS = 0)

    BEGIN

    FETCH NEXT FROM @MyCursor

    END

    CLOSE @MyCursor

    DEALLOCATE @MyCursor

  • Bi tp ng dng To procedure v thc thi in ra company name

    c s lng orders nhiu nht

    To proc p1 tr v doanh thu ca nm truyn vo, nu user khng truyn ngy vo th ly nm hin hnh

    Khai bo mt procedure CustomersOfCountryCursor ly ra mt cursor cha cc record ca table customers c country bng gi tr truyn vo. Thc thi CustomersOfCountryCursor v in ra cc d liu c trong cursor tr v.

  • Bi tp p dng (database QLVT)

    1. To procedure P1 ly ra danh sch cc ho n gm cc thng tin: MAHD, NGAY, TENKH, TONGTG

    2. To procedure P2 xo cc chi tit ho n ca ho n c m l tham s truyn vo

    3. To procedure P3 tnh tng doanh thu ca nm vi nm l tham s truyn vo v tr v gi tr l tng doanh thu tnh c.

  • Tm tt ni dung bui hc

    Stored procedure trong SQL Server ging procedure trong cc ngn ng lp trnh

    X l nhanh hn batch

    Procedure c th c cc tham s input v output

    thc thi mt stored procedure dng lnh execute

    Q & A

  • To proc ly ra danh sch khch hang c da ch l tham s truyn vo:

    CREATE PROC P2 @DC VARCHAR(50)

    AS

    select * from khachhang where diachi=@dc

  • Create proc P1

    As

    Select hd.mahd, tenkh, ngay, sum(sl*giaban) as tongtg

    From hoadon hd, khachhang kh, chitiethoadon cthd

    Where (hd.mahd=cthd.mahd) and

    (kh.makh = hd.makh)

    Group by hd.mahd, tenkh, ngay

  • Create proc p2 @mahd nvarchar(10)

    As

    delete * from chitiethoadon where mahd=@mahd

    Go

    -- thuc thi

    Exec p2 hd002

    go

  • Create proc p3 @nam int, @dt int OUTPUT

    As

    select @dt=sum(sl*giaban)

    From chitiethoadon cthd, hoadon hd

    Where (hd.mahd=cthd.mahd) AND

    year(ngay)= @nam

    Go

    Declare @dt int

    Exec p3 2000,@dt OUTPUT

    Print Doanh thu nam 2000 la + str(@dt,8)

  • Trong QLVT To procedure ly ra tn ca cc khch hng

    mua hng trong thng . V nm .. (tham s input). Danh sch ny c tr v trong mt kiu cursor.

    Thc thi P4 ly ra danh sch cc khch hng ca thng 6 nm 2000 v in ra tn ca cc khch hng .

  • Trong NorthWind Khai bo mt procedure CustomersOfCountryCursor

    ly ra mt cursor cha cc record ca table customers c country bng gi tr truyn vo. Thc thi CustomersOfCountryCursor v in ra cc d liu c trong cursor tr v.

  • TRIGGER Sau bi hc ny, sinh vin c th: Hiu c trigger l g, cng dng ca n To trigger Xo trigger Thay i trigger

  • Ni dung

    1. Trigger l g ?

    2. Khi no ta cn s dng Trigger

    3. c im ca Trigger

    4. To Mt Trigger nh th no?

    5. Cc v d Trigger

    6. Cc lu

  • Trigger l g ? Trigger l mt stored procedure c bit c gi t ng khi

    user cp nht d liu trn mt table

    c kt hp vi table: c nh ngha trn mt table c th .

    c gi t ng: Khi c mt thao tc cp cht d liu trn table (insert, update, hoc delete) th trigger ca thao tc tng ng c t ng thc hin.

    Khc vi procedure, trigger khng th c gi trc tip, khng nhn tham s

    L mt phn ca transaction: nhng lnh trong trigger c xem l mt single transaction, c th c roll back t bt k ch no trong trigger

  • Khi no ta cn s dng trigger Ta ch s dng trigger khi m cc bin php bo m data

    intergrity khc nh Constraints khng th tha mn yu cu ca ng dng.

    Thc hin cascade updates v cascade deletes qua cc table quan h trong database

    p buc tnh ton vn d liu phc tp: Thc hin cc rng buc c tham chiu n cc column trong nhiu table.

    nh ngha Custom Error Messages: Dng trigger tr v cc chui thng bo trng thi ca mt hng ng no .

    Bo tr cc d liu khng c chun ho:!

  • c im ca Trigger

    Trigger c thc hin t ng sau khi lnh INSERT, UPDATE, hoc DELETE c thc hin trn mt table m trigger c nh ngha. Cn cc constraints v INSTEAD OF trigger s c kim tra trc khi lnh INSERT, UPDATE, hoc DELETE thc hin.

    Constraints s c kim tra trc trigger. Mt table c th c nhiu Triggers cho mt action. Mt trigger

    c th c nh ngha cho nhiu action.

  • c im ca Trigger

    Khi c nhiu trigger trong mt table, th table owner c th dng procedure h thng sp_settriggerorder ch nh trigger u v trigger cui thc thi. Th t ca cc trigger cn li khng th sp xp c.

    User phi c quyn thc hin tt c cc lnh m c nh

    ngha trong Triggers Table Owners khng th to ra cc Triggers trn Views hoc

    Temporary Tables nhng c th tham chiu n view v temporary.

  • c im ca Trigger

    Triggers khng tr kt qu v.

    Triggers c th iu khin multi-row actions: mt hnh ng INSERT, UPDATE, hoc DELETE gi mt trigger c th nh hng ln nhiu dng d liu, Ta c th chn: X l tt c cc dng cng vi nhau trong trng hp cc

    dng nh hng phi tho iu kin ca trigger.

    X l tng dng tha iu kin.

  • Logic tables

    Khi c action Insert, table logic inserted sinh ra, c cu trc ging vi cu trc table c insert, c d liu l record ang c insert

    Khi co action delete, table deleted sinh ra, c cu trc ging vi cu trc table b deleted, c d liu l record ang b xo

    Khi c action update, c 2 table inserted v deleted

  • To trigger CREATE TRIGGER trigger_name

    ON { table | view } [ WITH ENCRYPTION ] { {{ FOR | AFTER | INSTEAD OF }

    { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE] } [ WITH APPEND ]

    AS [ { IF UPDATE ( column ) [ { AND | OR } UPDATE ( column ) ] [ ...n ] } ] sql_statement [ ...n ] } }

  • Tham s (1)

    Table | view : tn view/table m trigger c thc hin khi c action tng ng.

    WITH ENCRYPTION: m ho nt dung text ca lnh create trigger trong table syscomments.

    AFTER: Trigger s c gi ch khi tt c cc hnh ng thc hin xong. Cc kin tra constrain v cascade s c kim tra hon thnh trc khi trigger thc hin. Default l AFTER nu ch c t kho FOR c ch nh. AFTER trigger khng th nh ngha trn view.

    INSTEAD OF: ch nh trigger oc thc hin thay cho action ca trigger. INSTEAD OF triggers khng cho php cp nht d liu trn view c WITH CHECK OPTION.

  • Tham s (2)

    { [DELETE] [,] [INSERT] [,] [UPDATE] } : ch nh action gn vi trigger. i vi INSTEAD OF triggers, action DELETE khng cho php trn table m c relationship m ch nh CASCADE ON DELETE. Tng t, action UPDATE khng cho php trn table c relationships m CASCADE ON UPDATE.

    Table deleted v inserted l logical tables. Chng c cu trc ging vi table m trigger c nh ngha, cha cc dng gi tr c hoc mi m c th thay i bi action ca user. Ta c truy xut d liu trong 2 table ny trong nh ngha trigger.

  • Tham s (3)

    Cc gi tr kiu text, ntext, hoc image trong table inserted v deleted khng truy xut c.

    Khi trigger mc 65, gi tr null s c tr v ct c kiu text, ntext, hoc image trong table inserted hoc deleted nu ct cho php null; chui zero-length c tr v nu ct c th null.

    IF UPDATE (column): kim tra action update trn ct c ch nh, khgn dng cho action delete.

    With Append: Chn thm trigger ny vo cc trigger c trc

  • V d

    Use Northwind GO CREATE TRIGGER Empl_Delete ON Employees FOR DELETE AS IF (SELECT COUNT(*) FROM Deleted) > 1 BEGIN RAISERROR( 'You cannot delete more than one employee at a time.', 16, 1) ROLLBACK TRANSACTION END

  • Nhng lnh sau y khng c dng trong nh ngha trigger

  • V d (1) USE pubs IF EXISTS (SELECT name FROM sysobjects WHERE name =

    'reminder' AND type = 'TR') DROP TRIGGER reminder GO CREATE TRIGGER reminder ON titles FOR INSERT, UPDATE AS RAISERROR (50009, 16, 10) GO

  • Alter trigger ALTER TRIGGER trigger_name ON table [WITH ENCRYPTION] {{FOR {[,] [DELETE] [,] [UPDATE] [,][INSERT]} AS sql_statement [...n] } | {FOR {[,] [INSERT] [,] [UPDATE]} AS IF UPDATE (column) [{AND | OR} UPDATE (column) [,...n]] sql_statement [...n] } }

  • Xo trigger DROP TRIGGER trigger_name

  • Bi tp p dng (QLVT) To trigger khi insert mt record vo trong table

    CHITIETHOADON, th cp nht li SLTON ca vt t trong table VATTU

    To trigger khng cho php mt ho n c nhiu hn 4 chi tit ho n

    To trigger khng cho php hai vt t trng tn

    To trigger khng cho php xo cng lc nhiu hn mt khch hng

  • To trigger khng cho php xo mt vt t m c t nht mt chi tit ho n ca vt t .

    To trigger kim tra s lng bn ra ca mt vt t phi nh hn s lng tn trong kho

  • create trigger t1

    on chitiethoadon1

    for insert

    as

    declare @sl int, @mavt varchar(10)

    select @sl = sl, @mavt = mavt from inserted

    update vattu1 set slt=slt- @sl where mavt =@mavt