在表中插入多行,并在另一个表中插入触发器

时间:2014-04-09 04:23:56

标签: sql sql-server tsql triggers sql-insert

我正在尝试创建一个T-SQL触发器,它基本上会根据插入到原始表中的数据和第二个表中包含的数据将 x 行数插入第三个表中;但是,我在insert语句的选择部分中遇到了各种错误。

如果我注释掉这部分[qmgmt].[dbo].[skillColumns].[columnID] in (select columnID from [qmgmt].[dbo].[skillColumns]),IntelliSense将删除所有红线。

表设计:

  • Users表 - 包含用户信息
  • skillColumns表 - 可能的所有列的列表,在用户的productGroupID上过滤
  • Skills表 - 包含每位用户的数据,columnID
  • 中每skillColumns行一行
CREATE TRIGGER tr_Users_INSERT 
   ON [qmgmt].[dbo].[Users]
   AFTER INSERT
AS 
BEGIN
    INSERT into [qmgmt].[dbo].[Skills]([userID], [displayName], [columnID]) 
    Select [iTable].[userID], 
           [iTable].[displayName], 
           [cID] in (select [columnID] as [cID] from [qmgmt].[dbo].[skillColumns])
    From inserted as [iTable] inner join 
        [qmgmt].[dbo].[skillColumns] on 
        [iTable].[productGroupID] = [qmgmt].[dbo].[skillColumns].[groupID]
END
GO

我是否希望通过扳机实现目标?可以使用in关键字将多行插入到表格中吗?


更新:

使用J0e3gan提供的答案后,我能够以相反的方向创建一个触发器:

CREATE TRIGGER tr_skillColumns_INSERT_Users
    ON [qmgmt].[dbo].[skillColumns]
    AFTER INSERT
AS
BEGIN
    INTO [qmgmt].[dbo].[Skills]([userID], [displayName], [columnID])
    Select [qmgmt].[dbo].[Users].[userID],
           [qmgmt].[dbo].[Users].[displayName],
           [iTable].[columnID]
    From inserted as [iTable] inner Join 
        [qmgmt].[dbo].[Users] on
        [iTable].[groupID] = [qmgmt].[dbo].[Users].[productGroupID]
    Where
        [qmgmt].[dbo].[Users].[userID] in (select [userID] from [qmgmt].[dbo].[Users])
END
GO

1 个答案:

答案 0 :(得分:3)

是的,可以使用AFTER触发器完成此操作。

列列表不是您尝试使用的IN条件的正确位置,这就是为红色加下划线的原因。

请尝试将IN条件添加到JOIN条件:

CREATE TRIGGER tr_Users_INSERT 
   ON [qmgmt].[dbo].[Users]
   AFTER INSERT
AS 
BEGIN
    INSERT into [qmgmt].[dbo].[Skills]([userID], [displayName], [columnID]) 
    Select [iTable].[userID], 
           [iTable].[displayName], 
           [qmgmt].[dbo].[skillColumns].[columnID]
    From inserted as [iTable] inner join 
        [qmgmt].[dbo].[skillColumns] on 
        [iTable].[productGroupID] = [qmgmt].[dbo].[skillColumns].[groupID] and
        [qmgmt].[dbo].[skillColumns].[columnID] in (select columnID from [qmgmt].[dbo].[skillColumns])
END
GO

或者将其添加到WHERE子句:

CREATE TRIGGER tr_Users_INSERT 
   ON [qmgmt].[dbo].[Users]
   AFTER INSERT
AS 
BEGIN
    INSERT into [qmgmt].[dbo].[Skills]([userID], [displayName], [columnID]) 
    Select [iTable].[userID], 
           [iTable].[displayName], 
           [qmgmt].[dbo].[skillColumns].[columnID]
    From inserted as [iTable] inner join 
        [qmgmt].[dbo].[skillColumns] on 
        [iTable].[productGroupID] = [qmgmt].[dbo].[skillColumns].[groupID]
    Where
        [qmgmt].[dbo].[skillColumns].[columnID] in (select columnID from [qmgmt].[dbo].[skillColumns])
END
GO