I would like to record clicks for each item, and then follow the traffic to brand name merchandise, want to improve efficiency, so have to use a trigger, the following is learning materials I found in the library of Baidu, share with everyone.
Definition: What is the trigger? In SQL Server which is one of certain operating table, it triggers certain conditions, in order to execute a program. A trigger is a special stored procedure.
There are three common triggers: are used in Insert, Update, Delete event.
Why should I use a trigger? For example, such a two tables:
the Create the Table Student (- student table
StudentID int primary key, - student number
....
)
the Create the Table BorrowRecord (- student borrowing record sheet
BorrowRecord int identity (1,1), - - serial number
StudentID int, - student number
BorrowDate datetime, - borrowed time
returnDAte datetime, - return time
...
)
used functions are:
1. If I change the number of students to learn, I hope his library records are still relevant to the student (that is, at the same time change the number of records in the table of library science);
2. If the student has graduated, I want to delete his student number, but also remove its library records.
and many more.
This time can be used in trigger. For 1, create a trigger Update:
The Trigger truStudent the Create the On Student - create a trigger in the Student table for Update - Why are event-triggered As - after the trigger event to do IF Update (StudentID) the begin Update BorrowRecord the Set StudentID = i.StudentID the From BorrowRecord br, Deleted d, Inserted i --Deleted Inserted temporary tables and the Where br.StudentID d.StudentID = End
Understand the trigger inside the two temporary tables: Deleted, Inserted. Note Deleted and Inserted table showing the triggering event of the "old record" and "new record" respectively.
A system information database table records changes in the virtual table for storing two, namely:
a virtual table Deleted Inserted virtual table
stored in the new table does not store recording new record records
stored to update the modified before recording a new record store updates
are not stored when you delete records store deleted records
an update process can be seen as: to generate a new record Inserted table, copying the old records to deleted table, and then delete the Student records and write a new record .
For 2, create a Delete trigger
Create trigger trdStudent On Student for Delete As Delete BorrowRecord From BorrowRecord br , Delted d Where br.StudentID=d.StudentID
From these two examples we can see that the key triggers: A.2 temporary table; B trigger mechanism.
SQL trigger Example 2
/ *
Create a virtual test environment, including: Table [cigarette inventory table], table [cigarette sales table].
Please note that tracking data in both tables, the experience of flip-flops in the end what the implementation of business logic, have any effect on the data.
In order to express more clearly the role of a trigger, data redundancy table structure is present, and does not meet the third paradigm, it is noted here.
* /
The USE Master the GO the IF EXISTS (the SELECT NAME the FROM the SYSOBJECTS the WHERE xtype = 'the U-' the AND NAME = 'cigarette inventory table') the DROP TABLE cigarette inventory table the GO the IF EXISTS (the SELECT NAME the FROM the SYSOBJECTS the WHERE xtype = 'the U-' the AND NAME = 'cigarette sales table ') the DROP tABLE cigarette sales table GO
- Business Rules: the amount of sales = sales * sales price business rules.
CREATE TABLE cigarette sales table ( cigarette brands VARCHAR (40) PRIMARY KEY NOT NULL , buyer to VARCHAR (40) NULL, sales INT NULL, sales price MONEY NULL, the amount of sales NULL MONEY ) GO - business rule: the amount of inventory = * number of stocks priced inventory business rules. CREATE TABLE cigarette inventory table ( cigarette brand VARCHAR (40) PRIMARY KEY NOT NULL , the number of stocks INT NULL, inventory priced MONEY NULL, inventory value NULL MONEY ) GO
- create a trigger, Example 1
/ *
create a trigger [T_INSERT_ cigarette inventory table], this flip-flop is relatively simple.
Description: Every [cigarette inventory table] INSERT operation occurs, the trigger of the trigger.
Trigger functions: enforce business rules to ensure that the insertion of data, inventory amount = the number of stock inventory * Price.
Note: [INSERTED], [DELETED] for the system tables can not be created, modified, deleted, but you can call.
Important: The structure of these two systems insert tables with structured data tables.
* /
IF EXISTS (SELECT NAME FROM SYSOBJECTS WHERE XTYPE = 'TR' AND NAME = 'T_INSERT_ cigarette inventory table') the DROP TRIGGER T_INSERT_ cigarette inventory table the GO the CREATE TRIGGER T_INSERT_ cigarette inventory table ON cigarette inventory table the FOR the INSERT the AS - committing the transaction processing BEGIN TRANSACTION - enforce the following statement to ensure that business rules UPDATE cigarette inventory table SET amount = the number of inventory stock inventory Price * WHERE cigarette brand IN (SELECT the INSERTED cigarette brand from) COMMIT TRANSACTION GO
/ *
For [cigarette inventory table], insert test data:
Note that the data of the first pieces of data (GongDaShan new forces) in compliance with business rules,
the second data (GongDaShan man-peak), the [amount of inventory] empty, do not meet business rules,
Article III data (Yunnan image), the [amount of inventory] is not equal to [the number of stock] is multiplied by [stock unit price], does not meet the business rules.
Article data inventory quantity is zero.
Note that after inserting the data, to check whether the data [cigarette inventory table] in the amount of inventory = number of stock inventory * Price.
* /
INSERT INTO cigarette inventory table (cigarette brand, number of stocks, stock price, inventory amount) the SELECT 'GongDaShan new forces', 100,12,1200 UNION ALL the SELECT' GongDaShan man-peak ', 100, 22, NULL UNION ALL the SELECT' Yunnan image ', 100,60,500 UNION ALL the SELECT' Yuxi ', 0,30,0 GO - query data SELECT * FROM cigarette inventory table GO / *
The results set
RecordId cigarette brand inventory stock Quantity Unit Price Stock Amount
-------- ------------ -------- ------- ---- -----
. 1 GongDaShan new forces 1200.0000 12.0000 100
2 100 22.0000 2200.0000 GongDaShan artificial peaks
3 Yunnan image 6000.0000 60.0000 100
4 .0000 30.0000 Yuxi 0
(the number of rows affected by 4 rows)
* /
- trigger example 2
/ *
create trigger [T_INSERT_ cigarette sales table], the trigger is more complex.
Description: Every [cigarette inventory table] INSERT operation occurs, the trigger of the trigger.
Trigger functions: business rules.
Business Rules: If the inventory or selling cigarette brand inventory to zero does not exist, an error is returned.
Otherwise automatically reduce the amount of inventory and inventory amount [cigarette inventory table] corresponding brand cigarettes.
* /
IF EXISTS (SELECT NAME FROM SYSOBJECTS WHERE XTYPE = 'TR' AND NAME = 'T_INSERT_ cigarette sales table') the DROP TRIGGER T_INSERT_ cigarette sales table the GO the CREATE TRIGGER T_INSERT_ cigarette sales table ON cigarette sales table the FOR the INSERT the AS the BEGIN TRANSACTION - check the legitimacy of data: whether the cigarettes sold in stock, or stocks is greater than zero iF the NOT EXISTS ( the SELECT stock quantity FROM cigarette inventory table WHERE cigarette brand iN (SELECT cigarette brand the INSERTED FROM) ) BEGIN - returns the error RAISERROR ( ' ! the error cigarette inventory does not exist, can not be sold ', 16,1). - roll back the transaction rOLLBACK the RETURN END IF eXISTS ( the SELECT stock quantity FROM cigarette inventory table WHERE cigarette brand IN (SELECT cigarette brand FROM INSERTED) AND the number of stock < = 0 ) BEGIN - return error RAISERROR ( 'the error is less than or equal to 0 cigarette stock, can not be sold!', 16,1) - roll back the transaction ROLLBACK the RETURN END - for legitimate data processing - enforce the following statement, to ensure that business rules UPDATE cigarette sales table SET amount of sales = sales * sales price WHERE cigarette brand IN (SELECT cigarette brand in the FROM the INSERTED) DECLARE @ cigarette brand VARCHAR (40) SET @ cigarette brand = (SELECT cigarette brand in the FROM the INSERTED) DECLARE @ sales number mONEY number SET @ sales = (number of sales of the SELECT the FROM the INSERTED) UPDATE cigarette inventory table SET stock quantity = number of stock - sales @, inventory amount = (stock number - @ sales) * Stock Price WHERE cigarette brand = @ cigarette brand TRANSACTION COMMIT GO - please tracking [cigarette inventory table] and [cigarette sales table] data changes on their own. - For [cigarette sales table], the test data is inserted first, that the data is normal. INSERT INTO cigarette sales table (cigarette brand, business purchases, sales volume, sales price, the amount of sales) the SELECT 'GongDaShan new forces,' 'a buyer to' 10,12,1200 GO - for the [cigarette sales table] , the second test data insertion, the sales amount data * is not equal to the unit price sales. - trigger will automatically correct the data, the sales amount equal to the sales price * number of sales. INSERT INTO cigarette sales table (cigarette brand, business purchases, sales volume, sales price, the amount of sales) the SELECT 'GongDaShan artificial peak,' 'a buyer to' 10,22,2000 GO - for the [cigarette sales table] , insert the third test data that corresponds to the brand of cigarette in a cigarette inventory table could not be found. - trigger an error. INSERT INTO cigarette sales table (cigarette brand, business purchases, sales volume, sales price, the amount of sales) the SELECT 'Red River V8', 'a buyer to', 10,60,600 GO / * result set Server: Msg 50000, Level 16 , state 1, procedure T_INSERT_ cigarette sales tables, rows 15 errors! The cigarette inventory does not exist, it can not be sold. * / - for [cigarette sales table], insert the third test data, the data cigarette brand inventory to zero in cigarette inventory table. - trigger an error. INSERT INTO cigarette sales table (cigarette brand, business purchases, sales volume, sales price, the amount of sales) SELECT 'Yuxi', 'business purchases a', 10,30,300 the GO / * The results set Server: Msg 50000, Level 16, State 1, Procedure T_INSERT_ cigarette sales tables, rows 29 errors! The cigarette stock is less than or equal to 0, it can not be sold. * / - query data SELECT * FROM cigarette inventory table SELECT * FROM cigarette sales table GO / * add: 1, the main achievement of this example will be explained by using a simple trigger business rules specific to flexibility needed ; 2, on the flip-flop to understand and make good use of INSERTED, DELETED system tables; 3, this example creates triggers are fOR INSERT, refer to the specific syntax: //////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// ///////////////// the Trigger syntax /////////////////////////////// ////////////////////////////////////////////////// ///////////////////////////////////////////// the ON { table | view} TRIGGER trigger_name the CREATE [the ENCRYPTION the WITH] - is used to encrypt the trigger { {{the FOR | an AFTER | an INSTEAD. OF} {[the INSERT] [,] [the UPDATE]} [the WITH the APPEND] [the NOT the FOR Of REPLICATION] the AS [{the IF the UPDATE ( column) [{the AND | OR} the UPDATE (column)] [... n-] | the IF (the COLUMNS_UPDATED () {} bitwise_operator updated_bitmask) {} comparison_operator column_bitmask [... n-] }] sql_statement [... n-] } } 4, on the trigger, should also pay attention to (1), DELETE trigger can not capture TRUNCATE TABLE statement. (2), triggers are not allowed in the following Transact-SQL statements: the ALTER DATABASE the CREATE DATABASE DISK INIT DISK RESIZE the LOAD DATABASE DROP DATABASE RESTORE DATABASE LOG RECONFIGURE the LOAD RESTORE LOG (. 3), the trigger can be nested up to 32 levels. * / - Modify the trigger - essentially, is to modify the CREATE TRIGGER ... ALTER TRIGGER ... can be. - Delete trigger DROP TRIGGER xxx GO - delete a test environment DROP TABLE cigarette inventory table GO DROP TABLE cigarette sales table GO DROP TRIGGER T_INSERT_ cigarette inventory table GO DROP TRIGGER T_INSERT_ cigarette sales table GO ######## ################################################## ######## Fundamentals and examples of triggers : trigger Create tr_name ON Table / View {for | After |} INSTEAD of [Update] [,] [INSERT] [,] [Delete] [with Encryption] as {batch | if update (col_name ) [{and | or} update (col_name)]} Description: . 1 tr_name: trigger name Table Trigger acts of: 2 on table / view. A trigger can only act on a table 3 for and after: synonymous 4 after and instead of: sql 2000 with new projects instead of afrer difference After only activated after the triggering event occurs, can only be built on the table Instead of replaces the corresponding trigger event is performed, may be set up on the table can also be based on the view 5 insert, update, delete: three activation of the trigger operation may be performed simultaneously, optionally also one 6 if update (col_name): indicates that the operation made by the designated column is influential, influential, the trigger is activated. In addition, because the delete operation affects only the line, so if you use the delete operation can not be used this statement (although use is not wrong, but can not activate the trigger, no sense). Two special tables used when executing 7 triggers: deleted, inserted deleted and inserted can be said that a special temporary table, during activation of the trigger is generated automatically by the system, the table structure with the trigger action structure is a kind of data stored only difference. Continued The following table shows the differences inserted and deleted data difference data is inserted and deleted Inserted data storage insert and update operations performed after Deleted Storing data before update and delete operations Note: update operation is equivalent to first delete then carried insert, so that during an update operation, a copy of the data before the modification to the deleted table, the modified data is stored in a trigger action while the table, and also generates a table copied to insered ///////// the CREATE TRIGGER [TRIGGER admixture_receive_log] the ON dbo.chl_lydj the FOR the UPDATE the AS the begin DECLARE @djsfxg char (10) DECLARE @wtbh char (20 is ) SELECT @ = wtbh from wtbh inserted The Update ly_tzk SET djsfxg = 'modified' WHERE wtbh = @ wtbh End IF (SELECT data_sfjl from t_logsetup) = 'yes' the begin DECLARE @oldcjmc char (100) DECLARE @oldlyrq datetime DECLARE char @oldbzbh (60) DECLARE @oldzl char (20 is) DECLARE @olddj char (10) DECLARE @newcjmc char (100) DECLARE @newlyrq datetime declare @newbzbh char (60) declare @newzl char (20) declare @newdj char (10) declare @xgr char (20) select @oldcjmc=cjmc,@oldlyrq=lyrq,@oldbzbh=bzbh,@oldzl=zl,@olddj=dj from deleted select @newcjmc=cjmc,@newlyrq=lyrq,@newbzbh=bzbh,@newzl=zl,@newdj=dj from inserted select @xgr=xgr from t_modifyuser where @wtbh=wtbh if @oldcjmc<>@newcjmc begin insert into t_modifylog (wtbh, mod_time, mod_table, mod_field, ori_value, now_value, mod_people) values (@wtbh,getdate(), 'chl_lydj','cjmc', @oldcjmc, @newcjmc, @xgr) end end //////////修改时,直接把‘create’改为‘alter’即可 ///////////////////////// CREATE TRIGGER [TRIGGER ly_tzk_syf] ON dbo.ly_tzk FOR insert AS begin declare @clmc char(100) declare @dwbh char(100) declare @syf char(100) declare @dwgcbh char(100) declare @wtbh char(50) declare @dj_1 money declare @feiyong_z money declare @feiyong_xf money declare @feiyong_sy money declare @dj char(20) select @wtbh=wtbh , @clmc=clmc , @dwbh=dwbh ,@syf=syf from inserted select @dj=dj from feihao_bz where clmc=@clmc @ feiyong_z = feiyong_z SELECT, feiyong_xf = feiyong_xf @, @ = feiyong_sy feiyong_sy from gongchengxinxi WHERE dwgcbh = @ dwbh SET @ dj_1 = Convert (Money, @ DJ) IF @ dj_1 <> 0 begin set @feiyong_xf=@feiyong_xf+@dj_1 SET feiyong_sy = @ @ @ feiyong_sy- dj_1 Update ly_tzk @ DJ WHERE SYF = SET = @ wtbh wtbh Update gongchengxinxi SET feiyong_xf = @ feiyong_xf, feiyong_sy = @ = @ dwbh feiyong_sy WHERE dwgcbh End the else SET Update ly_tzk SYF = Convert (char, 0.0) @ = WHERE wtbh wtbh End //// ////////////////// the CREATE TRIGGER [TRIGGER ly_tzk_syf_shanchu] the ON dbo.ly_tzk the FOR Delete the AS the begin @clmc char DECLARE (100) DECLARE @dwbh char (100) DECLARE @dwgcbh char (100) DECLARE @wtbh char (50) Update gongchengxinxi SET feiyong_xf = @ feiyong_xf, feiyong_sy = @ feiyong_sy WHERE dwgcbh = @ dwbh declare @feiyong_z money declare @feiyong_xf money declare @feiyong_sy money declare @syf char(100) declare @syf_1 money char @dj --declare (20 is) DECLARE @ dj_1 Money SELECT = wtbh wtbh @, @ = clmc clmc, dwbh = dwbh @, @ = SYF from SYF inserted The --select @ DJ DJ from feihao_bz = @ = WHERE clmc clmc SELECT feiyong_z feiyong_z = @, @ = feiyong_xf feiyong_xf, @ = feiyong_sy feiyong_sy from gongchengxinxi WHERE dwgcbh = @ dwbh SET @ syf_1 = Convert (Money, @ SYF) IF @ syf_1 <> 0 the begin SET feiyong_xf = @ @ @ feiyong_xf- syf_1 SET @ = + @ @ feiyong_sy feiyong_sy syf_1 End End