简体   繁体   English

触发以使用自动增量值更新另一个表

[英]Trigger to update another table WITH auto-increment value

I'm having trouble creating a trigger for my database. 我在为数据库创建触发器时遇到问题。

I Have two tables, lets call them A and AHistory. 我有两个表,我们称它们为A和AHistory。

A has an ID and a value. A具有ID和值。

I want AHistory to keep track of the value and date for a set time. 我希望AHistory在设定的时间内跟踪值和日期。

AHistory Has an Auto Incremented ID, the value and a timestamp. AHistory具有自动递增的ID,值和时间戳。

this is as far as I have gotten: 据我所知:

CREATE TRIGGER Atrigger 
   ON  A
   AFTER INSERT
AS 
BEGIN    
    INSERT INTO AHistory
    SELECT value FROM INSERTED
END
GO

Assuming that your db schema looks like 假设您的数据库架构看起来像

CREATE TABLE a
   (id int identity primary key, 
     value varchar(32));

CREATE TABLE ahistory
   (id int identity primary key, 
     aid int, value varchar(32), 
     eventdate datetime);

Your trigger might look like 您的触发器可能看起来像

CREATE TRIGGER atrigger ON  A
AFTER INSERT AS 
    INSERT INTO ahistory (aid, value, eventdate)
    SELECT id, value, GETDATE() FROM INSERTED;

Here is SQLFddle demo 这是SQLFddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM