我在订单表上有一个触发器,可将订单详细信息插入order_details
表中。这在仅输入一行时有效,但在一次插入多行时无效。我已经阅读了多个线程 > 在各个站点上关于使用游标、while 语句、临时表等。我尝试了一些但没有成功。有关最佳/最简单方法的任何建议,以确保我在下订单时添加所有详细行。
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[CreateOrderDetails]
ON [dbo].[Orders]
FOR INSERT
AS
declare @OrderStagingId uniqueidentifier
declare @OrderType as varchar(50)
declare @OrderID uniqueidentifier
declare @LocationID uniqueidentifier
declare @status as varchar (25)
declare @vendorid as uniqueidentifier
SELECT @OrderID = OrderID, @LocationID = LocationID,
@vendorid = vendorid, @OrderStagingId = OrderStagingId
FROM inserted
Begin
SET NOCOUNT ON;
-- Insert statements for trigger here
Insert into [Brain].dbo.[Order_Details]
SELECT
NEWID() AS OrderDetailId, @OrderID AS OrderId,
dbo.OrderStaging_Details.EcProductID,
dbo.OrderStaging_Details.Qty, dbo.OrderStaging_Details.Qty_Type,
dbo.OrderStaging_Details.Cost, dbo.OrderStaging_Details.Ext_Cost,
dbo.OrderStaging_Details.EnteredBy,
NULL AS ReceivedBy, NULL AS ReceivedDate, NULL AS ReceivedQty,
dbo.OrderStaging_Details.OrderNote, NULL AS ReceivedNote,
dbo.OrderStaging_Details.UpdatedBy, dbo.OrderStaging_Details.UpdateDate
FROM
dbo.Vendor_Assigned_Locations
INNER JOIN
dbo.Vendor_Contacts
INNER JOIN
dbo.Vendors
INNER JOIN
dbo.OrdersStaging
INNER JOIN
dbo.OrderStaging_Details ON dbo.OrdersStaging.OrderStagingID = dbo.OrderStaging_Details.OrderStagingID
ON dbo.Vendors.VendorID = dbo.OrderStaging_Details.VendorId
ON dbo.Vendor_Contacts.Vendor_ID = dbo.Vendors.VendorID
ON dbo.Vendor_Assigned_Locations.LocationID = dbo.OrdersStaging.LocationID
AND dbo.Vendor_Assigned_Locations.VCID = dbo.Vendor_Contacts.VCID
INNER JOIN
dbo.Orders ON dbo.OrdersStaging.OrderStagingID = dbo.Orders.OrderStagingID
AND dbo.Vendors.VendorID = dbo.Orders.VendorID
AND dbo.Vendor_Contacts.VCID = dbo.Orders.VendorContactID
AND dbo.OrdersStaging.LocationID = dbo.Orders.LocationID
LEFT OUTER JOIN
dbo.Order_Details ON dbo.Orders.OrderID = dbo.Order_Details.OrderID
WHERE
(dbo.OrderStaging_Details.OrderStagingID = @OrderStagingID)
AND (dbo.OrdersStaging.LocationID = @Locationid)
AND (dbo.Vendors.VendorID = @Vendorid)
AND (dbo.Order_Details.OrderID IS NULL)
end