SESS-8

24
SQL SERVER 6.5 Chapter-8/1 Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority. OBJECTIVE Implementation of Triggers and Stored procedures SCOPE Triggers Creation of triggers Enforcing data integrity through triggers Stored procedures Creating and executing stored procedures Remote and system stored procedures How stored procedures are processed

description

SQL SWDecision makingprocesses in

Transcript of SESS-8

Page 1: SESS-8

SQL SERVER 6.5

Chapter-8/1Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

OBJECTIVE

Implementation of Triggers and Stored procedures

SCOPE

Triggers

Creation of triggersEnforcing data integrity through triggers

Stored procedures

Creating and executing stored proceduresRemote and system stored proceduresHow stored procedures are processed

Page 2: SESS-8

SQL SERVER 6.5

Chapter-8/2

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

TRIGGERS

About triggers

A trigger is a special kind of stored procedure that is invoked whenever an attempt ismade to modify the data in the table it protects.

Modifications to a table are made using INSERT, UPDATE, or DELETE statements.

Triggers are used to enforce business rules and data integrity such as automaticallyupdating summary data.

Triggers allow to perform cascading delete or update actions, if a referential integrityviolation occurs.

If constraints exist on the trigger table, they are checked prior to the trigger execution.If constraints are violated, the statement does not execute, hence trigger will not run.

Characteristics of trigger

• Are associated with tables.• Are automatic; they work irrespective of the cause of the data modification.• Are automatically invoked by SQL Server.• Cannot be called directly and do not have parameters.• Can nest up to 16 levels.

This allows a trigger that changes a table on which there is another trigger to invokethe second trigger, which can fire a third trigger and so on.

• Are conceptually advanced form of rules, used to enforce more elaborate restrictionson data. They prevent incorrect, unauthorized, or inconsistent changes to the data.

Creation of triggers

Triggers are created with the CREATE TRIGGER statement.

Statement specifies

(a) the table on which a trigger is defined.(b) the events for which trigger will invoke.

To prevent a trigger from firing , DROP TRIGGER statement is used.

Page 3: SESS-8

SQL SERVER 6.5

Chapter-8/3Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Syntax:

CREATE TRIGGER [ owner.] trigger_name

ON [owner.] table_name

FOR [ INSERT | UPDATE| DELETE ]

AS

IF UPDATE (column_name)...

[ { AND | OR } UPDATE (column_name)...]

sql_statements }

Trigger rules and guidelines

• A table can only have three trigger actions per table: one UPADTE, one INSERT andone DELETE trigger.

• Each trigger applies to only one table only. A single trigger can process all threeactions (UPDATE, DELETE, INSERT) .

• Only table owners can create and drop triggers for the table. This permission cannotbe transferred.

• A trigger cannot be created on a view or a temporary table, although triggers canreference them.

• A trigger should not include SELECT statements that return results to the user,because the returned results would have to be written into every application in whichmodifications to the trigger table are allowed.

• Triggers can be used to help ensure the relational integrity of the database.• Triggers should be used only for the data integrity enforcement and business rules

processing.• If a trigger is defined for an operation (INSERT, UPDATE or DELETE) that already

has a trigger association, the existing trigger is replaced with the new trigger.• On dropping a table all triggers associated to the triggers are automatically dropped. The system stored procedure sp_depends can be used to find out which tables havetrigger on them.

Page 4: SESS-8

SQL SERVER 6.5

Chapter-8/4

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Following SQL statements are not allowed in a trigger:

• All CREATE statements.• All DROP statements.• ALTER TABLE and ALTER DATABASE.• TRUNCATE TABLE.• GRANT and REVOKE.• UPDATE STATISTICS.• RECONFIGURE.• LOAD DATABASE and LOAD TRANSACTION.• All DISK statements.• SELECT INTO (because it creates table). INSERT trigger When an INSERT trigger statement is executed, new rows are added to the trigger tableand to the inserted table at the same time. The inserted table is a logical table that holds a copy of the rows that have been inserted. DIAGRAM inserted FRANCIS MARY POND VILLA

APPLICANT LAST_NAME FIRST_NAME ADDRESS BARR PETER CHURCH ROAD ALLEN SAM PARK STREET FRANCIS MARY POND VILLA

