1. Trang chủ
  2. » Công Nghệ Thông Tin

Views Functions Stored Procedures

88 490 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 88
Dung lượng 2,05 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Batch Batch Processing Views User defined Function Cursors StoreProcedures TriggersIntroduction to SQL BatchProcessingBatchIndividual SQLcommandsGrouped to form abatchCompiledas singleexecutionplanExampleReviewDeclare variableList of global variablesCONNECTIONS Number of connections made to theserver since it was last started.CPU_BUSY Number of milliseconds the system hasbeen processing since SQL Server wasstartedCURSOR_ROWS Number of rows in the most recentlyopened cursor.ERROR Error number of the last TSQL errorFETCH_STATUS 0 if the last fetch status was successful.1 if there was an error

Trang 1

Views – Functions- Stored Procedures

1

GV: Nguyễn Thị Cẩm Hương

Trang 3

Compiled

as single execution plan

Trang 4

Example

Trang 5

Review Declare variable

Trang 6

List of global variables

@@CONNECTIONS Number of connections made to the

server since it was last started.

@@CPU_BUSY Number of milliseconds the system has

been processing since SQL Server was started

@@CURSOR_ROWS Number of rows in the most recently

opened cursor.

@@ERROR Error number of the last T-SQL error

@@FETCH_STATUS 0 if the last fetch status was successful.

-1 if there was an error

Trang 7

List of global variables (2)

@@IDENTITY Last inserted identity value

@@LANGUAGE Name of the language currently in use.

@@MAX_CONNECTIONS Maximum number of concurrent

connections that can be made.

@@ROWCOUNT Number of rows affected by most

recent SQL Statement

@@SERVERNAME Name of local server

@@SERVICENAME Name of the SQL Service on this

computer

@@TIMETICKS Number of microseconds per tick on

the current computer

@@TRANSCOUNT Number of transaction open on the

current connection

@@VERSION Version information of SQL Server

Trang 8

Control Statements

Trang 9

Control Statements

Control Keyword Purpose

Trang 10

A set of TSQL statements to be executed can be enclosed in BEGIN END

Syntax:

Trang 11

We can execute different sets of SQL statements based on specified conditions

Syntax:

Trang 12

Example

Trang 13

WHILE statement

We can execute a SQL statement or a block

of statements based on some condition

Syntax:

Trang 14

Example

Trang 15

BREAK & CONTINUE - Example

Trang 16

RETURN: We can use RETURN at any point to exit from a block, procedure Statements after the RETURN statement are not executed

Syntax:

RETURN [ integer_expression ]

Trang 18

Example

Trang 19

Multi -column updates using CASE

Trang 21

GOTO example

Trang 22

WAITFOR

Trang 23

Implementing Views

 Definition and Advantages of Views

 Creating and Altering Views

 Using Views

 Partitioned Views

Trang 24

Definition and Advantages of Views

A view is essentially a named SELECT statement.

 It acts as a table, but does not contain any data

 It relies on the data stored in the underlying

table

 Like a table, a view can be queried, and data can

be inserted, deleted, and modified through a

view

Trang 25

Creating and Altering Views

 CREATE VIEW statement

syntax:

CREATE VIEW [<db_name>.][<owner>.]view_name [(column[ , n ])]

[ WITH ENCRYPTION|SCHEMABINDING|VIEW_METADATA}[ , n]] AS

select_statement [ WITH CHECK OPTION ]

 Dropping View: DROP VIEW view_name

Trang 26

Creating and Altering Views

 Altering Views:

ALTER VIEW [<db_name>.][<owner>.]view_name [(column[ , n ])]

[ WITH ENCRYPTION|SCHEMABINDING|VIEW_METADATA}[ , n]] AS

select_statement [ WITH CHECK OPTION ]

sp_rename old_viewname, new_viewname

Verifying Views: sp_helptext

sp_helptext viewname

Trang 27

The SELECT Statement

The SELECT Statement As you can see, a view contains a SELECT

statement and a few parameters, if needed The SELECT statement must follow some restrictions; the SELECT statement cannot:

Contain ORDER BY clause, unless there is a TOP clause in the select list

Contain COMPUTE or COMPUTE BY clauses

Contain the INTO keyword

Reference a temporary table or a table variable

Trang 28

The ENCRYPTION Option

CREATE VIEW vwProducts

EXEC sp_helptext vwProducts

Trang 29

The SCHEMABINDING Option

Trang 30

The WITH CHECK OPTION Option

CREATE VIEW CustomersCAView

SELECT * FROM Customers WHERE state=’CA’

WITH CHECK OPTION

GO

UPDATE CustomersCAView SET state=’OR’ WHERE

