当我在表Pedidos
上插入一条记录时,我有以下触发器正常工作。插入多个记录时触发器不起作用
但是,当我插入多个记录时,我收到一条512
错误消息。我已经搜索过有关插入多个记录和触发器的详细信息,但没有找到我的问题的答案。
触发器读取插入的记录并从其他表中找到值以修改表planificaciones
中的列situacion
的值。
我完全错误的方式,我试图做到这一点?我的触发器中是否有任何明显的问题?
CREATE TRIGGER TRG_INS_PL_SYNC_STATUS_PLA ON dbo.pedidos after insert as begin if @@ROWCOUNT = 0
return
set nocount on
declare @v_idpla int,
@v_situacion nvarchar(12),
@v_nombre nvarchar(50),
@v_almacen nvarchar(50),
@v_status_pedido nvarchar(4);
set @v_almacen = (select almacen_pedido from inserted);
set @v_nombre =(select cliente from inserted);
set @v_status_pedido = (select status_pedido from inserted);
set @v_situacion = (select top 1 nombre from dbo.StatusPlanificacion
where STATUS_PEDIDO = @v_status_pedido);
set @v_idpla = (select top 1 id from dbo.Planificaciones
where dia_entrega >= GETDATE() and situacion <> 'Departed'
and nombre like '%'[email protected]_almacen +'%'+ @v_nombre);
if(@v_idpla is not null)
begin
--select Timespan=SYSDATETIME() from inserted;
select @@rowcount;
UPDATE DBO.Planificaciones
SET situacion = @v_situacion
WHERE id = @v_idpla;
end
end
UPDATE &解决:寻找在坦纳建议我做的下一个更新的代码和作品,但我觉得有些人能发现这更加清晰和有效。在制革商建议,光标不是最好的方式来做到这一点,最好的选择是加入。在我的情况下,这个插入永远不会超过50个插入在同一时间。
CREATE TRIGGER TRG_INS_PL_SYNC_STATUS_PLA
ON dbo.pedidos
after insert as
begin
declare @v_idpla int,@v_situacion nvarchar(12),@v_nombre nvarchar(50),@v_almacen nvarchar(50), @v_status_pedido nvarchar(4)
DECLARE c_cursor CURSOR FAST_FORWARD FOR SELECT ALMACEN_PEDIDO, CLIENTE, STATUS_PEDIDO FROM INSERTED;
OPEN c_cursor
fetch next from c_cursor into @v_almacen,@v_nombre,@v_status_pedido
--declared and open cursor chargin values to variables
while @@fetch_status = 0
begin
-- set values to variables from anothers tables
set @v_situacion = (select top 1 nombre from dbo.StatusPlanificacion where STATUS_PEDIDO = @v_status_pedido);
set @v_idpla = (select top 1 id from dbo.Planificaciones where dia_entrega >= GETDATE() and
situacion <> 'Departed' and nombre like '%'[email protected]_almacen +'%'+ @v_nombre);
--check value not null for assigned variable and do update to the value
if(@v_idpla is not null)
begin
UPDATE DBO.Planificaciones
SET situacion = @v_situacion
WHERE id = @v_idpla;
end
--move to the next row of cursor
fetch next from c_cursor into @v_almacen,@v_nombre,@v_status_pedido
end
CLOSE c_cursor
DEALLOCATE c_cursor
end
您的代码需要重新考虑,因为它错误地假定'inserted'只包含一条记录。在一批中插入多个记录时不会出现这种情况。 – Jaco
可能重复的[SQL Server触发器在多行插入上工作](http://stackoverflow.com/questions/2178889/sql-server-a-trigger-to-work-on-multiple-row-inserts) – Tanner
感谢Jaco的回复,你能否建议我在一个批处理中插入多个recods的示例,并使用触发器查询另一个表来查找并将值应用于update语句? – user1353547