日期:2014-05-18  浏览次数:20492 次

在線等待:請教觸發器的問題2
表結構和觸發器代碼如下:
CREATE   TABLE   [dbo].[service_empl]   (
[empl_index]   [char]   (10)   COLLATE   Chinese_Taiwan_Stroke_CI_AS   NOT   NULL   ,
[empl_ensuremony]   [money]   NULL  
)   ON   [PRIMARY]
GO

ALTER   TABLE   [dbo].[service_empl]   WITH   NOCHECK   ADD  
CONSTRAINT   [service_empl]   PRIMARY   KEY     CLUSTERED  
(
[empl_index]
)     ON   [PRIMARY]  
GO

CREATE   TABLE   [dbo].[admini_ensuremoney]   (
[empl_index]   [char]   (10)   COLLATE   Chinese_Taiwan_Stroke_CI_AS   NOT   NULL   ,
[empl_oldmon]   [money]   NULL   ,
[empl_newmon]   [money]   NULL   ,
[empl_date]   [smalldatetime]   NOT   NULL  
)   ON   [PRIMARY]
GO

ALTER   TABLE   [dbo].[admini_ensuremoney]   WITH   NOCHECK   ADD  
CONSTRAINT   [PK_admin_ensuremoney]   PRIMARY   KEY     CLUSTERED  
(
[empl_index],
[empl_date]
)     ON   [PRIMARY]  
GO

ALTER   TABLE   [dbo].[admini_ensuremoney]   WITH   NOCHECK   ADD  
CONSTRAINT   [DF_admini_ensuremoney_empl_oldmon]   DEFAULT   (0)   FOR   [empl_oldmon],
CONSTRAINT   [DF_admini_ensuremoney_empl_newmon]   DEFAULT   (0)   FOR   [empl_newmon]
GO

CREATE   TRIGGER   [ensuremoney_insert]   ON   dbo.admini_ensuremoney  
FOR   INSERT,   UPDATE,   DELETE
AS
update   service_empl   set   service_ensuremoney=l.empl_oldmon     from   service_empl     y   ,   deleted   l   where   y.service_empl_index=l.empl_index
update   service_empl   set   service_ensuremoney=l.empl_newmon     from   service_empl   y   ,inserted   l   where   y.service_empl_index=l.empl_index

問題:這種方式會有一種錯誤:
當我增加,修改還是刪除admini_ensuremoney表中a君的一筆記錄時,如果這筆記錄的日期不是最新的日期,則此時也會去更新service_empl表中的值.

要求:我需要不管是增加,修改還是刪除操作,只有此筆記錄的日期是最新的日期(當前操作記錄的日期> =admini_ensuremoney中此人的最大日期)時,才去更新service_empl表中的數據.且能 "同時插入多筆相同service_empl_index的資料 "和 "同時插入多筆不同service_empl_index的資料 ".
說明:名種觸發情況的代碼可分開

http://community.csdn.net/Expert/topic/5372/5372712.xml?temp=.1426966
這個貼還有50分

------解决方案--------------------
--建立測試環境
CREATE TABLE [dbo].[service_empl] (
[service_empl_index] [char] (10) COLLATE Chinese_Taiwan_Stroke_CI_AS NOT NULL ,
[service_ensuremoney] [money] NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[service_empl] WITH NOCHECK ADD
CONSTRAINT [PK_service_empl] PRIMARY KEY CLUSTERED
(
[service_empl_index]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[admini_ensuremoney] (
[empl_index] [char] (10) COLLATE Chinese_Taiwan_Stroke_CI_AS NOT NULL ,
[empl_oldmon] [money] NULL ,
[empl_newmon] [money] NULL ,
[empl_date] [smalldatetime] NOT NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[admini_ensuremoney] WITH NOCHECK ADD
CONSTRAINT [PK_admin_ensuremoney] PRIMARY KEY CLUSTERED
(
[empl_index],
[empl_date]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[admini_ensuremoney] WITH NOCHECK ADD
CONSTRAINT [DF_admini_ensuremoney_empl_oldmon] DEFAULT (0) FOR [empl_oldmon],
CONSTRAI