Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Trigger resulting in NULL value
Message
 
 
À
11/07/2013 14:20:26
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Stored procedures, Triggers, UDFs
Versions des environnements
SQL Server:
SQL Server 6.5 and older
Application:
Web
Divers
Thread ID:
01578216
Message ID:
01578217
Vues:
42
>Hi,
>
>I am trying to create a trigger to update quantity on hand field of my stock items table whenever a transfer is done.
>
>This is my code:
>
>
USE [BPOptical]
>GO
>
>/****** Object:  Trigger [dbo].[Transfers_Insert_AdjustItemQty]    Script Date: 11/07/2013 02:17:31 PM ******/
>SET ANSI_NULLS ON
>GO
>
>SET QUOTED_IDENTIFIER ON
>GO
>
>
>-- =============================================
>-- Author:		<Author,,Name>
>-- Create date: <Create Date,,>
>-- Description:	<Description,,>
>-- =============================================
>CREATE TRIGGER [dbo].[Transfers_Insert_AdjustItemQty]
>   ON [dbo].[transfers]
>   AFTER INSERT
>AS 
>BEGIN
>	-- SET NOCOUNT ON added to prevent extra result sets from
>	-- interfering with SELECT statements.
>	SET NOCOUNT ON;
>
>	DECLARE @Quantity int
>	SET @Quantity = (SELECT trn_qty FROM inserted)
>
>	DECLARE @ItemId char(16)
>	SET @ItemId = (SELECT trn_itmfk FROM inserted)
>
>    -- Insert statements for trigger here
>	UPDATE dbo.Items
>			SET Items.iqtyonhand = Items.iqtyonhand - @Quantity
>		WHERE iitemid = @ItemId
>			AND iItemTypId = '43' -- 43 is for Inventory items
>
>
>END
>
>
>GO
>
>Is there something wrong with my logic here resulting in a null value?

There is one common mistake in this trigger as it's written to work only with a single insert.

I'll attempt to fix your code:
CREATE TRIGGER [dbo].[Transfers_Insert_AdjustItemQty]
   ON [dbo].[transfers]
   AFTER INSERT
AS 
BEGIN
	SET NOCOUNT ON;

                   MERGE dbo.Items as Target
                  USING (select trn_itmfk as ItemId, SUM(trn_Qty) as TotalQty 
FROM Inserted GROUP BY trn_itmfk) AS Source ON Target.ItemId = Source.ItemId

                 WHEN Matched  AND Target.ItemTypId  = '43' THEN UPDATE
                 SET iQtyOnHand = iQtyOnHand - COALESCE(Source.TotalQty,0);


END


GO
This is assuming you're using SQL Server 2008 and up.
If it's not broken, fix it until it is.


My Blog
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform