I apologize in advance for the dirt in the code, but I don’t know how to do it in another way.

USE [ERP] GO /****** Object: Trigger [dbo].[Потребность] Script Date: 11.05.2016 19:59:12 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER Trigger [dbo].[Потребность] ON [dbo].[Ведомость_материалов] FOR insert AS Declare @a int; Declare @b int; Declare @с int; Declare @v int; Declare @q int; select @с=Материал,@v=Колличество_на_складе from Ведомость_материалов select @a=sum(количество) from Заявка where Статус='В пути' AND Заявка.Наименование_детали=@с group by Наименование_детали select @b=количество from План where План.ID=@с select @q=Наименование_детали from Журнал_прихода update Ведомость_материалов set Чистая_потребность=@b-isnull(@a,0)-@v where Ведомость_материалов.Материал=@q 

his task is to calculate net profit by a simple formula


Net need = Quantity according to plan-quantity (only those that are still on the way) -quantity in stock


The problem is, when the Net need must be zero, then it takes on the value of the net need of another part.

  • 2
    Why do you in all your queries constantly select all the records from the tables, rather than the ones that were actually inserted during this trigger call. Why not use the inserted table, which just contains all the data you need. You should not have ANY query select without the condition where not from inserted - Mike
  • @Mike, inserted does not contain the number of the plan and the amount of the application - Sergey74rus
  • select @с=Материал,@v=Колличество_на_складе from Ведомость_материалов - do you have only one record in the select @с=Материал,@v=Колличество_на_складе from Ведомость_материалов table? If not, do you really need data from a random entry from this table here? The same question and about the table Журнал_прихода . - Yaant
  • @ Yaant, no, there are a lot of records - Sergey74rus
  • @Sergei And your request assigns to the variables @c and @v values ​​of one of them, and which one is unknown in advance. - Yaant

0