8

我在 SQL Server 2008 R2 中创建了一个包含以下列的表:ObservationId、FirstCreatedDate、description、... 和 LastUpdatedDate。ObservationId是一个以 1 为增量的标识。

我需要创建两个触发器,一个用于 INSERT,另一个用于 UPDATE。在插入新记录时,INSERT 触发器将通过获取当前日期时间来更新 FirstCreatedDate 列;在更新现有记录时,UPDATE 触发器将通过获取当前日期时间来更新 LastUpdatedDate 列。

我没有这样做,因为我猜测身份可能是问题所在。

谁能帮我一把?谢谢!

干杯,亚历克斯

ALTER TRIGGER [dbo].[T_InsertNewObservation] ON [dbo].[GCUR_OBSERVATION] 
  AFTER INSERT
AS 
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  -- Insert statements for trigger here
  UPDATE GCUR_OBSERVATION SET GCUR_OBSERVATION.FirstCreatedDate = getdate()
  FROM GCUR_OBSERVATION a INNER JOIN INSERTED ins ON a.ObservationId = ins.ObservationId

END
4

3 回答 3

12

我认为您大多是正确的,但没有正确访问 INSERTED 或 DELETED 表。

ALTER TRIGGER [dbo].[T_InsertNewObservation] ON [dbo].[GCUR_OBSERVATION] 
  AFTER INSERT
AS 
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  -- get the last id value of the record inserted or updated
  DECLARE @id INT
  SELECT @id = [ObservationId]
  FROM INSERTED

  -- Insert statements for trigger here
  UPDATE GCUR_OBSERVATION 
  SET GCUR_OBSERVATION.FirstCreatedDate = GETDATE()
  WHERE [ObservationId] = @id 

END

PS。希望这能像我在记事本中写的那样有效,并且还没有测试过。

于 2012-06-21T04:42:27.950 回答
1

下面的代码用于 AFTER UPDATE 以修改最后更改的日期列。

如果您发现任何问题,请提出建议。谢谢!

ALTER TRIGGER [dbo].[T_UpdateObservation] ON [dbo].[GCUR_OBSERVATION] 
AFTER UPDATE
AS 
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- get the last id value of the record inserted or updated
DECLARE @id INT
SELECT @id = [ObservationId]
FROM DELETED

-- Insert statements for trigger here
UPDATE GCUR_OBSERVATION
SET GCUR_OBSERVATION.LastUpdatedDate = getdate()
WHERE [ObservationId] = @id

END
于 2012-06-21T05:15:36.663 回答
-2
Create TRIGGER [dbo].[TrigerName] ON [dbo].[TableCreateTriger] FOR INSERT AS
INSERT INTO TableInsertDate SELECT * FROM TableCreateTriger
于 2017-07-18T08:51:39.087 回答