How to write Triggers in sql server 2008?
In sqlserver 2008, i write trigger like this but i am little bit doubt that it is wrong c开发者_开发知识库an you check this once.
ALTER trigger [dbo].[UST_RollPlan_History_Trigger]
on [dbo].[Tbl_F_Roll_PlanDetails_T] for INSERT as
insert into Tbl_F_Roll_PlanDetails_H
(rollingplanid, productcode, rollplanmonthyear,
rollplanyear, candflocation, quantity, amendedqty,
createdby, createdon, sessionid, status)
select rollingplanid, productcode,rollplanmonthyear,
rollplanyear, candflocation,quantity,amendedqty,
createdby, createdon, sessionid, status
from Tbl_F_Roll_PlanDetails_T
You typically, in a trigger, want to reference the inserted
(and/or deleted
) pseudo-table, that contains the rows which were affected by the operation. I expect you want this:
ALTER trigger [dbo].[UST_RollPlan_History_Trigger]
on [dbo].[Tbl_F_Roll_PlanDetails_T] for INSERT as
insert into Tbl_F_Roll_PlanDetails_H
(rollingplanid, productcode, rollplanmonthyear,
rollplanyear, candflocation, quantity, amendedqty,
createdby, createdon, sessionid, status)
select rollingplanid, productcode,rollplanmonthyear,
rollplanyear, candflocation,quantity,amendedqty,
createdby, createdon, sessionid, status
from inserted
which will insert rows that have just been inserted into Tbl_F_Roll_PlanDetails_T
into the Tbl_F_Roll_PlanDetails_H
table. (Incidentally, prefixed names in SQL are generally pointless, since the types of objects that can appear in any particular context are either a] already limitied to a single type of object, or b] should not need to be distinguished anyway)
Please check trigger examples at the following tutorial, SQL Server Triggers Triggers are powerful but developers should be very carefull while using triggers. Because many developers think it will work once for each effected row but triggers work only once.
精彩评论