如何使用触发器基于另一个表的行将行插入表中?

时间:2016-05-28 13:45:32

标签: sql-server tsql triggers bulkinsert

我有三张桌子:

员工

Id
FirstName
LastName
EmployeeTasksId

EmployeeTasks

Id
EmployeeId
EmployeeTaskDefinitionId

EmployeeTaskDefinitions

Id
Description
etc.

我想要做的是在Employee表中插入Employees之后,我需要根据插入的EmployeeTasksEmployee's表中插入行我和每个EmployeeTaskDefinition's Id.

例如:

    带有Employee 1的
  • Id已插入到Employee表
  • EmployeeTaskDefinitions表有6行,Ids 1-6
  • EmployeeTasks表在插入后需要有6行:

    Id = 1, EmployeeId = 1, EmployeeTaskDefinitonId = 1    
    Id = 2, EmployeeId = 1, EmployeeTaskDefinitonId = 2     
    Id = 3, EmployeeId = 1, EmployeeTaskDefinitonId = 3      
    Id = 4, EmployeeId = 1, EmployeeTaskDefinitonId = 4      
    Id = 5, EmployeeId = 1, EmployeeTaskDefinitonId = 5      
    Id = 6, EmployeeId = 1, EmployeeTaskDefinitonId = 6    
    

现在我已经阅读了很多关于游标的帖子,大多数人都说这对于这个任务来说是一个不好的做法。但你会怎么做这样的事情?注意:除了触发器之外,我不想使用其他任何东西。

编辑:这是我提出的查询。

CREATE TRIGGER CreateEmployee 
    ON [dbo].[EmployeeSet]
    AFTER INSERT
AS
    DECLARE @LoopCounter int, @MaxSettingDefinitionId int, @Id int
    SELECT @LoopCounter = MIN(Id), @MaxSettingDefinitionId = MAX(Id)
    FROM SettingsDefinitionSet

    WHILE(@LoopCounter IS NOT NULL AND @LoopCounter <= @MaxSettingDefinitionId)
    BEGIN
        SELECT @Id = Id FROM SettingDefinitionSet
        WHERE Id = @LoopCounter
        INSERT INTO SettingSet(CompanyId, EmployeeId, SettingDefinitionId, SettingType, State, Value)
        VALUES((SELECT CompanyId FROM inserted), (SELECT Id FROM inserted), 
                @Id, 
                (SELECT SettingType FROM SettingSet WHERE EmployeeId IS NULL AND CompanyId = (SELECT CompanyId FROM inserted) AND SettingDefinitionId = @Id), 
                (SELECT State FROM SettingSet WHERE EmployeeId IS NULL AND CompanyId = (SELECT CompanyId FROM inserted) AND SettingDefinitionId = @Id), 
                (SELECT Value FROM SettingSet WHERE EmployeeId IS NULL AND CompanyId = (SELECT CompanyId FROM inserted) AND SettingDefinitionId = @Id))
        SELECT @LoopCounter = MIN(Id) FROM SettingDefinitionSet
        WHERE Id > @LoopCounter
    END
GO

2 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

INSERT INTO EmployeeTasks(EmployeeId, EmployeeTaskDefinitionId)
SELECT inserted.id as EmployeeId, t.id as EmployeeTaskDefinitionId
    FROM inserted JOIN EmployeeTaskDefinitions

答案 1 :(得分:1)

正如我在评论中所指出的那样,Employee表格标准化不正确,不应该有EmployeeTasksId。如果您想自动将一些任务添加到新员工,请执行以下操作:

alter table EmployeeTaskDefinitions
add DefaultTask bit not null default 0
--update EmployeeTaskDefinitions set DefaultTask = 1 where...
--now create a trigger
create trigger trEmployee_i
on dbo.Employee after insert
as
begin
set nocount on
insert EmployeeTasks(EmployeeId,EmployeeTaskDefinitionId)
select i.id,td.id
from inserted i cross join EmployeeTaskDefinitions td
where td.DefaultTask = 1
end

P.S。:我希望EmployeeTasks.Id是标识栏。