SlideShare ist ein Scribd-Unternehmen logo
1 von 49
Implementing Triggers and Transactions

Objectives
In this lesson, you will learn to:
 Create the INSERT, DELETE, and UPDATE triggers
 Modify triggers
 Drop triggers
 Enforce data integrity through triggers
 Use the AFTER and the INSTEAD OFF triggers




©NIIT                                       SQL/Lesson 10/Slide 1 of 49
Implementing Triggers and Transactions

10.D.1 Using the INSERT Trigger
 When a new row is inserted in the Requisition table, the
  value of the siNoOfVacancy attribute should be less than the
  difference between the iBudgetedStrength and
  iCurrentStrength attributes of the Position table. Ensure that
  this user-defined data integrity requirement is implemented.




©NIIT                                          SQL/Lesson 10/Slide 2 of 49
Implementing Triggers and Transactions

Task List
 Identify the object that can maintain user-defined data
  integrity
 Draft statements to create an INSERT trigger
 Create a trigger in the database
 Check the existence of the trigger in the database
 Insert a row in the Requisition table and verify that the trigger
  is working




©NIIT                                            SQL/Lesson 10/Slide 3 of 49
Implementing Triggers and Transactions

Identify the object that can maintain user-defined data
integrity
 A trigger is a block of code that constitutes a set of T-SQL
  statements that are activated in response to certain actions
 Characteristics of a Trigger
     It is fired automatically by SQL Server when any data
      modification statement is issued
     It cannot be explicitly invoked or executed, as in the case
      of the stored procedures




©NIIT                                           SQL/Lesson 10/Slide 4 of 49
Implementing Triggers and Transactions

Identify the object that can maintain data integrity
(Contd.)
     It prevents incorrect, unauthorized or inconsistent changes
      in data
     It cannot return data to the user
 Result:
     A trigger can be used to maintain data integrity




©NIIT                                          SQL/Lesson 10/Slide 5 of 49
Implementing Triggers and Transactions

Draft the statements to create an INSERT trigger
 Creating triggers
    Triggers can be created in the Query Analyzer window by
     using the CREATE TRIGGER statement
     Syntax
      CREATE TRIGGER trigger_name
      ON table_name
      [WITH ENCRYPTION]
      FOR [INSERT | DELETE | UPDATE]
      AS sql_statements




©NIIT                                       SQL/Lesson 10/Slide 6 of 49
Implementing Triggers and Transactions

Draft the statements to create an INSERT trigger
(Contd.)
 Magic tables
     Whenever a trigger fires in response to the INSERT,
      DELETE, or UPDATE statement, two special tables are
      created. These are the inserted and the deleted tables.
      They are also referred to as magic tables
     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
©NIIT                                         SQL/Lesson 10/Slide 7 of 49
Implementing Triggers and Transactions

Draft the statements to create an INSERT trigger
(Contd.)
 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 new row is added
      to both the trigger and the inserted tables




©NIIT                                       SQL/Lesson 10/Slide 8 of 49
Implementing Triggers and Transactions

Draft the statements to create an insert trigger (Contd.)
 Action:
     The table on which the trigger has to be created is
      Requisition
     The trigger has to be of insert type
     The name of the trigger can be trgInsertRequisition
     Write the batch statements
      CREATE TRIGGER trgInsertRequisition
      ON Requisition FOR insert AS
      DECLARE @VacancyReported int
      DECLARE @ActualVacancy int
      SELECT @ActualVacancy = iBudgetedStrength -
      iCurrentStrength

©NIIT                                          SQL/Lesson 10/Slide 9 of 49
Implementing Triggers and Transactions

Draft the statements to create an insert trigger (Contd.)
    FROM Position Join Inserted on
    Position.cPositionCode =
      Inserted.cPositionCode
    SELECT @VacancyReported =
            inserted.siNoOfVacancy
    FROM inserted
    IF(@VacancyReported  @Actualvacancy)
    BEGIN
    PRINT 'The actual vacancies are less than the
      vacancies reported. Hence, cannot insert.'
    ROLLBACK TRANSACTION
    END
    RETURN
©NIIT                                   SQL/Lesson 10/Slide 10 of 49
Implementing Triggers and Transactions

Create a trigger in the database
 Action:
     Type the drafted code in the Query Analyzer window
     Press F5 to execute the code




©NIIT                                      SQL/Lesson 10/Slide 11 of 49
Implementing Triggers and Transactions

Check the existence of the trigger in the database
 Action:
  sp_help trgInsertRequisition




©NIIT                                  SQL/Lesson 10/Slide 12 of 49
Implementing Triggers and Transactions

Insert a row in the Requisition table and verify that the
trigger is working
 Action:
  INSERT Requisition
  VALUES('000003','0001',getdate(), getdate() +
  7, '0001', 'North', 20)




©NIIT                                    SQL/Lesson 10/Slide 13 of 49
Implementing Triggers and Transactions

Just a Minute...
1. What are magic tables?
2. Which statement is used to create triggers?




©NIIT                                        SQL/Lesson 10/Slide 14 of 49
Implementing Triggers and Transactions

10.P.1 Using the INSERT Trigger
 When a new row is added to the Employee table, the
  iCurrentStrength attribute of the Position table should be
  increased by one.




©NIIT                                         SQL/Lesson 10/Slide 15 of 49
Implementing Triggers and Transactions