CustomerID=’LETSS’

Trang 32

Using Views

 Updating Data

 If the view is based on two or more tables, the UPDATE,

INSERT, and DELETE statements cannot affect more than one table In other words, if the view is based on more than one

table, you cannot run a DELETE statement, and all the columns referenced in the INSERT and UPDATE statements should

belong to the same underlying table.

 You cannot update, insert, or delete data in a view created with the DISTINCT clause.

 You cannot update, insert, or delete data in a view using

grouping functions.

 You cannot update, insert, or delete data in a view if it

contains calculated columns.

 Your insert, update, or delete operation may fail because of

column or table constraint or of column properties.

Trang 33

Partitioned Views

Trang 34

SELECT * FROM

ServerB.MyCompany.dbo.CustomersEurope UNION ALL

SELECT * FROM

ServerC.MyCompany.dbo.CustomersAsia

Trang 35

Partitioned Views

A partitioning column needs to follow some strict rules:

 The column value should be validated by a CHECK

constraint using only the following operators: BETWEEN, AND, OR, <, <=, >, >=, and = Note <> and ! are not allowed

in a CHECK constraint if the column has to be a

partitioning column.

 The column is NOT NULL.

 The column is part of the table primary key.

 The column is not a calculated column.

 Only one CHECK constraint exists on the column.

 Furthermore, the tables need to follow some rules, too

 The table cannot have indexes on computed columns.

Trang 36

Partitioned Views

Create Table KH_BAC

(Makh int, TenKh Nchar(30),

Khuvuc Nvarchar(30) NOT NULL CHECK ( Khuvuc='Bac bo'),

PRIMARY KEY (Makh, Khuvuc)

)

Create Table KH_TRUNG

(Makh int, TenKh Nchar(30),

Khuvuc Nvarchar(30) NOT NULLCHECK ( Khuvuc='Trung bo'),

PRIMARY KEY (Makh, Khuvuc)

)

Create Table KH_NAM

(Makh int, TenKh Nchar(30), Khuvuc Nvarchar(30) NOT NULL CHECK ( Khuvuc='Nam bo'), PRIMARY KEY (Makh, Khuvuc)

)

Trang 38

Partitioned Views

As you have just seen, updates are possible, but there are some

restrictions that exist on INSERT, UPDATE, and DELETE statements.

 INSERT statements are possible only if:

All the columns declared in the views are referenced in the INSERT statement.

The DEFAULT keyword is not allowed in the VALUES

clause This rule and the following one disallow a table from containing a column with an IDENTITY property.

The table does not contain a timestamp column.

The table does not contain reflexive joins.

Trang 39

Partitioned Views

 UPDATE statements are possible only if:

The DEFAULT keyword is not allowed in the SET clause.

The table does not contain a timestamp column.

The table does not contain reflexive joins.

 DELETE statements are possible only if:

The table does not contain reflexive joins.

Trang 41

Definition and Advantages of

User-defined Function

User-defined function (UDF)

 Modular programming capability

Trang 42

Creating and Altering a UDF

 All the functions are created and managed by

 CREATE FUNCTION statement

 ALTER FUNCTION statement

 DROP FUNCTION statement

Trang 43

A scalar UDFs

Trang 44

A scalar UDF

Trang 45

The table-valued UDFs

An inline table-valued UDF:

It can be seen as a view with parameters They

execute one SELECT statement, as in a view, but can include parameters, like a stored

procedure

 The basic syntax is:

Trang 46

The table-valued UDFs

Trang 47

Multi table-valued UDFs

Trang 48

The table-valued UDFs

Trang 49

CREATE TABLE [Order Details] (

OrderID int NOT NULL , ProductID int NOT NULL ,

UnitPrice money NOT NULL DEFAULT (0),

Quantity smallint NOT NULL DEFAULT (1),

Discount real NOT NULL DEFAULT (0),

Total AS dbo.TotalAmount(UnitPrice, Quantity,

Discount))

Trang 51

Load the current row into variables

FETCH

Test for existing rows

EMPTY?

Return to FETCH if rows

found

No

Release the active set

CLOSE Yes

Trang 53

Declare Cursor

Trang 54

Open Cursor

Fetch Cursor

Trang 55

Close Cursor

Deallocate Cursor

Trang 56

Cursor- Example

Trang 57

STORED PROCEDURES

 Definition and Advantages of Stored Procedures

 Creating and Altering a Stored Procedure

 Using Parameters

 Executing a Stored Procedure

 Managing Errors

Trang 58

Definition and Advantages

of Stored Procedures

 A stored procedure is a collection or batch of T-SQL statements and control-of-flow language that is stored under one name, and executed as a single unit

Trang 59

