我有三张桌子:
员工
Id
FirstName
LastName
EmployeeTasksId
EmployeeTasks
Id
EmployeeId
EmployeeTaskDefinitionId
EmployeeTaskDefinitions
Id
Description
etc.
我想要做的是在Employee
表中插入Employees
之后,我需要根据插入的EmployeeTasks
在Employee'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
答案 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
是标识栏。