10.D.2 Using the DELETE Trigger
 Create a trigger to disable deleting rows from the
  ContractRecruiter table




©NIIT                                         SQL/Lesson 10/Slide 16 of 49
Implementing Triggers and Transactions

Task List
 Draft statements to create a delete trigger
 Create the trigger in the database
 Check the existence of the trigger in the database
 Delete a row from the ContractRecruiter table to verify the
  trigger




©NIIT                                           SQL/Lesson 10/Slide 17 of 49
Implementing Triggers and Transactions

Draft statements to create a DELETE trigger
 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   Cascade method
        Âź The   Restrict method
        Âź The   Nullify method




©NIIT                                         SQL/Lesson 10/Slide 18 of 49
Implementing Triggers and Transactions

Draft statements to create a DELETE trigger (Contd.)
 Result:
    The table on which the trigger is to be created is
     ContractRecruiter
    The trigger is a DELETE trigger
    The name of the trigger is trgDeleteContractRecruiter
    The batch statements are:
        CREATE TRIGGER trgDeleteContractRecruiter
        ON ContractRecruiter FOR delete
        AS
        PRINT 'Deletion of Contract Recruiters is
        not allowed'
        ROLLBACK TRANSACTION RETURN
©NIIT                                       SQL/Lesson 10/Slide 19 of 49
Implementing Triggers and Transactions

Create the trigger in the database
 Action:
     Type the drafted code in the Query Analyzer window
     Press F5 to execute the code

Check the existence of the trigger in the database
 Action:
  sp_help trgDeleteContractRecruiter




©NIIT                                      SQL/Lesson 10/Slide 20 of 49
Implementing Triggers and Transactions

Delete a row from the ContractRecruiter table to verify
the trigger
 Action:
     Execute the following statement:
        DELETE ContractRecruiter
        WHERE cContractRecruiterCode = '000001'
     When this command is executed, the trigger would be
      fired and it would prevent the deletion of rows from the
      ContractRecruiter table




©NIIT                                          SQL/Lesson 10/Slide 21 of 49
Implementing Triggers and Transactions

Just a Minute...
 When is a DELETE trigger fired?




©NIIT                               SQL/Lesson 10/Slide 22 of 49
Implementing Triggers and Transactions

10.D 3. Using the UPDATE Trigger
 Create a trigger so that the average siPercentageCharge
  attribute of the ContractRecruiter table should not be more
  than 11 when the value of siPercentageCharge is increased
  for any ContractRecruiter




©NIIT                                       SQL/Lesson 10/Slide 23 of 49
Implementing Triggers and Transactions

Task List
 Draft statements to create an update trigger
 Create the trigger in the database
 Check the existence of the trigger in the database
 Update siPercentageCharge of the ContractRecruiter table
  and verify that the average does not exceed the required
  value




©NIIT                                        SQL/Lesson 10/Slide 24 of 49
Implementing Triggers and Transactions

Draft statements to create an UPDATE trigger
 The UPDATE trigger
     This trigger is fired whenever there is a modification to
      the trigger table
 Result:
     The table on which the trigger is to be created is
      ContractRecruiter
     The trigger is an UPDATE trigger
     The name of the trigger is trgUpdateContractRecruiter



©NIIT                                           SQL/Lesson 10/Slide 25 of 49
Implementing Triggers and Transactions

Draft statements to create an UPDATE trigger (Contd.)
     The trigger is:
        CREATE TRIGGER trgUpdateContractRecruiter
        ON ContractRecruiter FOR UPDATE
        AS
        DECLARE @AvgPercentageCharge int
        SELECT @AvgPercentageCharge =
        avg(siPercentageCharge)
        FROM ContractRecruiter
        IF(@AvgPercentageCharge  11)
        BEGIN
        PRINT 'The average cannot be more than 11'
        ROLLBACK TRANSACTION
        END
        RETURN

©NIIT                                  SQL/Lesson 10/Slide 26 of 49
Implementing Triggers and Transactions

Create the trigger in the database
 In the Query Analyzer window, type the draft code
 Press F5 to execute the code


Check the existence of the trigger in the database
 Action:
  sp_help trgUpdateContractRecruiter




©NIIT                                       SQL/Lesson 10/Slide 27 of 49
Implementing Triggers and Transactions

Update siPercentageCharge of the ContractRecruiter
table and verify that the average does not exceed the
required value
 Action:
     Execute the following UPDATE statement:
        UPDATE ContractRecruiter
        SET siPercentageCharge
        =siPercentageCharge+10
       WHERE cContractRecruiterCode='0002’
  If the average exceeds the limit, then the trigger would
  generate an error message

©NIIT                                         SQL/Lesson 10/Slide 28 of 49
Implementing Triggers and Transactions

10.P.2 Using the UPDATE Trigger
 When an employee resigns, the resignation date is updated
  in the Employee table. After the resignation date is updated,
  the iCurrentStrength attribute of the Position table should be
  decreased by 1.




©NIIT                                         SQL/Lesson 10/Slide 29 of 49
Implementing Triggers and Transactions

10.D.4 Modifying the Trigger
 Modify the trigger trgInsertRequisition that was created
  earlier to check whether the siNoOfVacancy attribute is less
  than the difference between iBudgetedStrength and
  iCurrentStrength from the Position table. If so, the trigger
  should display a message:
  “Sorry, the available vacancy is less than the reported
  vacancy. The transaction cannot be processed.”




