Click here to load reader

Assertions, Views and Programming Techniques

  • Upload
    bairn

  • View
    64

  • Download
    0

Embed Size (px)

DESCRIPTION

Chapter 9. Assertions, Views and Programming Techniques. Constraints as assertions. In SQL, users can specify general constraints via declarative assertions , using the CREATE ASSERTION statement of the DDL (data definition language). - PowerPoint PPT Presentation

Citation preview

Data Modeling Using the Entity-Relationship (ER) Model

Chapter 9Assertions, Viewsand Programming TechniquesConstraints as assertionsIn SQL, users can specify general constraints via declarative assertions, using the CREATE ASSERTION statement of the DDL (data definition language). Each assertion is given a constraint name and is specified via a condition similar to the WHERE clause of an SQL query.Syntax: CREATE ASSERTION CHECK (search condition) []Constraints as assertionsExample:CREATE ASSERTION SALARY_CONSTRAINTCHECK (NOT EXISTS ( SELECT *FROM Employee E, employee M, department DWHERE E.SALARY>M.SALARY AND E.DNO=D.DNUMBER AND D.MGRSSN=M.SSN ) ); (reference page 256)Constraints as assertionsSpecify a query that violates (vi phm) the condition; include inside a NOT EXISTS clauseQuery result must be empty if the query result is not empty, the assertion has been violated

SQL TriggersObjective: to monitor a database and take action when a condition occurs.Triggers are expressed in a syntax similar to assertions and include the following:Event (e.g., an update operation)ConditionAction (to be taken when the condition is satisfied)

5SQL TriggersA trigger to compare an employees salary to his/her supervisor during insert or update operations:

