SQL SERVER database development trigger application

Source: Internet
Author: User
Tags datetime getdate sql server books rowcount system log

SQL SERVER database development trigger application

Question: SQL SERVER database development trigger application
Author: Cultivator
Date: 2006-01-10
Note: Due to limited personal abilities, errors or omissions may inevitably occur in the article. Please forgive me! At the same time, you are welcome to point out so that I can modify it in time to avoid misleading the next viewer. Finally, I hope this article will help you.

I don't know how many friends in the jar use the trigger. If you already know the trigger, skip this article. If you have not used the trigger before, let's get to know each other.

QUOTE:
Definition:
A trigger is a special type of stored procedure that you cannot directly call. When you use one or more of the following data modification operations to modify data in a specified table, the trigger will take effect: UPDATE, INSERT, or DELETE. Triggers can query other tables and contain complex SQL statements. They are mainly used to force complex business rules or requirements.

A trigger application maintains and maintains data integrity and legitimacy. How can this problem be understood? That is to say, you can submit any data in the program, and then use the trigger to judge the integrity and validity of the data. Of course, this is just an example. This is not recommended in actual applications, data integrity and legitimacy should be verified by applications.

Next, I will describe the trigger application as an instance.

Set: There are two tables in the current database: "uMateriel" and "uRecord", which are used to save the item information and the entry and exit records of the item respectively. The structure is as follows:

QUOTE:
UMateriel
----------------
MId int
MName nvarchar (40)
MNum int DEFAULT 0

URecord
----------------
RId int
MId int
RNum int
RDate datetime DEFAULT GetDate ()
RMode bit DEFAULT 0

Now, the data table is available. Now let's take a look at the actual application.

Now, we want to purchase item A with A quantity of 100. The time is the day and the number of known item A is 1. Generally, we need to perform the following two steps:

QUOTE:
1. Add an item A purchase record in the uRecord record table:
Insert into uRecord (mId, rNum, rMode) VALUES (1,100, 0)

2. Update the number of item A in the uMateriel inventory table:
UPDATE uMateriel SET mNum = mNum + 100 WHERE mId = 1

That is to say, the above two statements must be processed in the code to ensure inventory accuracy. Take ASP code as an example:

QUOTE:
On Error Resume Next

'// Set adoConn to the connected ADODB. Connection object
With adoConn
        '// Start the transaction. Because the multi-step data update operation is involved, the transaction is used here.
. BeginTrans
        '// Insert the entry record
. Execute ("insert into uRecord (mId, rNum, rMode) VALUES (1,100, 0 )")

        '// Update the item inventory record
. Execute ("UPDATE uMateriel SET mNum = mNum + 100 WHERE mId = 1 ")

        '// Determine whether an error has occurred
If Err. Number <> 0 Then
                '// If an error occurs, the transaction is rolled back.
. RollbackTrans
Response. Write "error! "
Err. Clear
Else
                '// If no error occurs, the transaction is committed.
. CommitTrans
End If
End

The above code can update a warehouse receiving record, but today we want to know the trigger application. What content should be written in the trigger to simplify the above code? Create a trigger.

The syntax for creating a trigger is long and simplified:

QUOTE:
CREATE TRIGGERTrigger nameONTable name/View Name
{ FOR | AFTER | INSTEAD}{[DELETE] [,] [INSERT] [,] [UPDATE]}
AS
Trigger content (SQL statement)



QUOTE:
Description of SQL SERVER books online:
AFTER
The specified trigger is triggered only when all specified operations in the SQL statement are successfully executed. This trigger can be executed only after all reference cascade operations and constraints check are completed successfully.
If you only specifyFORKeyword, thenAFTERIs the default setting.
You cannot define an AFTER trigger on a view.

INSTEAD
Specify the trigger to be executed, instead of the SQL statement to be triggered, to replace the trigger statement operation.
In a table or view, each INSERT, UPDATE, or DELETE statement can define up to one INSTEAD trigger. However, you can define a view on each view with an instead of trigger.
The instead of trigger cannot be defined in the updatable view with check option. If an instead of trigger is added to the updatable view WITH the check option specified, SQL Server generates an error. You must use alter view to delete this option before defining the instead of trigger.