The inserted table can be examined by the trigger, to determine whether or how thetrigger actions should be carried out. The inserted table allows to compare the INSERTED rows in the table to the rows in theinserted table. The rows in the inserted table are always duplicates of one or more rows in the triggertable. With the inserted table, inserted data can be referenced without having to store the

Page 5: SESS-8

SQL SERVER 6.5

Chapter-8/5Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

information in the variables. DELETE trigger When a DELETE trigger statement is executed, rows are deleted from the table, and areplaces in a special table called deleted table. DIAGRAM APPLICANT LAST_NAME FIRST_NAME ADDRESS BARR PETER CHURCH ROAD ALLEN SAM PARK STREET FRANCIS MARY POND VILLA

deleted FRANCIS MARY POND VILLA

When using the DELETE trigger statement consider the following:

• The deleted table and the database tables will not have any rows in common.• When a row is appended to the deleted table, it no longer exists in the database table.• Space is allocated the deleted table from the database’s allocated space. The deleted

table is always in cache.• The DELETE trigger does not execute for the TRUNCATE TABLE statement.• Deleted and inserted tables are conceptual tables. They are structurally like the table

on which the trigger is defined. They hold the rows of information modified by theuser.

Page 6: SESS-8

SQL SERVER 6.5

Chapter-8/6

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

UPDATE trigger When an UPDATE statement is executed on a table that has an UPDATE trigger, theoriginal rows are moved into the deleted table, while the update row is inserted into theinserted table and the table being updated DIAGRAM

TABLE

inserted

deleted

When using the UPDATE trigger statement, consider the following:

• After all rows are updated, deleted and inserted tables are loaded, and then theUPDATE trigger executes.

• The deleted and inserted tables, as well as the updated table can be examined by thetrigger to determine whether multiple rows have been updated or how the triggeractions should be carried out.

UPDATE on a column

UPDATE trigger can be defined

(a) to protect data in a specific column.(b) to test modifications of a specified column.

Original record that is being updatedgoes to the deleted table.

Updated row isinserted into theinserted table and thetable is updated

Page 7: SESS-8

SQL SERVER 6.5

Chapter-8/7Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Syntax:

IF UPDATE < column_name>

EXAMPLE

CREATE TRIGGER trigger1ON member

FOR UPDATEASIF UPDATE (last_name)BEGIN

RAISERROR (‘Transaction cannot be processed’)ROLLBACK TRANSACTION

END

OUTPUT:

• Prevents the user from modifying the last_name field of the table member.

Enforcing data integrity through triggers

Triggers are used to enforce:

(a) Data integrity(b) Referential integrity

• Can take actions or cascade actions.• Can define custom error message.

(c) Business rules• Enforce restrictions that are more complex than those defined with CHECK

constraints.

Enforcing data integrity

Triggers can be used to enforce data integrity by cascading changes to affected tablesthroughout the database.

The following example shows, how a trigger cascades to change affected tablesthroughout the database.

Page 8: SESS-8

SQL SERVER 6.5

Chapter-8/8

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

EXAMPLE

CREATE TRIGGER del_trigON fineFOR DELETEASUPDATE memberSET fine_amt = 0FROM member, deletedWHERE member.mem_no = deleted.mem_no

OUTPUT:• Enforces data integrity by changing the status of fine_amt to 0 in the member table when a fine record

for that member is deleted from the fine table.

Note: The record is fetched in the member table for updation on the basis of the record in the deletedtable.

Enforcing referential integrity

• Database accuracy

Assures vital data in database remains accurate and useable as database changes

• Maintains Primary and Foreign keys

Keeps the values of foreign keys in line with those in primary keys.

Allows actions to be taken when a key is inserted, updated or deleted.

Triggers can be used to enforce referential integrity.

Referential integrity can be defined by using FOREIGN KEY and REFERENCEconstraints with the CREATE TABLE statement.

Triggers are useful to ensure appropriate actions when cascading deletions or updatesneed to occur.

EXAMPLE

CREATE TRIGGER adult_insertON adultFOR INSERTASIF (SELECT COUNT(*)

FROM member, insertedWHERE member.mem_num=inserted.mem_num)=0

BEGINPRINT ‘Transaction cannot be processed’PRINT ‘No entry for member for this adult.’ROLLBACK TRANSACTION

END

Page 9: SESS-8

SQL SERVER 6.5

Chapter-8/9Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

OUTPUT:• When a user inserts a record in the table adult, the trigger adult_insert is fired.• The mem_num inserted in the adult table should be present in the member table.• The existence of the mem_num inserted into the adult table is checked against the member table

using the inserted table.

The trigger works when a single row is inserted. If multiple rows are inserted as with(SELECT statement), the trigger will not work correctly.

Multi-row trigger

A multi-row insert can occur from an INSERT with a SELECT statement. Multirowconsiderations can also apply to multi-row updates and multi-row deletes.

EXAMPLE

CREATE TRIGGER adult_insertON adultFOR INSERTASDECLARE @rcnt intSELECT @rcnt = @@rowcountIF (SELECT COUNT(*)

FROM member, insertedWHERE member.mem_num=inserted.mem_num)=0

BEGINPRINT ‘Transaction cannot be processed’PRINT ‘No entry for member for this adult.’ROLLBACK TRANSACTION

END

IF (SELECT COUNT(*)FROM member, insertedWHERE member.mem_num=inserted.mem_num)<> @rcnt

BEGINPRINT ‘Not all adults have an entry in the Member table’PRINT ‘Multi-row insert transaction has been rolled backed..’ROLLBACK TRANSACTION

END

Page 10: SESS-8

SQL SERVER 6.5

Chapter-8/10

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Business rules

The following example involves a member who is discontinuing membership. Amember with outstanding loans can be prevented from being deleted from the database.

If there are no outstanding loans, member can be deleted.

EXAMPLE

CREATE TRIGGER mem_withdrawON member FOR DELETEASIF (SELECT books_on_issue FROM member, deletedWHERE member.mem_no = deleted.mem_no) > 0BEGIN

PRINT ‘Transaction not processed’PRINT ‘Member has books with him’ROLLBACK TRANSACTION

ENDELSEPRINT ‘Member deleted’

Nested and non-nested triggers

Any trigger can contain an UPDATE, INSERT or DELETE statement that affects anothertable.

With nesting enabled, a trigger that changes a table can activate a second trigger, whichcan in turn activate a third trigger and so on.

Nesting is enabled at installation, but can be disabled or enabled using the sp_configuresystem stored procedure.

Triggers can be nested up to 16 levels.

If any trigger in a nested chain sets off an infinite loop, the nesting level is exceeded andthe trigger terminates.

Nested trigger can be used to perform functions such as storing a backup copy of rowsaffected by a previous trigger.

Page 11: SESS-8

SQL SERVER 6.5

Chapter-8/11Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

CLASSROOM EXERCISES

1. What are the ways in which you can display the information about triggers?2. Will the trigger work if you change the name of the object referenced by a trigger? If no, what should be done to make the trigger work?3. What is nesting of triggers?

Page 12: SESS-8

SQL SERVER 6.5

Chapter-8/12

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

STORED PROCEDURES

Stored procedures enhance the power, efficiency and flexibility of SQL Server andimproves the performance of SQL statements and batches.

About Stored Procedures

• Stored procedures are a way to create routines and procedures that are run on theserver, by the server processes.

• These are pre-complied SQL statements and control-of-flow language stored on the

server that execute very quickly. • These routines can be started by an application calling them, or called by data

integrity rules or triggers.

Using Stored Procedures

Stored Procedure can:

• Return values ( the values which are part of the table and also the values that are notthe part of the table but are calculated during the running of stored procedures ) ormodify values

• Compare a user-supplied value against the pre-requisites for information in thesystem.

• Take parameters• Call other procedures• Return a status value to a calling procedure or batch to indicate success or failure

Permissions for creating a stored procedure

• A stored procedure can only be created in the current database.• Permission to execute the procedure that is created is set by default to the owner of

the database, who can transfer it to the other users.

Page 13: SESS-8

SQL SERVER 6.5

Chapter-8/13Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Creating stored procedures

Stored procedures are created using the CREATE PROCEDURE statement.

Syntax:

CREATE PROCedure [owner.] procedure_name[ ;number]

[@parameter_name datatype [ = default] [ OUTPUT]...

[FOR REPLICATION] | [WITH RECOMPILE], ENCRYPTION

AS sql_statements

EXAMPLE

CREATE PROCEDURE all_membersAS SELECT * FROM members

OUTPUT:

• A procedure called all_members has been created that contains a SELECT statement to display allrows of the table member

.

Execution

• After a procedure is created, its name is entered on a line to execute the procedure.• If the name of the stored procedure is preceded with other statements, the keyword

EXEC needs to precede the name of the stored procedure.

EXAMPLE

The procedure all_members created in the previous example can be executed as follows:

all_members /* Executes procedure when not preceded by any other statements */

Page 14: SESS-8

SQL SERVER 6.5

Chapter-8/14

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

OUTPUT:

• All records of the member table will be displayed.

OR

SELECT * FROM applicant /* When preceded by other statementEXEC insert_procedure such as SELECT. */

OUTPUT:

• All records of the applicant table will be displayed first.

• Then, all records from the member table will be displayed.

;number option

• The semicolon and an integer after the name of the stored procedure enables to createmultiple versions of a procedure with the same name.

• When the procedure is executed, the version number determines the version of theprocedure to be executed.

• If no version is specified, the first version is executed. • A single DROP PROCEDURE statement will drop all the versions of the stored

procedure. • After procedures have been grouped, individual procedures within the group can not

be dropped.

EXAMPLE

CREATE PROCEDURE pr;1 /* Creates version 1 of theAS procedure pr */PRINT ‘Version 1’

CREATE PROCEDURE pr;2 /* Creates version 2 of theAS procedure pr . */PRINT ‘Version 2’

OUTPUT:

• When the procedure pr;1 is executed, it prints ‘Version1’.

• When procedure pr;2 is executed, it prints ‘Version 2’.

• When procedure the group name is specified to execute the procedure ,the first version gets executedand ‘Version 1’ is printed.

Page 15: SESS-8

SQL SERVER 6.5

Chapter-8/15Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Execution of procedure Output

pr;1 Version 1pr;2 Version 2Pr Version 1

Using parameters with procedures

• If a procedure is executed that calls another procedure, the called procedure canaccess objects created by the calling procedure.

• Parameters can be used to pass the information into a procedure from the command-line.

• This is done by defining the parameters with the CREATE PROCEDURE statementusing the following options.

@parameter_name

• It specifies a parameter in the procedure.• One or more parameters can be declared in the CREATE PROCEDURE statement.• When the procedure is executed the user must supply the value of each declared

parameter.• Parameter name is always preceded by the symbol ‘@’.

datatype

• It specifies the datatype of the parameter.• All system-supplied and user-defined datatypes are supported except the image

datatype.

default

• It specifies the default value of the parameter.• If a default is default is defined a user can execute the procedure without specifying ,

a value for that parameter.

Page 16: SESS-8

SQL SERVER 6.5

Chapter-8/16

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

EXAMPLE

CREATE PROCEDURE insert_proc /* A procedure insert_(@p1 char (10), @p2 char (20) , @p3 int) proc is created AS which defines 3INSERT INTO table1 parameters */ VALUES (@p1, @p2, @p3)

insert_proc ‘Harry’, ‘Gill’, 222 /* Using INSERTstatement threevalues are suppliedfrom the commandline to theprocedure whichinserts the valuesinto the tabletable1 */

SELECT * FROM table1 WHERE code = 22 /* Lists the record justinserted into thetable through theprocedure */

OUTPUT option

EXAMPLE

Creation of a stored procedure

CREATE PROCEDURE p1@a1 smallint,@a2 smallint,@result smallint OUTPUT

ASSELECT @result = @a1 * @a2

GO

Executing store procedure

DECLARE @var smallintSELECT @var = 40EXEC p1 3, 4, @var OUTPUTSELECT ‘The result is :’, @varGO

OUTPUT:

The result is: 12

Page 17: SESS-8

SQL SERVER 6.5

Chapter-8/17Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

• In the above example, a stored procedure is created which calculates the product oftwo numbers.

• Then a batch calls this procedure to obtain the product of the number 3 and 4.• The batch first loads a value in the @var just to verify that it will be replaced but the

correct result during the call to p1.• If the keyword OUTPUT were omitted from the procedure call, the call would still

execute but the value of @var would be unchanged by the execution of the procedure.• If the OUTPUT keyword were omitted from the procedure definition but left in the

procedure call then an error condition would exist because the batch would be askingthe stored procedure for output that the stored procedure was not written to produce.

RECOMPILE option

• Should be used when you are executing stored procedures with atypical parametersfor example, where the plan stored for the procedure might not be optimal for thatparameter.

EXAMPLE

Example 1

CREATE PROC testproc @title_no title_no WITH RECOMPILEAS SELECT * FROM loanWHERE title_no= @title_no

OUTPUT:• Recompiles and optimizes every execution of the stored procedure and creates a new query plan.

Example 2

EXEC sp_help WITH RECOMPILE

OUTPUT:• Creates new query plan during the execution of the stored procedure. The new execution plan is stored

in the cache.

Example 3

sp_recompile title

• The option causes any stored procedures and triggers that use the named table to be recompiled thenext time it runs.

Page 18: SESS-8

SQL SERVER 6.5

Chapter-8/18

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

ENCRYPTION option

• Encrypts the syscomments table entry that contains the text of the CREATEPROCEDURE statement.

Stored procedure rules and guidelines

• The name of the stored procedure should follow the rules of naming an identifier.• An object can not be referenced in the stored procedure definition if it does not exists.• Except CREATE statements, any number and any type of SQL statements can be

included in stored procedures.• The CREATE PROCEDURE statement can not be combined with other SQL

statements in a single batch.• The maximum number of parameters in a stored procedure is 255.• Temporary tables can be referenced within a procedure.• If a procedure is executed that calls another procedure, called procedure can access all

objects except temporary tables created by the first procedure.• If a private temporary table is created inside a procedure, the temporary table exists

only for the purposes of the procedure; it disappears when you exit the procedure.• Private and public temporary stored procedures analogous to temporary tables can be

created.• ‘#’ prefix to the procedure name denotes a private temporary stored procedure.• ‘##’ prefix to the procedure name denotes a public temporary stored procedure.

Information on stored procedure

• To list the definition of the procedure, the system stored procedure sp_helptext isexecuted.

• Procedures created with the ENCRYPTION option can not be viewed withsp_helptext.

• For a report on the objects referenced by the stored procedure, use the sp_dependssystem stored procedure.

• sp_help system stored procedure can be used to list information about the procedure

Auto execution stored procedure

• It is possible to have one or more stored procedures execute automatically when SQLServer starts.

• Execution of the stored procedure starts when the last database has been recovered atstartup.

• Infinite number of start up procedures can be present.• Each startup procedure consumes one connection when executing.

Page 19: SESS-8

SQL SERVER 6.5

Chapter-8/19Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

• If multiple procedures need to be executed at startup and you don’t need to executethem in parallel only one procedure can be made as the startup procedure and thatprocedure can call other procedures.

• This will use only one connection.

System stored procedure Description

sp_makestartup Makes an existing stored procedure a startup procedure.sp_unmakestartup Stops a procedure from executing at startupsp_helpstartup Provides a list of all procedures that will execute at startup.

EXAMPLE

CREATE PROCEDURE testproc /* Creates a procedure calledINSERT t1 DEFAULT VALUES testproc , which inserts default

values into the table t1 */

sp_makestartup testproc /* Makes the procedure testproc as startup procedure. */

sp_helpstartup /* Lists all the startup procedures defined. */

Executing a Stored Procedure on a remote server

• Stored procedures residing on a remote server are called remote stored procedures.• Remote stored procedures can be executed from the local server.• To use remote stored procedures, you must have remote servers established.• A remote server on a SQL Server network is a server that a user can access through

the local server.• When servers are configured to allow remote stored procedures, this information is

stored in sysservers and sysremotelogins system tables in the master database.• A client connected to one SQL server, when executes the remote stored procedure on

another SQL Server, client connection to that SQL server is not established.• The server to which the client is connected accepts the client’s request and send it to

the remote server on client’s behalf.• Remote server processes the request and sends the results to the original server.• The original server, then, in turn passes the results to the client.• Remote stored procedures request can also be initiated by the server.

Page 20: SESS-8

SQL SERVER 6.5

Chapter-8/20

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Syntax:

EXECUTE servername.dbname.owner.stored_procedure_name

• Client includes the EXECUTE statement as part of a normal batch submitted to thelocal server.

EXAMPLE

EXEC sp_addlogin user1EXEC server2.master.sa.sp_addlogin user1

OUTPUT:

• The login name user1 is added to both the servers i.e to the local server as well as the remote serverserver2.

Conditions for implementing remote store procedures

• A server must allow remote access from other servers. By default, access is allowed.• To turn off this feature, use sp_configure to turn off the Remote Access

configuration option.• Each server must store both its own name as the local server (stored by default) and

the name of the other server in the sysservers table.• The login ID that the local server uses when opening the connection must exist on the

remote server.

Page 21: SESS-8

SQL SERVER 6.5

Chapter-8/21Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Processing of Stored Procedures

DIAGRAM

Parsing

Stored Procedure

Resolve namesNormalize

Resolve viewsResolve

aggregatesProtection Map

Name stored in sysobjects tableText stored in syscomments table

Decision Compile

Query tree stored in sysprocedurestable

Execute

Execution plan held temporarily inprocedure cache

Page 22: SESS-8

SQL SERVER 6.5

Chapter-8/22

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

Creation

• When a stored procedure is created, it is analysed by the query processor.• It prepares an internal normalized structure for the procedure called as query tree. The

stored procedure is placed in the following system tables: Stored procedure’s Name sysobjects Text syscomments Query tree sysprocedures Execution • When a stored procedure is executed for the first time, the procedure is brought into

the memory and compiled• The fully compiled form called as execution or procedure plan is then stored in the

procedure cache - SQL Server’s temporary memory buffer.• The execution plan is not stored permanently in a system table.• The execution plan remains in the procedure cache unless other memory needs force

it out so that the next request for execution can be processed without any compilationoverhead.

CLASSROOM EXERCISES

1. Can a trigger contain a stored procedure?2. How can the text of a stored procedure and a trigger be viewed?

Page 23: SESS-8

SQL SERVER 6.5

Chapter-8/23Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

LAB EXERCISES

1. Create a trigger called warn which prints a message to the user when he tries to add or change the data in the table titles of pubs database.2. Create a trigger that updates the ytd_sales column in the titles table every time a new row is added to the sales table. Update the ytd_sales column in the titles table such that ytd_sales is equal to its previous value plus the value added to the qty field of sales table.3. Create a trigger that updates ytd_sales column in the titles table every time one or more sales rows are deleted.It updates the ytd_sales column in the titles table so that ytd_sales is equal to its previous value minus the value subtracted from sales.qty.4. Display the information about all the available triggers in the database.5. Drop the triggers.6. Create a stored procedure which shows the list of tables available in the database.7. Create a stored procedure such that if authors first name and last name are given, it displays the title and publisher of each of that author’s books. (Use pubs database)8. Create a procedure which displays the name of all authors who have written a book published by the publisher given as a parameter. If no publisher name is supplied, the procedure should show the authors published by ‘Algodata Infosystems’.9. Create a procedure that performs division of two integer variables . The third variable should be defined as an output parameter. If the divisor is 0, value 100 should be returned, otherwise 0 should be returned. Check by displaying the return value as well as the third variable defined as output parameter.

Page 24: SESS-8

SQL SERVER 6.5

Chapter-8/24

Copyright Tata Infotech Ltd. : Copying of this document in part or full is not permitted without express authority.

SUMMARY

Trigger is a special kind of stored procedure that is invoked whenever an attempt is madeto modify the data in the table it protects.

Triggers are created using CREATE TRIGGER statement.

A table can have only three trigger actions UPDATE, INSERT and DELETE.

When INSERT trigger is executed, new rows are added to the trigger table as well as alogical table called inserted.

When a DELETE trigger statement is executed, rows are deleted from the table and areplaced in table deleted.

When an UPDATE trigger statement is executed, original rows are moved to deletedtable and update row is inserted into the inserted table and the table being updated.

Stored procedures are pre-compiled SQL statements stored on the server.

Stored procedures are created using CREATE PROC statement.

Auto execution stored procedure are created using the system stored proceduresp_makestartup.