Definition and Advantages

of Stored Procedures

 Stored procedure compilation process

Query (procedure) Parsing Normalizing Optimizing Compiling

Query tree (stored in syscomments) Query plan (stored in cache)

Trang 60

Creating a Stored Procedure

 The CREATE PROCEDURE Statement

CREATE PROC [ EDURE ] procedure_name [ ; number ]

Trang 61

Creating a Stored Procedure

SELECT ProductName, Total=SUM(Quantity)

FROM Products P, [Order Details] OD, Orders O, Customers C WHERE C.CustomerID = @CustomerID

AND C.CustomerID = O.CustomerID AND O.OrderID =

OD.OrderID AND OD.ProductID = P.ProductID

GROUP BY ProductName

Trang 62

Creating a Stored Procedure

 You can use any Transact-SQL statement in a

stored procedure, but some limitations exist

 A stored procedure always ends when the

query processor finds a GO

 ALTER TABLE, CREATE INDEX, CREATE TABLE, All the DBCC statements, DROP TABLE, DROP INDEX, TRUNCATE TABLE, and UPDATE

STATISTICS

Trang 63

Altering a Stored Procedure

WHERE City = @City

END

Trang 64

Dropping a Stored Procedure

 The DROP PROCEDURE Statement Is used to drop a stored procedure from the database

DROP PROCEDURE proc_name

Example:

DROP PROCEDURE CustOrderHist

Trang 65

Using Parameters

 Using Parameters

 Stored procedures is their ability to accept input and output parameters.

 A stored procedure can have up to 2,100

parameters, separated by commas.

 The RETURN statement is another way to return a value from a stored procedure, only one value

integer can be returned with the RETURN

statement.

A parameter declaration has the following syntax:

{@parameter data_type} [= default] [OUTPUT]

Trang 66

RETURN 0 END

ELSE

BEGIN PRINT 'No Records Found for given city' RETURN 1

END END

Trang 67

Using Parameters

 Example 2:

CREATE PROCEDURE prcGetUnitPrice_UnitInStock @ProductID int,

@Unitprice Money OUTPUT, @UnitInStock smallint OUTPUT AS

BEGIN

IF EXISTS (SELECT * FROM Products

WHERE ProductID = @ProductID) BEGIN

SELECT @Unitprice=Unitprice,@UnitsInStock=UnitInStock FROM Products

WHERE ProductID=@ProductID RETURN 0

END ELSE RETURN 1 END

Trang 68

Executing a Stored Procedure

 A stored procedure can be executed from a client program, another stored procedure, or directly from a Transact-SQL batch.

Trang 69

Executing a Stored Procedure

Example 2:

CREATE PROCEDURE prcDisplayUnitPrice_UnitsInStock @ProductID int AS

BEGIN

DECLARE @UnitPrice Money, @UnitsInStock smallint

DECLARE @ReturnValue Tinyint

EXEC @ReturnValue = prcGetUnitPrice_UnitInStock @ProductID,

@UnitPrice output, @UnitsInStock output

IF (@ReturnValue = 0)

BEGIN PRINT 'The Status for product: '+ Convert(char(10),

@ProductID) PRINT 'Unit price : ' + CONVERT( char(10), @Unitprice)

PRINT 'Current Units In Stock:' + CONVERT (char(10),

@UnitsInStock) END

ELSE PRINT 'No records for the given productID ' + Convert(char(10),

@ProductID) END

Trang 70

Executing a Stored Procedure

Example:

EXECUTE prcDisplayUnitPrice_UnitsInStock 1222

GO

EXECUTE prcDisplayUnitPrice_UnitsInStock 1

Trang 71

Managing Errors

 No system is perfect Errors happen all the time all errors are not equal from a SQL Server point of view Some errors cause general failure of the server, while others just stop the statement or warn the user An error is composed of many parts:

An error number.

 An error message indicating the apparent cause of the error.

A severity level indicating the kind of problem encountered There are

25 levels of severity:

Severity Level Used to Indicate

0 or 10 Errors in information entered by the user These message are

considered information

11 through 16 Errors that can be corrected by the user.

17 Insufficient resources (such as locks or disk space)

18 Nonfatal internal errors These errors usually indicate an internal

software problem.

19 That an internal non-configurable limit in SQL Server was exceeded.

20 through 25 Fatal errors

Trang 72

Creating and Using Custom Error Messages

 Creating Custom Error Messages

sp_addmessage [ @msgnum = ] msg_id , [ @severity = ] severity ,

[ @msgtext = ] 'msg' [ , [ @lang = ] 'language' ] [ , [ @with_log = ] 'with_log' ] [ , [ @replace = ] 'replace' ]

 Using Custom Error Messages