{[DELETE] [,] [INSERT] [,] [UPDATE]}
It specifies which data modification statements will be executed on a table or view to activate the trigger keywords. You must specify at least one option. These keywords can be combined in any order in the trigger definition. If more than one option is specified, separate them with commas.
ForINSTEADTrigger. You cannot use the DELETE option ON a table with reference relationships in the on delete cascade operation. Similarly, you cannot use the UPDATE option ON a table that has an on update cascade reference relationship.

Now we create a trigger based on the above syntax (note that the trigger is attached to a table or view, so it can only be created in the table or in the query analyzer ), this trigger is used to automatically update the inventory quantity.

QUOTE:
Create trigger [trUpdateMaterielNum] ON [dbo]. [uRecord]
-- Indicates that the trigger is executed after the record is inserted.
AFTER INSERT
AS
-- Number of the current update
DECLARE @ intID int
-- Number of current updates
DECLARE @ intNum int
-- Current mode
DECLARE @ intMode int

-- Determines whether a record is updated. @ ROWCOUNT is a system function and returns the number of rows affected by the previous statement.
IF @ ROWCOUNT> 0
BEGIN
        -- Obtain the number and quantity of items currently inserted,InsertedA table is used to store copies of rows affected by INSERT and UPDATE statements.
SELECT @ intID = mId, @ intNum = rNum, @ intMode = rMode FROMInserted

        -- Judge the current mode (0 indicates warehouse receiving, 1 indicates warehouse picking) to update the current item quantity
IF @ intMode = 0
UPDATE uMateriel SET mNum = mNum + @ intNum WHERE mId = @ intID
ELSE
UPDATE uMateriel SET mNum = mNum-@ intNum WHERE mId = @ intID
END

Let's take a look at this TRIGGER. First, use the create trigger statement to define a TRIGGER based on the uRecord table trUpdateMaterielNum. after insert, this TRIGGER will be executed AFTER the record is inserted, that is to say, when we execute the insert into uRecord (mId, rNum, rMode) VALUES (1,100, 0) statement in the program, the content in the trigger trUpdateMaterielNum will be automatically executed, that is to say, the inventory will be automatically updated. Now let's change the ASP code.

QUOTE:
On Error Resume Next

'// Set adoConn to the connected ADODB. Connection object
'// Insert the entry record
AdoConn. Execute ("insert into uRecord (mId, rNum, rMode) VALUES (1,100, 0 )")

'// Determine whether an error has occurred
If Err. Number <> 0 Then
Response. Write "error! "
Err. Clear
End If

Is it much simpler? Yes, there is no need to consider inventory here. You only need to insert a sequential account, and the inventory update will be handled by the trigger.

The preceding example is an application of a trigger. The trigger parameters include DELETE and UPDATE, which are executed at or after deletion and UPDATE respectively. The following is an example of a delete trigger.

We add a table to the database to record logs. Its structure is as follows:

QUOTE:
USysLog
--------------
LId int
LEvent nvarchar (200)
LTime datetime DEFAULT GetDate ()

Now we assume that this table is used to record system logs. When we delete a Journal account and record an event in the log table, we create a trigger for deleting a uRecord table.

QUOTE:
Create trigger [trDeleteRecord] ON [dbo]. [uRecord]
-- Indicates that the trigger is executed after the record is inserted.
FOR DELETE
AS
-- The currently deleted serial number
DECLARE @ intID int
-- Number of deleted items
DECLARE @ intNum int
-- Current mode
DECLARE @ intMode int

-- Determines whether a record is updated. @ ROWCOUNT is a system function and returns the number of rows affected by the previous statement.
IF @ ROWCOUNT> 0
BEGIN
        -- Get the information of the row currently deleted,DeletedA table is used to store copies of rows affected by the DELETE and UPDATE statements.
SELECT @ intID = rId, @ intNum = rNum, @ intMode = rMode FROMDeleted

        -- Insert a simple deletion event log to the log table.
Insert into uSysLog (lEvent) VALUES ('The user deleted the serial number: '+ CAST (@ intID as nvarchar (20) +', quantity: '+ CAST (@ intNum as nvarchar (20) +', direction: '+ CASE @ intMode WHEN 0 then' warehouse receiving 'else' warehouse picking 'end)
END

After the trigger is created, an event log is added to the system log as long as we delete a record in the uRecord table.

Through the above brief introduction, I hope that friends who have never used a trigger will have a general idea and an impression on the trigger. If you want to know more about it, SQL SERVER books online is a good helper for you. The simple application of the trigger will be introduced here, and we will continue later.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.