para-WITH RECOMPILE will force SQL Server to create a new execution plan each andevery time you execute the stored procedure and is the best way to create a stored pro-cedure that has in
Trang 16 On the third screen, check the Insert box next to the authors table Click Next.
7 On the final screen, click the Edit button.
8 On the Edit screen, change the name of the stored procedure to Authors_Insert,
then click OK
Trang 29 On the final screen, click Finish Note that the Edit button will allow you to
change the code used to create the stored procedure, but you do not want tomake any changes here
UNDERSTANDING STORED PROCEDURES
Trang 3If you would like to see exactly what this stored procedure will do for you, open itand look at its properties in Enterprise Manager You will notice in Figure 14.1 that it
is a simple stored procedure that uses input parameters to insert new records into theauthors table
FIGURE 14.1
The Create Stored Procedure Wizard is designed to create quick, simple stored procedures.
Now that you know how to create and use stored procedures, you need to know how
to keep them running fast Let’s get a little more in depth on how they work andhow to optimize them
Optimizing Stored Procedures
To optimize a stored procedure, it is best for you to understand a little more abouthow SQL Server executes queries When SQL Server first executes a query (any query,not just stored procedures), it compiles the query first The compiling process is justSQL Server peering inside your query to see what you are trying to accomplish Specif-ically, SQL Server looks at what tables you are JOINing and what columns you havespecified in the WHERE clause of your query Once the server has this knowledge, it
can develop an execution plan, which is a map of what indexes would return data
fastest Once the execution plan has been devised, SQL Server stores it in procedurecache, which is an area of RAM that has been specifically apportioned for this purpose
Trang 4Now, whenever you run the same query again or a very similar query, SQL Server doesnot need to create another execution plan to get your data; it simply uses the execu-tion plan that has been stored in the procedure cache
This can cause a problem for you at times, though For instance, you may need tochange the structure (or schema) of your database, adding a new table or columns to
an existing table If this kind of change occurs, SQL Server will automatically pile your stored procedures to use the changes in the structure The only time thestored procedure will not be recompiled is if you create a new index; in that instance,you must recompile the stored procedure manually so that SQL Server can create anexecution plan that takes advantage of the new index
recom-Or, suppose that you have a stored procedure that uses widely varied input meters every time you run it Some of those parameters may affect the JOIN orWHERE clause statements in the stored procedure, and because SQL Server uses thoseparameters to create an execution plan, it may not be wise to use the same executionplan every time the stored procedure is run—you may want to recompile it You havetwo ways to force SQL Server to recompile your stored procedure; the first is by creat-ing it with the WITH RECOMPILE statement
para-WITH RECOMPILE will force SQL Server to create a new execution plan each andevery time you execute the stored procedure and is the best way to create a stored pro-cedure that has input parameters that change drastically every time you use it (andaffect the JOIN and WHERE clauses in the stored procedure) For example, if youwanted to recompile the Show_Authors stored procedure every time you run it, thecode to create it would look as follows:
CREATE PROCEDURE Show_Authors
@city varchar(50)WITH RECOMPILEAS
SELECT au_fname, au_lname, address, city, state, zipFROM authors
WHERE city = @cityORDER BY au_lname DESC
It is the WITH RECOMPILE option that tells SQL Server to create a new executionplan every time the stored procedure is executed and not store that execution plan incache That can be tedious and slow if you need to change the execution plan onlyoccasionally, though If that is the case, you should use the second method for recom-piling a stored procedure: the EXECUTE…WITH RECOMPILE statement EXECUTE…
WITH RECOMPILE tells SQL Server to create a new execution plan just this one time,not every time the statement is executed If you use this statement, the code used to
UNDERSTANDING STORED PROCEDURES
Trang 5create the stored procedure does not change, but when you execute the stored dure, it looks as follows:
proce-EXEC Show_Authors WITH RECOMPILE
By using these RECOMPILE statements, you can keep your stored procedures runningfast However, thus far, you haven’t secured them from prying eyes—let’s do that now
Securing Your Stored Procedures
When you create a stored procedure, you are just creating a query that is stored onthe server rather than on the client machines These stored procedures are contained
in the syscomments system table in each database and are completely accessible bydefault This means that by executing a simple SELECT query against the syscom-ments table in the database where the stored procedure was created, your users couldsee all of the code used to create the procedure This may not be desirable because one
of the main uses of a stored procedure is to remove the user from the complexity andstructure of the underlying tables, and, as we will discuss in Chapter 18, stored proce-dures are used for securing tables as well By reading the definition of the stored pro-cedure right from syscomments, the users would be bypassing that security; in otherwords, they would be hacking To avoid that, you should create stored proceduresusing the WITH ENCRYPTION statement
WITH ENCRYPTION is designed to keep prying eyes out of definitions stored inthe syscomments table—not just for stored procedures, but for everything storedthere (views, triggers, etc.) In the following exercise, you will execute a SELECT queryagainst the syscomments table in the pubs database to see what is stored there and,therefore, what your users could see:
1 Open Query Analyzer and log in using Windows NT Authentication (unless you
need to use SQL Server Authentication)
2 Enter the following code and execute it by clicking the green arrow button on
the toolbar (you have to join the sysobjects table because the name is storedthere—only the ID is stored in syscomments):
USE PubsSELECT ob.name, com.text FROM syscomments comJOIN sysobjects ob
ON ob.id = com.idWHERE ob.name = ‘Show_Authors’
Trang 63 Notice in the result set that you can read the code used to create and run the
stored procedure
4 To encrypt it, open Enterprise Manager, expand the pubs database, then select
the Stored Procedures icon
5 In the contents pane, double-click the Show_Authors stored procedure to bring
up the properties
6 To encrypt the stored procedure, change the definition to look as follows (notice
the bold changes):
CREATE PROCEDURE DBO.Show_Authors
@city varchar(50) = ‘Oakland’
WITH ENCRYPTION
ASSELECT au_fname, au_lname, address, city, state, zipFROM authors
WHERE city = @cityORDER BY au_lname DESC
UNDERSTANDING STORED PROCEDURES
Trang 77 Click OK to apply the changes.
8 To verify that it has been encrypted, double-click Show_Authors to bring up the
properties again You should receive an error message stating that the object isencrypted and therefore unreadable Click OK to return to the stored procedureproperties screen
9 Return to Query Analyzer and execute the query from step 2 again; notice that
this time you cannot read the text from syscomments, because it is full ofunreadable characters (these characters may vary depending on your system)
Trang 810 Close Query Analyzer.
WAR N I N G Once you create an object, such as a stored procedure, using WITHENCRYPTION, you cannot decrypt the object Make sure you are finished modifying theobject for a while before encrypting
User-defined stored procedures (the ones you make yourself) are a very powerful tool,but they are not the only stored procedures with which you have to work Microsoft hasgiven you a batch of ready-made stored procedures that are designed to help you workwith system tables These are called system and extended stored procedures
Using System and Extended Stored Procedures
Microsoft has started using the term metadata quite a bit these days; it means tion about information When the term is applied to SQL Server, it means informationabout objects on the server, such as how big a database file is or what permissions auser has When you want to change or read such system information, you could openthe system tables directly and start fiddling with the data inside, but that usually turns
informa-UNDERSTANDING STORED PROCEDURES
Trang 9out badly because most of the values in the system tables are not designed to be stood by mere mortal humans (most of the values in these tables are numeric and noteasily decoded) A much better way, the supported way, to change or read the systeminformation is by using system stored procedures.
under-Using System Stored Procedures
Every time you add a database, add a login (which is used to grant access to SQL Server),create an index, or add or modify any object on the server, you are making changes tothe system tables, which is where SQL Server stores information about your objects Theinformation stored in these system tables is mostly numeric data, which is difficult toread, let alone modify, directly That is why Microsoft has given you scores of storedprocedures (about 650) to help with the task of modifying system tables They are all
stored in the master and msdb databases, and most begin with the characters sp_ Here
is a synopsis of some of the more common system stored procedures:
sp_tables: This stored procedure will show you any object that can be used
in the FROM clause of a SELECT query This is useful if you have forgotten orjust don’t know the exact name of the table or view you need to query
sp_stored_procedures: This will list all of the stored procedures availablefor your use Again this is useful if you have forgotten or just don’t know thename of the procedure you need
sp_server_info: Using this procedure is the best way to determine how yourSQL Server was configured at setup, such as the character set or sort order thatwas defined at install, what version of SQL Server you are running (for exam-ple, desktop or standard), etc
sp_databases: This lists all of the available databases on the server It can beuseful for finding database names
sp_start_job: This is used to start an automation job in SQL Server This isvery handy for jobs that are scheduled on demand We’ll be discussing jobs andautomation in Chapter 17
sp_stop_job: This procedure will stop a job that has been started already
sp_addlogin: This procedure is used to add a standard login to the server toallow users access to the server as a whole This is very useful for creating ascript that will regenerate user logins in the event of a system crash We’ll dis-cuss security and logins in Chapter 18
sp_grantlogin: This is used to grant access on SQL Server to a Windows NTaccount This should be combined with the sp_addlogin account to create ascript to re-create user accounts in the event of a disaster
Trang 10sp_setapprole: An account role in SQL Server (as you will see in Chapter 18)
is used to make sure that only approved applications are used to access yourdatabase This stored procedure activates the application role so that the usercan access the database with the permissions that are granted to the applica-tion role
sp_password: As you will see in Chapter 18, there is a difference betweenstandard and Windows NT login accounts; this stored procedure is used tochange passwords for standard, and only standard, logins
sp_configure: Several global configuration options can be set to change theway SQL Server behaves For example, you can tell the server whether to allowupdates to system tables directly or how much system memory to use Thesp_configure stored procedure can be used to change such options The avail-able options are listed here:
• max degree of parallelism
• max server memory
• max text repl size
• max worker threads
• media retention
• min memory per query
• min server memory
Trang 11• network packet size
• remote login timeout
• remote proc trans
• remote query timeout
• resource timeout
• scan for startup procs
• set working set size
• show advanced options
sp_processmail: SQL Server is capable of not only sending, but receivingand responding to e-mail When SQL Mail is configured (which you will learnhow to do in Chapter 17), you can send a query via e-mail to the MSSQLServerservice When you run this stored procedure, the MSSQLServer service will readthe query in the e-mail and send back the result set
Trang 12sp_rename: This will change the name of any object in the database.
sp_renamedb: This will change the name of the database itself
sp_help: This can be used to find information about any object in the base It returns properties such as created date, column names, foreign-key con-straints, etc
data-sp_helptext: This is used to display the actual text that was used to create
an object in the database This information is read from the syscommentstable
sp_help*: There are many other stored procedures that have sp_help as thefirst few characters All of them are designed to give you specific informationabout a type of object in the database
These system stored procedures are used like any other stored procedure Let’s look
at an example:
1 Open Query Analyzer from the SQL Server 2000 group under Programs on the
Start menu and log in with Windows NT Authentication (unless you must useSQL Server Authentication)
2 To use sp_help to get information about the authors table in the pubs database,
enter and execute the following code:
USE PubsEXEC sp_help ‘authors’
UNDERSTANDING STORED PROCEDURES
Trang 133 To see how your SQL Server is faring at the moment, use the sp_monitor stored
procedure:
EXEC sp_monitor
4 Close Query Analyzer.
Trang 14Using Extended Stored Procedures
Another type of stored procedure is the extended stored procedure These do just what
the name implies: They extend the capabilities of SQL Server so that it can do thingsthat a database server would not ordinarily be capable of doing For example, youwouldn’t expect a database server to be able to execute a command from the com-mand prompt, but thanks to an extended stored procedure that comes with SQLServer, called xp_cmdshell, SQL Server can do just that
Extended stored procedures are just C++ code saved in and executed from aDynamic Link Library (DLL) Most of the extended stored procedures are executedwith other system stored procedures, so you won’t use them very often by them-selves, but here is a short list of the ones you may use:
xp_cmdshell: This stored procedure is used to run programs that are narily run from the command shell, such as the dir command or md (makedirectory) This comes in very handy when you need to have SQL Server create
ordi-a directory for ordi-automordi-aticordi-ally ordi-archiving BCP files or something of thordi-at nordi-ature
xp_fileexist: This procedure can be used to test for the existence of a fileand, if that file exists, to do something (such as BCP) with it The followingcode shows you how to test for the existence of the autoexec.bat file If @ret =
1, the file exists; if it equals 0, the file does not exist This is not documented inBooks Online or on the Microsoft Web site, so we will give you the syntax here
The second line declares a variable to hold an output parameter, the third linecalls the procedure with an output parameter, and the fourth line displays theoutput (note that this must be done in the master database):
USE MasterDECLARE @ret intEXEC xp_fileexist ‘c:\autoexec.bat’, @ret outputSELECT @ret
xp_fixeddrives: This shows you the drive letters of the fixed disks and howmany MBs of available space are on each one
Again, each of these extended stored procedures is executed just like a regularstored procedure Let’s try some here:
1 Open Query Analyzer from the MS SQL Server group under Programs on the
Start menu and log in with Windows NT Authentication
2 To use xp_cmdshell to get a directory listing of your C drive, enter and execute
the following code:
EXEC xp_cmdshell ‘dir c:’
UNDERSTANDING STORED PROCEDURES
Trang 153 To see whether you have a file named autoexec.bat on your C drive, enter and
execute the following code (it will return a 1 if the file exists):
DECLARE @ret intEXEC xp_fileexist ‘c:\autoexec.bat’, @ret outputSELECT @ret
4 Close Query Analyzer.
Trang 16Summary
In this chapter, you learned all about stored procedures You learned first what theyare—just a collection of Transact-SQL statements, usually a query, that is stored cen-trally on the server waiting to be executed by users The advantage to storing thesecentrally is that when your users execute them, they are not sending hundreds oflines of code over the network and thus bogging it down—they are sending only one
line of code: EXEC stored_procedure These stored procedures are also easier to
man-age than dispersed code because when you need to make a change to the code, youhave to do it only at the server rather than running around to each client machine
After learning what stored procedures are, you learned how to create them Youlearned first how to create a simple stored procedure that returns a result set to theuser using static parameters that cannot be changed Next you learned how to allowusers to control the information they get back by using input and output parameters
Then you learned how to create a simple query for inserting, updating, or deletingdata using the Create Stored Procedure Wizard
Trang 17Once that section was complete, you learned how to optimize some stored dures by recompiling them when necessary Then you learned that all stored procedureshave a record associated with them in the syscomments table that contains all of thetext that is used to create and execute the procedure To secure this code, you learnedthat you can encrypt the entry in syscomments with the WITH ENCRYPTION clause.After that, you discovered the power of system and extended stored procedures.The system stored procedures are the easiest and best way to modify system data, andthe extended stored procedures are used for extending the abilities of SQL Serverbeyond those of a normal database server.
proce-Now that you have stored procedures under your belt, you can make access to yourdata faster and more efficient However, you still need to be able to control what theusers are putting in those databases In the next chapter, we will introduce you to onemethod of controlling that data: using triggers
Trang 18CHAPTER 15
Using Triggers
F E A T U R I N G : Understanding Triggers 538 Advanced Considerations 560
Trang 19As a database administrator or developer, you want to be able to control
what data your users are inserting, updating, or deleting in your tables Forexample, you may not want a user to be able to delete a customer accountfrom one table if there is a pending sale for that account in another table.For that type of control, a simple foreign-key relationship will work just fine
Another example would be when you want your users to insert and update data,but not delete it In that instance, you would just need to modify the security settings
on your server to deny delete permissions to your users for that one table (we’ll cuss permissions in Chapter 18)
dis-Suppose, though, that you have a credit limit column in your customers table andthat you do not want users to be able to increase that credit limit past $10,000 with-out management approval Or suppose that you want to automatically notify a man-ager every time a customer is deleted from a database so that the manager can ask theperson who deleted the account for details Maybe you want to know when a user hasinserted a new customer so that you can track the user’s sales and give them a big, fatbonus later In each of these examples, you cannot use the simple permissions or foreign-key relationships—you need to use triggers
In this chapter, we are going to discuss all four types of triggers: INSERT, UPDATE,DELETE, and INSTEAD OF We’ll see not only how they work, but also how you canuse them to enforce complex business logic on your databases We’ll begin by getting
a basic understanding of triggers
Understanding Triggers
A trigger is a collection of SQL statements that looks and acts a great deal like a stored
procedure (which we discussed in Chapter 14) The only real difference between thetwo is that a trigger cannot be called with the EXEC (short for execute) command;triggers are activated (or fired) when a user tries to insert, update, or delete data Forexample, suppose that you have defined an INSERT trigger on a customer informationtable that states that your users cannot add a new customer from outside the UnitedStates As soon as any user tries to insert a new customer, the INSERT trigger will exe-cute and determine whether the record passes the criteria set forth in the trigger Ifthe record passes, the insert is completed; if the record does not pass, the record is notinserted
SQL Server is able to block data modifications if they don’t pass your stringent
cri-teria because triggers are considered transactions A transaction (as discussed in
Chap-ter 8) is a block of Transact-SQL code that SQL Server treats as a unit Code is grouped
Trang 20into a transaction by placing a BEGIN TRAN statement at the beginning of the code
and a COMMIT statement at the end, either by the user (an explicit transaction) or by SQL Server (an implicit transaction) Because a trigger is seen as a transaction, you
need to add only the ROLLBACK command to the appropriate spot in the code if youdon’t want to let a record pass the trigger The ROLLBACK command will cause theserver to stop processing the modification and disallow the transaction, forgettingthat it ever took place (this is true of all types of triggers)
To go one step further, you can send an error message to the user who tried to late the trigger by using the RAISERROR() command If you want to get really fancy,you can even tell on them and have the error message sent to a manager
vio-In this sense, triggers can be thought of as database watchdogs If you’ve neverseen a watchdog in action, it may help to visualize it A watchdog is generally used toguard animals out in the pasture—cows, sheep, horses, etc The watchdog just quietlysits and waits, doing nothing, until something happens—such as a predator
approaching the flock As soon as that predator comes up, the watchdog springs intoaction, barking, chasing, and attacking until the predator has been vanquished Trig-gers act in the same way, waiting quietly on the database server until a user tries tomodify data, then springing into action to enforce your business logic
Of course there are other ways to enforce business logic For example, you learnedabout foreign-key relationships in Chapter 4 With a foreign-key relationship inplace between a customers table and an orders table, you can keep your users fromdeleting a customer with a pending order You can also keep a user from inserting anorder for a customer who does not exist in the customers table
You will also learn about permissions in Chapter 18, where you will find that youcan deny users the permission to insert, update, or delete If, for example, you denyinsert permission to some of your users, those users cannot insert any records at all
The same goes for the update and delete permissions—if any of these are denied, theaction just does not take place If any of these permissions are granted, the users can
do whatever they would like with very little inhibition
These methods are great for implementing simple business logic, such as marketing
cannot delete, but they can insert or customers cannot be deleted if they have a pending order Most companies have business logic that is a great deal more complex than
that They may, for example, have a business rule that states sales cannot update a
user’s credit limit to exceed $10,000 without management approval or a user may not delete
a customer with a credit limit above $10,000 These are very common business rules that
cannot be implemented by using the foreign-key relationships or permissions on atable Only by using triggers can you properly enforce this complex business logic
Let’s start that process now, by working with INSERT triggers
Trang 21Working with INSERT Triggers
INSERT triggers can be used to modify, or even disallow, a record being inserted Agood example of how to use an INSERT trigger might be keeping users from addingcertain types of records, such as customers with a credit limit over $10,000 Anotherexample might be adding data to the record being inserted, perhaps adding the datethat the record was created or the name of the user inserting the record You can evenuse an INSERT trigger to cascade changes to other tables in your database For example,suppose that you have two databases: a contact manager database and a humanresources database Many companies keep the same information in both databasesbecause they want to have employee information listed as a contact as well An INSERTtrigger (as well as UPDATE and DELETE triggers) can cascade updates in one database
to the other to keep all information in both databases current
INSERT triggers fire off (are executed) every time someone tries to create a new record
in a table using the INSERT command As soon as a user tries to insert a new record into a
table, SQL Server copies the new record into a table in the database called the trigger table and a special table stored in memory called the inserted table As shown in Figure 15.1, this
means that your new record exists in two tables, the trigger table and the inserted table.The records in the inserted table should exactly match the records in the trigger table
FIGURE 15.1
SQL Server places newly created records
in the trigger table and the inserted table.
Inserted is a valuable table when you need to cascade changes to other tablesthroughout the database For example, suppose you have a database that containscustomer, order detail, and product inventory information Every time you sell anorder to a customer, you need to subtract the total of the order from the inventory inthe products table to keep the inventory current There are two ways to do this First,
you could store the amount of product sold to the customer in a memory variable
(which is a temporary storage area created in memory) and update the products tablewith a second UPDATE statement, but that requires extra code, which can slow thesystem down and therefore is not a clean solution The second way involves using thelogical inserted table The value that you need is being stored in two places, the trig-ger table and the inserted table, so you can just pull the value from inserted and apply
Table 1 (trigger table)
INSERT Table 1 VALUES(“New,” “Customer”)
Inserted
Trang 22it to order details This means that you can write code into your INSERT trigger toautomatically subtract data from the products table based on values in the insertedtable The code would resemble something as follows:
UPDATE p SET p.instock = (p.instock – i.qty)FROM Products p JOIN inserted I
ON p.prodid = i.prodid
To create this trigger and see how it works, you must meet a few prerequisites First,you will need the sales database you created in Chapter 11 If you don’t have thatdatabase, you will need to refer to Chapter 11 to create it Next, you will need to fillthe tables with some values:
1 Open Query Analyzer by selecting it from the SQL Server 2000 group in
Pro-grams on the Start menu and log in using either Windows NT or SQL ServerAuthentication
2 You need to enter some customers to sell products to Enter and execute the
fol-lowing code to populate the customers table with customer information (ifthese values exist in your table from a previous chapter, you can skip this step;
to verify this, just run the query SELECT * FROM customers):
USE SalesINSERT customersVALUES (‘Jerry’, ‘Jorden’, ’111 Main’, ‘Mesa’, ’AZ’, ‘84312’,
‘6025551212’)INSERT customersVALUES (‘Tom’, ’Smith’, ’609 Georgia’, ’Fresno’, ’CA’, ’33045’,
‘5105551212’)INSERT customersVALUES (‘Shane’, ‘Travis’, ‘806 Star’, ‘Phoenix’, ‘AZ’, ‘85202’,
‘6021112222’)
3 You need some products to sell To populate the products table with product
and inventory information, enter and execute the following code:
INSERT ProductsVALUES (‘Giant Wheel of Brie’, 200)INSERT Products
VALUES (‘Wool Blankets’, 545)INSERT Products
VALUES (‘Espresso Beans’, 1527)INSERT Products
Trang 234 Close Query Analyzer.
Now that you have populated the tables in the sales database with data, you areready to create a trigger that will automatically update the instock column of theproducts table based on the amount of product sold to a customer To do that, youwill create an INSERT trigger on the orders table, because when you sell something to
a customer, you insert a new record in the orders table:
1 Open Enterprise Manager by selecting it from the SQL Server 2000 group under
Programs on the Start menu and expand your server, then databases, then thesales database
2 Select the Tables icon under the sales database.
3 In the right pane, right-click the orders table and select Manage Triggers under
All Tasks
4 In the Properties dialog that comes up, change the code to look as follows:
CREATE TRIGGER InvUpdate ON [Orders]
FOR INSERT AS
UPDATE p SET p.instock = (p.instock - i.qty)FROM Products p JOIN inserted i
ON p.prodid = i.prodid
5 Check your syntax and then click OK to create the trigger
Trang 24With the INSERT trigger in place on the orders table, you are ready to test the ger In the following series of steps, you will create a new record in the orders table(thereby simulating an order by a customer) to cause the INSERT trigger to fire Thisshould reduce the instock amount in the products table:
trig-1 To test the trigger, select Query Analyzer from the Tools menu in Enterprise
Manager
2 Enter and execute the following code to verify the instock quantity for item 1 (it
should be 200):
USE SalesSELECT prodid, instockFROM Products
3 To cause the INSERT trigger to fire off, you will insert a new record in the orders
table To do this, click the New Query button (the icon on the toolbar that lookslike a blank piece of paper with a folded corner), and enter and execute the fol-lowing code, which assumes that you are selling 15 count of product number 1
to customer ID 1 on today’s date (GETDATE() is used to return today’s date):
USE SalesINSERT Orders
Trang 25VALUES (1,1,15,getdate())
4 To verify that the INSERT trigger fired off and removed 15 from the instock
col-umn of the products table, click the New Query button, and enter and executethe following code:
USE SalesSELECT prodid, instockFROM Products
5 Notice that the exact quantity you sold customer number 1 (qty 15) was subtracted
from the total instock quantity of prodid 1 You now have 185 instead of 200
6 Close Query Analyzer.
Did you see what happened here? You created an INSERT trigger that referenced thelogical inserted table Whenever you insert a new record in the orders table now, thecorresponding record in the products table will be updated to subtract the quantity ofthe order from the quantity on hand in the instock column of the products table.The next type of trigger that we will look into is just as powerful Let’s delve intoDELETE triggers