當我在表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