使用触发器在另一个表中插入记录

时间:2014-01-21 18:19:37

标签: sql sql-server-2008 triggers

您好我正在使用SQLServer2008。

以下是我的Product表格。

ProductId
CategoryId
Name
Qty

其中ProductId是主键并自动生成。以下是我的Stock

StockId
ProductId
Stock

此处StockId是主键并自动生成。 现在,当在Product表中插入任何新的reord时,我想使用触发器在ProductId表中插入生成的Stock。我怎样才能做到这一点。任何帮助,将不胜感激。感谢

1 个答案:

答案 0 :(得分:1)

尝试以下方法。假设您希望新产品stock默认为0。否则相应修改。

CREATE TRIGGER trig_Insert_Stock
ON [Product]
FOR INSERT
AS
Begin
    Insert into Stock (ProductId, Stock) 
    Select Distinct i.ProductId, 0 
    from Inserted i
End