RAISERROR ( { msg_id | msg_str } { , severity , state

}

[ , argument [ , n ] ] ) [WITH LOG]

 Deleting Custom Error Messages

sp_dropmessage [ @msgnum = ] message_number [ , [ @lang = ] 'language' ]

Trang 73

Creating and Using Custom Error Messages

EXEC sp_addmessage @msgnum = 50100, @severity = 16,

@msgtext = N'The Product with the Product_id %d does not exist'

EXEC sp_addmessage @msgnum = 50101, @severity = 10,

@msgtext = N'The Supplier with the Suplierid %s does not

Server: Msg 50101, Level 16, State 1, Line 1

The Supplier with the Suplierid CDCN4 does not exist

Trang 74

Creating and Using Custom Error Messages

Trang 75

IMPLEMENTING TRIGGER

 Definition and Advantages of trigger

 Creating and Altering a trigger

Trang 76

Definition and Advantages of trigger

A trigger is a block of code that constitutes a set of

T-SQL statements that are activated in response to certain actions A trigger can be used to maintain data integrity

 It prevents incorrect, unauthorized or

inconsistent changes in data

 It cannot return data to the user

Trang 77

Definition and Advantages of trigger

 Two types of triggers exist:

 AFTER triggers that run after the statements that fired them

 INSTEAD OF triggers that run instead of

statements that fired them

 All the Triggers are created and managed by

 CREATE TRIGGER statement

 ALTER TRIGGER statement

 DROP TRIGGER statement

Trang 78

Creating triggers

 Creating triggers

CREATE TRIGGER trigger_name

ON table [WITH ENCRYPTION]

{FOR | AFTER| INSTEAD OF}

 Triggers can be nested up to 32 levels

Trang 79

The inserted table contains a copy of all records

that are inserted in the trigger table

The deleted table contains all records that have

been deleted from the trigger table

 Whenever any updation takes place, the trigger uses both the inserted and the deleted tables

Trang 80

AFTER TRIGGERS

The INSERT Trigger:

 An INSERT trigger is fired whenever an attempt

is made to insert a row in the trigger table

 When an INSERT statement is issued, a newrow is added to both the trigger and theinserted tables

Inserted

Table

Trang 81

AFTER TRIGGERS

Example:

CREATE TRIGGER NGAYLAP_NGAYGIAO

ON Hoadon AFTER INSERT

Trang 82

-AFTER TRIGGERS

 DELETE trigger

 A DELETE trigger is fired whenever an attempt

is made to delete rows from the trigger table

 There are three ways of implementing

referential integrity using a DELETE trigger

These are:

 The Restrict method

Trang 83

 The DELETE trigger process

DELETED FROM HoaDon WHERE MaHD=1003

DELETED Table

DELETED Trigger

Trang 84

 The UPDATE trigger: This trigger is fired whenever there

is a modification to the trigger table

UPDATED HoaDon SET MaKH=‘TH3’ WHERE MaHD=1003UPDATED Trigger

MaHD NgayLapHD LoaiHD NoiChuyen NgayGiao MaKH

1003 01/01/2004 N Tp HCM 03/03/2004 CDCN4

DELETED Table

INSERTED Table

Trang 85

INSTEAD OF TRIGGERS

 The INSTEAD OF INSERT Trigger: Like the AFTER

trigger, the INSTEAD OF trigger works with the

Inserted table But the logic is a little bit different:

1 The user or the system runs an INSERT statement.

2 If the record does not violate any constraint, it is

inserted only in the Inserted table (not in the base table).

3 The trigger fires and performs any necessary action.

Trang 86

Example:

CREATE TRIGGER Xoa_HD

ON Hoadon INSTEAD OF DELETE

ON hd.MaHD=d.Mahd) DELETE HOADON

WHERE MAHD IN (SELECT MAHD FROM DELETED)

RAISERROR('Cac chi tiet HD da bi xoa',10,1)

END

SET NOCOUNT

ON -DELETE HoaDon WHERE MaHD=1003

Trang 87

INSTEAD OF TRIGGERS

 Example: tests the quantity of a product in stock

before accepting an order

CREATE TRIGGER InsOrdDet ON [Order Details]

INSTEAD OF INSERT

AS

DECLARE @qty int

SELECT @qty=quantity FROM Inserted

IF @qty<= (SELECT UnitsInStock FROM Products P

JOIN Inserted I ON P.ProductID = I.ProductID)

INSERT INTO [Order Details]

SELECT * FROM Inserted

ELSE

RAISERROR(‘Not enough products in stock’, 16, 1)

Ngày đăng: 06/12/2016, 12:12

TỪ KHÓA LIÊN QUAN

w