CREATE TRIGGER INFORM_SUPERVISORBEFORE INSERT OR UPDATE OF SALARY, SUPERVISOR_SSN ON EMPLOYEE FOR EACH ROW WHEN(NEW.SALARY> (SELECT SALARY FROM EMPLOYEE WHERE SSN=NEW.SUPERVISOR_SSN))INFORM_SUPERVISOR (NEW.SUPERVISOR_SSN,NEW.SSN;Views (virtual tables) in SQLConcept of a View: A view is a single table that is derived from other tables. These other tables could be base tables or previously defined views. A view does not necessarily exist in physical form, it is considered a virtual tableAllows for limited update operations.Allows full query operations.A convenience (thun li) for expressing certain operations

l mt bng o m ni dung c nh ngha bi mt cu select, view cng bao gm cc ct v cc dng d liu, nhng khng l ni lu tr d liu, cc dng v ct d liu c tham chiu t cc bng khi nh ngha viewChc nng ca view: Ch cho user xem nhng g cn xemn gin ho vic truy cp d liuChn d liu cn thit ng vi mi user, m bo an ton d liuDng Import v exportView l mt i tng ca CSDL

7Views (virtual tables) in SQLSpecification of Views:

Example:

CREATE VIEW view_name [(column[ ,...n ])]AS select_statement [ WITH CHECK OPTION ]CREATE VIEW WORKS_ON1AS SELECT FNAME, LNAME, PNAME, HOURSFROM EMPLOYEE, PROJECT, WORKS_ONWHERE SSN=ESSN AND PNO=PNUMBER;Column: tn ct c dng trong trng hp ct c pht sinh t mt biu thc, hmSelect_statement: cu lnh select dng nh ngha viewWith check option: buc cc lnh sa i d liu trn view phi s dng tp iu kin bn trong cu lnh select nh ngha view8Views (virtual tables) in SQLExample:CREATE VIEW DEPTJNFO(DEPT_NAME,NO_OF_EMPS,TOTAL_SAL)AS SELECT DNAME, COUNT (*), SUM (SALARY)FROM DEPARTMENT, EMPLOYEEWHERE DNUMBER=DNOGROUP BY DNAME;Views (virtual tables) in SQLExample: Specify a different WORKS_ON table

CREATE TABLE WORKS_ON_NEW ASSELECT FNAME, LNAME, PNAME, HOURSFROM EMPLOYEE, PROJECT, WORKS_ON WHERE SSN=ESSN AND PNO=PNUMBERGROUP BY PNAME;

Cu lnh select trong view khng c cha:Mnh ORDER BYMnh COMPUTE V COMPUTE BYCc bng tm khng c tham chiu trong view khng dng select Into trong viewCc trigger v ch mc khng c to ra trn view

10Views (virtual tables) in SQLDELETE VIEW:DROP VIEW view_nameRENAME Views: sp_rename old_viewname, new_viewnameCHECK VIEW:sp_helptext viewnameMODIFY VIEW :ALTER VIEW view_name (column_list)AS select_statementProgramming TechniquesApproaches to Database Programming: Several techniques exist for including database interactions in application programs. The programs include variable, statement SQL, control structure. The basic concept:IdentifiersBatch (tp cc cu lnh T-SQL lin tip kt thc bng lnh GO)Script (tp ca 1 hoc nhiu batch c lu thnh mt tp tin .SQL)

Programming TechniquesData type: have two typeSystem - supplied data typeUser- defined data typeReference to object:Server.database.owner.objectVariablesLocal variableDeclare:

Example: DECLARE @EmpIDVar intDECLARE@ VariableName var_typeVariablesAssign value for the variable: When a variable is declared, its value is Null.

Example:DECLARE @temp_name varchar(20)SELECT @temp_name = companynameFROM customersWHERE customerid = adsff

SET @VariableName = expressionorSELECT{@VariableName=expression} [,n]VariablesExample 2:DECLARE @temp_city varchar(10)SET @temp_city = londonSELECT * FROM CustomersWHERE city = @temp_city

VariablesExample 3:

DECLARE @temp_CustID Char(5), @temp_name varchar(50)SET @temp_CustID = ALFKISELECT @temp_name = CompanyName FROM CustomersWhere CustomerID = @temp_CustID PRINT CustomerID is + @temp_CustID + and Name is + @temp_name

VariablesGlobal Variables: is a System function Return value of the function is displayed by statement SELECT @@Variablename.Not assign the value to the global variables.Global variables have no data type.Variable name begins with @@.Some Global Variables: @@SERVERNAME: Server name@@ROWCOUNT: number of rows are affected by the closest statementVariablesExample:Update Employees set LastName = Brooke Where LastName =BrookIf(@@rowcount =0)beginprint No rows were updatedreturnend

Variables@@ERROR: return the index of error@@IDENTITY: return IDENTITY Execution of the SQL statementDynamic SQL statement:

Example:DECLARE @vname varchar(20), @table varchar(20), @vdbase varchar(20)SET @vname="'White'"SET @table='authors'SET @vdbase='pub'EXECUTE ('USE'+@vdbase + 'SELECT * FROM '+ @ vtable + 'WHERE au_lastname=+@vname)

EXEC [USE] ({@string_variable| [ N ] 'tsql_string'} [+ ...n ] ) Execution of the SQL statementBatches: the set of the SQL statement is sent to server and they are executed at the same time.If any statement in the batch has error then SQL server will not execute all statements in the batches.Each batch cannot contain all of these following statements: CREATE PROCEDURE, CREATE TRIGGER, CREATE VIEW, CREATE RULE, CREATE DEFAULT.

Execution of the SQL statementExample:gouse masterif exists(select * from sysdatabases where name like 'sales')drop database salesgocreate database saleson( name = sales_data, filename ='e:\sales_data.mdf', size = 1, maxsize = 5, filegrowth =1)log on ( name = sales_log, filename ='e:\sales_log.ldf', size = 1, maxsize = 2, filegrowth =1)

Execution of the SQL statementTransact-SQL Scripts: A script is a set of the T-SQL statement stored in a file of one or many batches.Transactions: is a work unit with 4 characteristicsAtomicConsistent (nht qun)Isolated (c lp)Durable (bn)Execution of the SQL statementTransaction Structure:BEGIN TRANSACTION [] [WITH MARK ][ SAVE TRANSACTION ]

ROLLBACK TRANSACTION [ | ]

COMMIT TRANSACTION

Execution of the SQL statementExample:BEGIN TRANUPDATE authorsSET city=San Jose Where au_lname=smithINSERT titlesVALUES(BU1122,Teach Yourself SQL,business, 9988, $35.00, $1000,10,4501,a great book)SELECT *from titleauthorCOMMIT TRAN

Execution of the SQL statementExample: BEGIN TRANDELETE Sales where titles_id =BU1032if @@ERROR >0ROLLBACK TRAN (hu hon ton giao tc)elseCOMMIT TRAN

Control structureIF ELSEIF boolean_expression {sql_statement | statement_block}[ELSE boolean_expression {sql_statement | statement_block}]

Control structureBEGIN ENDBEGIN{sql_statement | statement_ block}END

Control structureExample: IF (SELECT COUNT(*) FROM authors WHERE contract =0) >0 BEGIN PRINT 'These authors do not have contracts on file: ' SELECT au_lname, au_fname, au_id FROM authors WHERE contract=0ENDELSEBEGIN PRINT 'All authors have contracts on file.' END

Control structureWHILEWHILE boolean_expression {sql_statement | statement_block} [BREAK] {sql_statement | statement_block} [CONTINUE]Control structureExample 1:DECLARE @counter INTSET @counter=0WHILE (@counter $50 BREAKELSE CONTINUEENDPRINT 'Too much for the market to bear'

Control structureCASESimple CASE functionCASE input_expression WHEN when_expression THEN result_expression[ ...n ] [ELSE else_result_expression ] END Control structureSearched CASE functionCASEWHEN Boolean_expression THEN result_expression[ ...n ] [ ELSE else_result_expression ] END

Control structureExample: SELECT Category = CASE typeWHEN 'popular_comp' THEN 'Popular Computing' WHEN 'mod_cook' THEN 'Modern Cooking' WHEN 'business' THEN 'Business' WHEN 'psychology' THEN 'Psychology' WHEN 'trad_cook' THEN 'Traditional CookingELSE 'Not yet categorizedENDCAST(title AS varchar(25)) AS 'Shortened Title',price AS Price FROM titles WHERE price IS NOT NULLORDER BY type, price COMPUTE AVG(price) BY type

Control structureExample:SELECT ProductID, Quantity, UnitPrice, [discount%]= CASEWHEN Quantity