关于触发器的问题,高分求助!!!!
我想用触发器来按照不同的ClassID值来自动递增字段ID的值,我按照以下的方法在插入一条记录时正常,但如果进行多行同时插入时,就是用insert table select * from table2这样的形式插入时,新插入的ID字段值都相同,并未像我预想中的那样自动递增。
CREATE TRIGGER [MaintenanceID_Insert] ON [dbo].[OptionItem]
INSTEAD OF INSERT
AS
insert into OptionItem (ClassID, ID, RootID, PID, Layer, [Order], Child, Name, Comment)
select ClassID, ID = (select isnull(Max(ID), 0) + 1 from OptionItem where ClassID = inserted.ClassID), RootID, PID, Layer, [Order], Child, Name, Comment from inserted
后来我改成用游标的方式,逐条的进行插入,但后来才发现在inserted表中的记录其OptionID字段全部为0,因此我无法定位到inserted中的某条记录,因此假如同时插入25条记录,真实的就会出现25*25=625条记录。
Declare @OptionID int, @ClassID int
Declare InsertCollection cursor for select OptionID, ClassID from inserted
open InsertCollection
fetch next from InsertCollection into @OptionID, @ClassID
while @@FETCH_STATUS <> -1
begin
--update OptionItem set ID = (select isnull(Max(ID), 0) + 1 from OptionItem where ClassID = @ClassID) where OptionID = @OptionID
--insert into OptionItem (ClassID, ID, RootID, PID, Layer, [Order], Child, Name, Comment)
-- select ClassID, ID = (select isnull(Max(ID), 0) + 1 from OptionItem where ClassID = @ClassID), RootID, PID, Layer, [Order], Child, Name, Comment from inserted where OptionID = @OptionID
select * from inserted where OptionID = @OptionID
fetch next from InsertCollection into @OptionID, @ClassID
end
CLOSE InsertCollection
DEALLOCATE InsertCollection
请问这样的问题我应该如何解决呢??