插入时的sql触发器

时间:2011-11-04 20:33:34

标签: sql-server triggers

快速问题,我正在构建一个简单的触发器,其目的是减少名为openSeats的表字段的值,触发器在插入时执行,但我不知道用什么命令来说: 减小值openSeats,其中Id等于插入的Id

USE [Training]
GO
/****** Object:  Trigger [dbo].[DecrementSeat]    Script Date: 11/04/2011 14:55:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================

ALTER TRIGGER [dbo].[DecrementSeat]
   ON  [dbo].[personTraining]
   AFTER INSERT

AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    UPDATE [dbo].[tbl_training]
    SET openSeats = openSeats - 1 
    WHERE training_id = 

END

2 个答案:

答案 0 :(得分:2)

您的触发器应该能够处理“多行”插入。我希望你想为插入的每一行从openSeats中减去1。

这样的事情:

UPDATE [dbo].[tbl_training]
   SET openSeats = openSeats - 
       ( SELECT COUNT(1) FROM inserted
          WHERE inserted.training_id = [dbo].[tbl_training].training_id )
 WHERE training_id IN
       ( SELECT inserted.training_id FROM inserted
          WHERE inserted.training_id IS NOT NULL )

答案 1 :(得分:0)

在触发器中尝试此操作:

update dbo.tbl_training
set openSeats = openSeats - 1
where training_id in
(
    select training_id
    from inserted
)

它利用SQL Server在触发期间填充插入数据的inserted动态表。