©NIIT                                         SQL/Lesson 10/Slide 30 of 49
Implementing Triggers and Transactions

Task List
 Draft the command to modify the trigger
 Create the trigger in the database
 Check that the trigger has been modified in the database
 Insert a row in the Requisition table and verify that the trigger
  is working




©NIIT                                           SQL/Lesson 10/Slide 31 of 49
Implementing Triggers and Transactions

Draft the command to modify the trigger
 The ALTER TRIGGER Command
     The contents of a trigger can be modified by:
        Âź Dropping   the trigger and recreating it
        Âź Using   the ALTER TRIGGER statement
     It is advisable to drop a trigger and recreate it, if the
      objects being referenced by it are renamed




©NIIT                                                SQL/Lesson 10/Slide 32 of 49
Implementing Triggers and Transactions

Draft the command to modify the trigger (Contd.)
    Syntax:
     ALTER TRIGGER trigger_name
     ON table_name
     [WITH ENCRYPTION]
     FOR [INSERT | DELETE | UPDATE]
     AS sql_statements
 Action:
    The table on which the trigger had been created is
     Requisition
    Determine the type of trigger
    The name of the trigger to be modified is
     trgInsertRequisition


©NIIT                                       SQL/Lesson 10/Slide 33 of 49
Implementing Triggers and Transactions

Draft the command to modify the trigger (Contd.)
     Write the batch statements:
      ALTER TRIGGER trgInsertRequisition ON
      Requisition
      FOR insert
      AS
      DECLARE @VacancyReported int
      DECLARE @ActualVacancy int
      SELECT @ActualVacancy = iBudgetedStrength –
      iCurrentStrength
      FROM Position
      SELECT @VacancyReported =
      inserted.siNoOfVacancy
      FROM inserted

©NIIT                                 SQL/Lesson 10/Slide 34 of 49
Implementing Triggers and Transactions

Draft the command to modify the trigger (Contd.)
    IF(@VacancyReported  @ActualVacancy)
    BEGIN
    RAISERROR ('Sorry, the available
    vacancy is less than the reported vacancy.
    The transaction cannot be processed.', 10,
      1)
    ROLLBACK TRANSACTION
    END
    RETURN
Create the trigger in the database
 Action:
     In the Query Analyzer window, type the drafted code
     Press F5 to execute the batch statement
©NIIT                                       SQL/Lesson 10/Slide 35 of 49
Implementing Triggers and Transactions

Check that the trigger has been modified in the
database
 Action:
  sp_helptext trgInsertRequisition
Insert a row in Requisition table and verify that the
trigger is working
 Action:
  INSERT Requisition
  VALUES('000002','0001',getdate(),getdate()
  +7,’0001','North',20)


©NIIT                                    SQL/Lesson 10/Slide 36 of 49
Implementing Triggers and Transactions

Just a Minute...
 Which statement is used to recreate a trigger?




©NIIT                                       SQL/Lesson 10/Slide 37 of 49
Implementing Triggers and Transactions

10.D.5 Dropping the Trigger
 The DELETE trigger named trgDeleteContractRecruiter
  needs to be removed, as it is no longer required.




©NIIT                                    SQL/Lesson 10/Slide 38 of 49
Implementing Triggers and Transactions

Task List
 Draft the command to delete the trigger
 Execute the command
 Verify that the trigger has been removed




©NIIT                                        SQL/Lesson 10/Slide 39 of 49
Implementing Triggers and Transactions

Draft the command to delete the trigger
 The DROP TRIGGER Command is used to delete a trigger
  from the database
     Syntax:
        DROP TRIGGER trigger_name[,..n]
 Action:
     The command to delete the trigger would be:
        DROP TRIGGER trgDeleteContractRecruiter




©NIIT                                       SQL/Lesson 10/Slide 40 of 49
Implementing Triggers and Transactions

Execute the command
 Action:
     In the Query Analyzer window, type the drafted code
     Press F5 to execute the batch statement


Verify that the trigger has been removed
 Action:
  sp_help trgDeleteContractRecruiter
    The above command will give an error message as the
     trigger has been removed

©NIIT                                       SQL/Lesson 10/Slide 41 of 49
Implementing Triggers and Transactions

Enforcing Data Integrity Through Triggers
 Triggers and Data Integrity
     A trigger can be used to enforce business rules and data
      integrity in the following ways:
        Âź Ifchanges are made to the master table, then the same
          changes are cascaded to all the dependent tables
        Âź Ifsome changes violate referential integrity, then all
          such changes are rejected, thereby canceling any
          attempt to modify data in the database
        Âź It   allows very complex restrictions to be enforced
        Âź Itcan perform a particular action, depending on the
          outcome of the modifications that have been made to
          the tables
©NIIT                                             SQL/Lesson 10/Slide 42 of 49
Implementing Triggers and Transactions

Enforcing Data Integrity Through Triggers (Contd.)
 Multiple Triggers
     SQL Server allows multiple triggers to be defined on a
      given table. This implies that a single DML statement may
      fire two or more triggers. The triggers are fired in the
      order of creation
 AFTER and INSTEAD OF Triggers
     The AFTER trigger can be created on any table for the
      INSERT, UPDATE, or DELETE operation just like the
      normal triggers
     The AFTER trigger gets fired after the execution of the
      DML operation for which it has been defined
©NIIT                                         SQL/Lesson 10/Slide 43 of 49
Implementing Triggers and Transactions

Enforcing Data Integrity Through Triggers (Contd.)
     By default, if more than one AFTER trigger is created on a
      table for a DML operation such as INSERT, UPDATE, or
      DELETE, then the sequence of execution is the order in
      which they were created
     In case you have multiple AFTER triggers for any single
      DML operation, you can change the sequence of execution
      of these triggers by using the sp_settriggerorder system
      stored procedure
     Syntax
        sp_settriggerorder triggername,order-value,DML-
        operation

©NIIT                                        SQL/Lesson 10/Slide 44 of 49
Implementing Triggers and Transactions

Enforcing Data Integrity Through Triggers (Contd.)
     INSTEAD OF triggers can be primarily used to perform an
      action such as a DML operation, on another table or view
     This type of trigger can be created on both table as well as
      on a view
     Unlike AFTER triggers you cannot create more than one
      INSTEAD OF trigger for a DML operation on the same table
      or view




©NIIT                                         SQL/Lesson 10/Slide 45 of 49
Implementing Triggers and Transactions

Just a Minute...
 How are triggers used to maintain integrity and consistency
  of data?




©NIIT                                        SQL/Lesson 10/Slide 46 of 49
Implementing Triggers and Transactions

Summary
In this lesson you learned that:
 A trigger is a block of code that constitutes a set of T-SQL
  statements that get activated in response to certain actions
 A trigger fires in response to the INSERT, UPDATE, and
  DELETE statements
 A trigger can be created in the Query Analyzer by using the
  CREATE TRIGGER statement
 A magic table is a conceptual table that is structurally similar
  to the table on which a trigger is defined



©NIIT                                          SQL/Lesson 10/Slide 47 of 49
Implementing Triggers and Transactions

Summary (Contd.)
 There are two types of magic tables:
     Inserted, which stores a copy of the rows that have been
      inserted into the trigger table
     Deleted, which stores those records that have been
      deleted from the trigger table
 A trigger can be viewed using the sp_help and sp_helptext
  system stored procedures
 A trigger can be altered using the ALTER TRIGGER
  statement
 A trigger can be deleted using the DROP TRIGGER
  statement
©NIIT                                        SQL/Lesson 10/Slide 48 of 49
Implementing Triggers and Transactions

Summary (Contd.)
 A trigger can be used to enforce business rules and data
 integrity
 The AFTER trigger is executed after all constraints and triggers
  defined on the table have successfully executed
 INSTEAD OF triggers can be used to perform another action
  such as a DML operation on another table or view




©NIIT                                        SQL/Lesson 10/Slide 49 of 49

Weitere Àhnliche Inhalte

Andere mochten auch

Dacj 1-3 b
Dacj 1-3 bDacj 1-3 b
Dacj 1-3 bNiit Care
 
Comp tia n+_session_08
Comp tia n+_session_08Comp tia n+_session_08
Comp tia n+_session_08Niit Care
 
01 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_0101 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_01Niit Care
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREDouglas Bernardini
 
Sql server basics
Sql server basicsSql server basics
Sql server basicsVishalJharwade
 
Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 bNiit Care
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architectureAjeet Singh
 

Andere mochten auch (8)

Dacj 1-3 b
Dacj 1-3 bDacj 1-3 b
Dacj 1-3 b
 
Comp tia n+_session_08
Comp tia n+_session_08Comp tia n+_session_08
Comp tia n+_session_08
 
01 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_0101 iec t1_s1_plt_session_01
01 iec t1_s1_plt_session_01
 
SQL | Computer Science
SQL | Computer ScienceSQL | Computer Science
SQL | Computer Science
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 
Sql server basics
Sql server basicsSql server basics
Sql server basics
 
Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
 

Ähnlich wie Sql xp 10

Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersAlexey Furmanov
 
Flexviews materialized views for my sql
Flexviews materialized views for my sqlFlexviews materialized views for my sql
Flexviews materialized views for my sqlJustin Swanhart
 
Sql xp 07
Sql xp 07Sql xp 07
Sql xp 07Niit Care
 
Eclipse Summit Europe '10 - Test UI Aspects of Plug-ins
Eclipse Summit Europe '10 - Test UI Aspects of Plug-insEclipse Summit Europe '10 - Test UI Aspects of Plug-ins
Eclipse Summit Europe '10 - Test UI Aspects of Plug-insTonny Madsen
 
How to instantiate any view controller for free
How to instantiate any view controller for freeHow to instantiate any view controller for free
How to instantiate any view controller for freeBenotCaron
 
10 qmds2005 session14
10 qmds2005 session1410 qmds2005 session14
10 qmds2005 session14Niit Care
 
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxCASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxketurahhazelhurst
 
L0020 - The Basic RCP Application
L0020 - The Basic RCP ApplicationL0020 - The Basic RCP Application
L0020 - The Basic RCP ApplicationTonny Madsen
 
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...Shahzad
 
04a intro while
04a intro while04a intro while
04a intro whilehasfaa1017
 
Tools and Techniques for Understanding Threading Behavior in Android*
Tools and Techniques for Understanding Threading Behavior in Android*Tools and Techniques for Understanding Threading Behavior in Android*
Tools and Techniques for Understanding Threading Behavior in Android*IntelÂź Software
 
Taming startup dynamics - Magnus Jungsbluth & Domagoj Cosic
Taming startup dynamics - Magnus Jungsbluth & Domagoj CosicTaming startup dynamics - Magnus Jungsbluth & Domagoj Cosic
Taming startup dynamics - Magnus Jungsbluth & Domagoj Cosicmfrancis
 
Introduction to Reactive Extensions (Rx)
Introduction to Reactive Extensions (Rx)Introduction to Reactive Extensions (Rx)
Introduction to Reactive Extensions (Rx)Tamir Dresher
 
IBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesIBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesKeshav Murthy
 
Sql xp 06
Sql xp 06Sql xp 06
Sql xp 06Niit Care
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13Niit Care
 
1 Database Security Lab 2 – Virtual Private Database.docx
1 Database Security Lab 2 – Virtual Private Database.docx1 Database Security Lab 2 – Virtual Private Database.docx
1 Database Security Lab 2 – Virtual Private Database.docxjeremylockett77
 
Aae oop xp_07
Aae oop xp_07Aae oop xp_07
Aae oop xp_07Niit Care
 

Ähnlich wie Sql xp 10 (20)

Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Flexviews materialized views for my sql
Flexviews materialized views for my sqlFlexviews materialized views for my sql
Flexviews materialized views for my sql
 
Sql xp 07
Sql xp 07Sql xp 07
Sql xp 07
 
Eclipse Summit Europe '10 - Test UI Aspects of Plug-ins
Eclipse Summit Europe '10 - Test UI Aspects of Plug-insEclipse Summit Europe '10 - Test UI Aspects of Plug-ins
Eclipse Summit Europe '10 - Test UI Aspects of Plug-ins
 
How to instantiate any view controller for free
How to instantiate any view controller for freeHow to instantiate any view controller for free
How to instantiate any view controller for free
 
10 qmds2005 session14
10 qmds2005 session1410 qmds2005 session14
10 qmds2005 session14
 
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docxCASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
CASE STUDY InternetExcel Exercises, page 434, textRecord your.docx
 
L0020 - The Basic RCP Application
L0020 - The Basic RCP ApplicationL0020 - The Basic RCP Application
L0020 - The Basic RCP Application
 
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...To Study The Tips Tricks  Guidelines Related To Performance Tuning For  N Hib...
To Study The Tips Tricks Guidelines Related To Performance Tuning For N Hib...
 
04a intro while
04a intro while04a intro while
04a intro while
 
Tools and Techniques for Understanding Threading Behavior in Android*
Tools and Techniques for Understanding Threading Behavior in Android*Tools and Techniques for Understanding Threading Behavior in Android*
Tools and Techniques for Understanding Threading Behavior in Android*
 
Taming startup dynamics - Magnus Jungsbluth & Domagoj Cosic
Taming startup dynamics - Magnus Jungsbluth & Domagoj CosicTaming startup dynamics - Magnus Jungsbluth & Domagoj Cosic
Taming startup dynamics - Magnus Jungsbluth & Domagoj Cosic
 
Introduction to Reactive Extensions (Rx)
Introduction to Reactive Extensions (Rx)Introduction to Reactive Extensions (Rx)
Introduction to Reactive Extensions (Rx)
 
IBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesIBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql Features
 
Sql xp 06
Sql xp 06Sql xp 06
Sql xp 06
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13
 
Unit 4
Unit 4Unit 4
Unit 4
 
1 Database Security Lab 2 – Virtual Private Database.docx
1 Database Security Lab 2 – Virtual Private Database.docx1 Database Security Lab 2 – Virtual Private Database.docx
1 Database Security Lab 2 – Virtual Private Database.docx
 
Aae oop xp_07
Aae oop xp_07Aae oop xp_07
Aae oop xp_07
 

Mehr von Niit Care

Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 bNiit Care
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 aNiit Care
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 cNiit Care
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 bNiit Care
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 aNiit Care
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 cNiit Care
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 bNiit Care
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 aNiit Care
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 cNiit Care
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 aNiit Care
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 cNiit Care
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-cNiit Care
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-bNiit Care
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-aNiit Care
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-cNiit Care
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-bNiit Care
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-aNiit Care
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 bNiit Care
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 cNiit Care
 
Dacj 1-3 a
Dacj 1-3 aDacj 1-3 a
Dacj 1-3 aNiit Care
 

Mehr von Niit Care (20)

Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 
Dacj 1-3 a
Dacj 1-3 aDacj 1-3 a
Dacj 1-3 a
 

KĂŒrzlich hochgeladen

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

KĂŒrzlich hochgeladen (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Sql xp 10

  • 1. Implementing Triggers and Transactions Objectives In this lesson, you will learn to: Create the INSERT, DELETE, and UPDATE triggers Modify triggers Drop triggers Enforce data integrity through triggers Use the AFTER and the INSTEAD OFF triggers ©NIIT SQL/Lesson 10/Slide 1 of 49
  • 2. Implementing Triggers and Transactions 10.D.1 Using the INSERT Trigger When a new row is inserted in the Requisition table, the value of the siNoOfVacancy attribute should be less than the difference between the iBudgetedStrength and iCurrentStrength attributes of the Position table. Ensure that this user-defined data integrity requirement is implemented. ©NIIT SQL/Lesson 10/Slide 2 of 49
  • 3. Implementing Triggers and Transactions Task List Identify the object that can maintain user-defined data integrity Draft statements to create an INSERT trigger Create a trigger in the database Check the existence of the trigger in the database Insert a row in the Requisition table and verify that the trigger is working ©NIIT SQL/Lesson 10/Slide 3 of 49
  • 4. Implementing Triggers and Transactions Identify the object that can maintain user-defined data integrity A trigger is a block of code that constitutes a set of T-SQL statements that are activated in response to certain actions Characteristics of a Trigger It is fired automatically by SQL Server when any data modification statement is issued It cannot be explicitly invoked or executed, as in the case of the stored procedures ©NIIT SQL/Lesson 10/Slide 4 of 49
  • 5. Implementing Triggers and Transactions Identify the object that can maintain data integrity (Contd.) It prevents incorrect, unauthorized or inconsistent changes in data It cannot return data to the user Result: A trigger can be used to maintain data integrity ©NIIT SQL/Lesson 10/Slide 5 of 49
  • 6. Implementing Triggers and Transactions Draft the statements to create an INSERT trigger Creating triggers Triggers can be created in the Query Analyzer window by using the CREATE TRIGGER statement Syntax CREATE TRIGGER trigger_name ON table_name [WITH ENCRYPTION] FOR [INSERT | DELETE | UPDATE] AS sql_statements ©NIIT SQL/Lesson 10/Slide 6 of 49
  • 7. Implementing Triggers and Transactions Draft the statements to create an INSERT trigger (Contd.) Magic tables Whenever a trigger fires in response to the INSERT, DELETE, or UPDATE statement, two special tables are created. These are the inserted and the deleted tables. They are also referred to as magic tables 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 ©NIIT SQL/Lesson 10/Slide 7 of 49
  • 8. Implementing Triggers and Transactions Draft the statements to create an INSERT trigger (Contd.) 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 new row is added to both the trigger and the inserted tables ©NIIT SQL/Lesson 10/Slide 8 of 49
  • 9. Implementing Triggers and Transactions Draft the statements to create an insert trigger (Contd.) Action: The table on which the trigger has to be created is Requisition The trigger has to be of insert type The name of the trigger can be trgInsertRequisition Write the batch statements CREATE TRIGGER trgInsertRequisition ON Requisition FOR insert AS DECLARE @VacancyReported int DECLARE @ActualVacancy int SELECT @ActualVacancy = iBudgetedStrength - iCurrentStrength ©NIIT SQL/Lesson 10/Slide 9 of 49
  • 10. Implementing Triggers and Transactions Draft the statements to create an insert trigger (Contd.) FROM Position Join Inserted on Position.cPositionCode = Inserted.cPositionCode SELECT @VacancyReported = inserted.siNoOfVacancy FROM inserted IF(@VacancyReported @Actualvacancy) BEGIN PRINT 'The actual vacancies are less than the vacancies reported. Hence, cannot insert.' ROLLBACK TRANSACTION END RETURN ©NIIT SQL/Lesson 10/Slide 10 of 49
  • 11. Implementing Triggers and Transactions Create a trigger in the database Action: Type the drafted code in the Query Analyzer window Press F5 to execute the code ©NIIT SQL/Lesson 10/Slide 11 of 49
  • 12. Implementing Triggers and Transactions Check the existence of the trigger in the database Action: sp_help trgInsertRequisition ©NIIT SQL/Lesson 10/Slide 12 of 49
  • 13. Implementing Triggers and Transactions Insert a row in the Requisition table and verify that the trigger is working Action: INSERT Requisition VALUES('000003','0001',getdate(), getdate() + 7, '0001', 'North', 20) ©NIIT SQL/Lesson 10/Slide 13 of 49
  • 14. Implementing Triggers and Transactions Just a Minute... 1. What are magic tables? 2. Which statement is used to create triggers? ©NIIT SQL/Lesson 10/Slide 14 of 49
  • 15. Implementing Triggers and Transactions 10.P.1 Using the INSERT Trigger When a new row is added to the Employee table, the iCurrentStrength attribute of the Position table should be increased by one. ©NIIT SQL/Lesson 10/Slide 15 of 49
  • 16. Implementing Triggers and Transactions 10.D.2 Using the DELETE Trigger Create a trigger to disable deleting rows from the ContractRecruiter table ©NIIT SQL/Lesson 10/Slide 16 of 49
  • 17. Implementing Triggers and Transactions Task List Draft statements to create a delete trigger Create the trigger in the database Check the existence of the trigger in the database Delete a row from the ContractRecruiter table to verify the trigger ©NIIT SQL/Lesson 10/Slide 17 of 49
  • 18. Implementing Triggers and Transactions Draft statements to create a DELETE trigger 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 Cascade method Âź The Restrict method Âź The Nullify method ©NIIT SQL/Lesson 10/Slide 18 of 49
  • 19. Implementing Triggers and Transactions Draft statements to create a DELETE trigger (Contd.) Result: The table on which the trigger is to be created is ContractRecruiter The trigger is a DELETE trigger The name of the trigger is trgDeleteContractRecruiter The batch statements are: CREATE TRIGGER trgDeleteContractRecruiter ON ContractRecruiter FOR delete AS PRINT 'Deletion of Contract Recruiters is not allowed' ROLLBACK TRANSACTION RETURN ©NIIT SQL/Lesson 10/Slide 19 of 49
  • 20. Implementing Triggers and Transactions Create the trigger in the database Action: Type the drafted code in the Query Analyzer window Press F5 to execute the code Check the existence of the trigger in the database Action: sp_help trgDeleteContractRecruiter ©NIIT SQL/Lesson 10/Slide 20 of 49
  • 21. Implementing Triggers and Transactions Delete a row from the ContractRecruiter table to verify the trigger Action: Execute the following statement: DELETE ContractRecruiter WHERE cContractRecruiterCode = '000001' When this command is executed, the trigger would be fired and it would prevent the deletion of rows from the ContractRecruiter table ©NIIT SQL/Lesson 10/Slide 21 of 49
  • 22. Implementing Triggers and Transactions Just a Minute... When is a DELETE trigger fired? ©NIIT SQL/Lesson 10/Slide 22 of 49
  • 23. Implementing Triggers and Transactions 10.D 3. Using the UPDATE Trigger Create a trigger so that the average siPercentageCharge attribute of the ContractRecruiter table should not be more than 11 when the value of siPercentageCharge is increased for any ContractRecruiter ©NIIT SQL/Lesson 10/Slide 23 of 49
  • 24. Implementing Triggers and Transactions Task List Draft statements to create an update trigger Create the trigger in the database Check the existence of the trigger in the database Update siPercentageCharge of the ContractRecruiter table and verify that the average does not exceed the required value ©NIIT SQL/Lesson 10/Slide 24 of 49
  • 25. Implementing Triggers and Transactions Draft statements to create an UPDATE trigger The UPDATE trigger This trigger is fired whenever there is a modification to the trigger table Result: The table on which the trigger is to be created is ContractRecruiter The trigger is an UPDATE trigger The name of the trigger is trgUpdateContractRecruiter ©NIIT SQL/Lesson 10/Slide 25 of 49
  • 26. Implementing Triggers and Transactions Draft statements to create an UPDATE trigger (Contd.) The trigger is: CREATE TRIGGER trgUpdateContractRecruiter ON ContractRecruiter FOR UPDATE AS DECLARE @AvgPercentageCharge int SELECT @AvgPercentageCharge = avg(siPercentageCharge) FROM ContractRecruiter IF(@AvgPercentageCharge 11) BEGIN PRINT 'The average cannot be more than 11' ROLLBACK TRANSACTION END RETURN ©NIIT SQL/Lesson 10/Slide 26 of 49
  • 27. Implementing Triggers and Transactions Create the trigger in the database In the Query Analyzer window, type the draft code Press F5 to execute the code Check the existence of the trigger in the database Action: sp_help trgUpdateContractRecruiter ©NIIT SQL/Lesson 10/Slide 27 of 49
  • 28. Implementing Triggers and Transactions Update siPercentageCharge of the ContractRecruiter table and verify that the average does not exceed the required value Action: Execute the following UPDATE statement: UPDATE ContractRecruiter SET siPercentageCharge =siPercentageCharge+10 WHERE cContractRecruiterCode='0002’ If the average exceeds the limit, then the trigger would generate an error message ©NIIT SQL/Lesson 10/Slide 28 of 49
  • 29. Implementing Triggers and Transactions 10.P.2 Using the UPDATE Trigger When an employee resigns, the resignation date is updated in the Employee table. After the resignation date is updated, the iCurrentStrength attribute of the Position table should be decreased by 1. ©NIIT SQL/Lesson 10/Slide 29 of 49
  • 30. Implementing Triggers and Transactions 10.D.4 Modifying the Trigger Modify the trigger trgInsertRequisition that was created earlier to check whether the siNoOfVacancy attribute is less than the difference between iBudgetedStrength and iCurrentStrength from the Position table. If so, the trigger should display a message: “Sorry, the available vacancy is less than the reported vacancy. The transaction cannot be processed.” ©NIIT SQL/Lesson 10/Slide 30 of 49
  • 31. Implementing Triggers and Transactions Task List Draft the command to modify the trigger Create the trigger in the database Check that the trigger has been modified in the database Insert a row in the Requisition table and verify that the trigger is working ©NIIT SQL/Lesson 10/Slide 31 of 49
  • 32. Implementing Triggers and Transactions Draft the command to modify the trigger The ALTER TRIGGER Command The contents of a trigger can be modified by: Âź Dropping the trigger and recreating it Âź Using the ALTER TRIGGER statement It is advisable to drop a trigger and recreate it, if the objects being referenced by it are renamed ©NIIT SQL/Lesson 10/Slide 32 of 49
  • 33. Implementing Triggers and Transactions Draft the command to modify the trigger (Contd.) Syntax: ALTER TRIGGER trigger_name ON table_name [WITH ENCRYPTION] FOR [INSERT | DELETE | UPDATE] AS sql_statements Action: The table on which the trigger had been created is Requisition Determine the type of trigger The name of the trigger to be modified is trgInsertRequisition ©NIIT SQL/Lesson 10/Slide 33 of 49
  • 34. Implementing Triggers and Transactions Draft the command to modify the trigger (Contd.) Write the batch statements: ALTER TRIGGER trgInsertRequisition ON Requisition FOR insert AS DECLARE @VacancyReported int DECLARE @ActualVacancy int SELECT @ActualVacancy = iBudgetedStrength – iCurrentStrength FROM Position SELECT @VacancyReported = inserted.siNoOfVacancy FROM inserted ©NIIT SQL/Lesson 10/Slide 34 of 49
  • 35. Implementing Triggers and Transactions Draft the command to modify the trigger (Contd.) IF(@VacancyReported @ActualVacancy) BEGIN RAISERROR ('Sorry, the available vacancy is less than the reported vacancy. The transaction cannot be processed.', 10, 1) ROLLBACK TRANSACTION END RETURN Create the trigger in the database Action: In the Query Analyzer window, type the drafted code Press F5 to execute the batch statement ©NIIT SQL/Lesson 10/Slide 35 of 49
  • 36. Implementing Triggers and Transactions Check that the trigger has been modified in the database Action: sp_helptext trgInsertRequisition Insert a row in Requisition table and verify that the trigger is working Action: INSERT Requisition VALUES('000002','0001',getdate(),getdate() +7,’0001','North',20) ©NIIT SQL/Lesson 10/Slide 36 of 49
  • 37. Implementing Triggers and Transactions Just a Minute... Which statement is used to recreate a trigger? ©NIIT SQL/Lesson 10/Slide 37 of 49
  • 38. Implementing Triggers and Transactions 10.D.5 Dropping the Trigger The DELETE trigger named trgDeleteContractRecruiter needs to be removed, as it is no longer required. ©NIIT SQL/Lesson 10/Slide 38 of 49
  • 39. Implementing Triggers and Transactions Task List Draft the command to delete the trigger Execute the command Verify that the trigger has been removed ©NIIT SQL/Lesson 10/Slide 39 of 49
  • 40. Implementing Triggers and Transactions Draft the command to delete the trigger The DROP TRIGGER Command is used to delete a trigger from the database Syntax: DROP TRIGGER trigger_name[,..n] Action: The command to delete the trigger would be: DROP TRIGGER trgDeleteContractRecruiter ©NIIT SQL/Lesson 10/Slide 40 of 49
  • 41. Implementing Triggers and Transactions Execute the command Action: In the Query Analyzer window, type the drafted code Press F5 to execute the batch statement Verify that the trigger has been removed Action: sp_help trgDeleteContractRecruiter The above command will give an error message as the trigger has been removed ©NIIT SQL/Lesson 10/Slide 41 of 49
  • 42. Implementing Triggers and Transactions Enforcing Data Integrity Through Triggers Triggers and Data Integrity A trigger can be used to enforce business rules and data integrity in the following ways: Âź Ifchanges are made to the master table, then the same changes are cascaded to all the dependent tables Âź Ifsome changes violate referential integrity, then all such changes are rejected, thereby canceling any attempt to modify data in the database Âź It allows very complex restrictions to be enforced Âź Itcan perform a particular action, depending on the outcome of the modifications that have been made to the tables ©NIIT SQL/Lesson 10/Slide 42 of 49
  • 43. Implementing Triggers and Transactions Enforcing Data Integrity Through Triggers (Contd.) Multiple Triggers SQL Server allows multiple triggers to be defined on a given table. This implies that a single DML statement may fire two or more triggers. The triggers are fired in the order of creation AFTER and INSTEAD OF Triggers The AFTER trigger can be created on any table for the INSERT, UPDATE, or DELETE operation just like the normal triggers The AFTER trigger gets fired after the execution of the DML operation for which it has been defined ©NIIT SQL/Lesson 10/Slide 43 of 49
  • 44. Implementing Triggers and Transactions Enforcing Data Integrity Through Triggers (Contd.) By default, if more than one AFTER trigger is created on a table for a DML operation such as INSERT, UPDATE, or DELETE, then the sequence of execution is the order in which they were created In case you have multiple AFTER triggers for any single DML operation, you can change the sequence of execution of these triggers by using the sp_settriggerorder system stored procedure Syntax sp_settriggerorder triggername,order-value,DML- operation ©NIIT SQL/Lesson 10/Slide 44 of 49
  • 45. Implementing Triggers and Transactions Enforcing Data Integrity Through Triggers (Contd.) INSTEAD OF triggers can be primarily used to perform an action such as a DML operation, on another table or view This type of trigger can be created on both table as well as on a view Unlike AFTER triggers you cannot create more than one INSTEAD OF trigger for a DML operation on the same table or view ©NIIT SQL/Lesson 10/Slide 45 of 49
  • 46. Implementing Triggers and Transactions Just a Minute... How are triggers used to maintain integrity and consistency of data? ©NIIT SQL/Lesson 10/Slide 46 of 49
  • 47. Implementing Triggers and Transactions Summary In this lesson you learned that: A trigger is a block of code that constitutes a set of T-SQL statements that get activated in response to certain actions A trigger fires in response to the INSERT, UPDATE, and DELETE statements A trigger can be created in the Query Analyzer by using the CREATE TRIGGER statement A magic table is a conceptual table that is structurally similar to the table on which a trigger is defined ©NIIT SQL/Lesson 10/Slide 47 of 49
  • 48. Implementing Triggers and Transactions Summary (Contd.) There are two types of magic tables: Inserted, which stores a copy of the rows that have been inserted into the trigger table Deleted, which stores those records that have been deleted from the trigger table A trigger can be viewed using the sp_help and sp_helptext system stored procedures A trigger can be altered using the ALTER TRIGGER statement A trigger can be deleted using the DROP TRIGGER statement ©NIIT SQL/Lesson 10/Slide 48 of 49
  • 49. Implementing Triggers and Transactions Summary (Contd.) A trigger can be used to enforce business rules and data integrity The AFTER trigger is executed after all constraints and triggers defined on the table have successfully executed INSTEAD OF triggers can be used to perform another action such as a DML operation on another table or view ©NIIT SQL/Lesson 10/Slide 49 of 49