使用触发器插入另一个表

时间:2016-02-09 07:43:27

标签: sql sql-server-2008 triggers insert

我想在使用触发器插入后插入记录,但它无法正常工作。 它在会计表上。 首先我写了触发器,我得到了这个错误: INSERT语句与FOREIGN KEY约束冲突数据库中发生冲突语句已终止。 然后我找到了密钥并在该表上写了触发器然后我收到了新的错误: 这个sqltransaction已经完成它不再可用的sql server 这是触发器:

USE [Sepidar01]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Alter TRIGGER [INV].[CrmSelectInsertVWInvoiceItems] 
ON  [INV].[InventoryDeliveryItem] 
After Insert
AS 
BEGIN
SET NOCOUNT ON;

DECLARE @CustomerCode varchar(40)
DECLARE @InvoiceRef INT
DECLARE @Price decimal(19, 4)
DECLARE @CreationDate datetime
DECLARE @Quantity decimal(19, 4)
DECLARE @GuID uniqueidentifier
DECLARE @KalaCode int
DECLARE @BaseInvoiceItem int

SELECT @BaseInvoiceItem=(BaseInvoiceItem) FROM INSERTED

select @CreationDate AS [inv.CreationDate],@CustomerCode AS [dl.Code],@Price       
AS [invitem.Price],@Quantity AS [invitem.Quantity], @KalaCode AS [itemst.ItemStockID]
from [Sepidar01].[INV].[InventoryDeliveryItem] as invent
join sls.InvoiceItem as invitem
on BaseInvoiceItem =InvoiceItemID
join sls.Invoice as inv
on InvoiceId = InvoiceRef
join acc.dl as dl
on inv.CustomerRealName like dl.Title
join inv.ItemStock as itemst
on invitem.ItemRef = itemst.ItemRef
where invent.BaseInvoiceItem  = @BaseInvoiceItem

SELECT @GuID AS [bartar_newpaitientId]
  FROM [192.168.0.15].[Bartar_MSCRM].[dbo].[bartar_newpaitientBase] as newPatient
  where newPatient.bartar_CustomerCode = @CustomerCode

INSERT INTO [192.168.0.15].[Test_MSCRM].[dbo].[bartar_callcenterreportBase]
       ([bartar_callcenterreportId]
       ,[OwnerId]
       ,[statecode]
       ,[CreatedOn]
       ,[bartar_Date] 
       ,[bartar_patientName]
       ,[bartar_Brand]
       ,[bartar_Paste]
       ,[bartar_Bag]
       ,[bartar_ACC]
       ,[bartar_NextDateSales]
       ,[bartar_name])
 VALUES
       (NEWID(),'315BE87D-0035-E511-80B5-0007E9498006',0,@CreationDate,@CreationDate,@GuID,0,0,0,0,@CreationDate,'System')

END

那么我该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:1)

你必须改变你的第一个选择:

select @CreationDate=[inv.CreationDate],@CustomerCode=[dl.Code],
@Price=[invitem.Price],
@Quantity=[invitem.Quantity], @KalaCode=[itemst.ItemStockID]
from [Sepidar01].[INV].[InventoryDeliveryItem] as invent
join sls.InvoiceItem as invitem
on BaseInvoiceItem =InvoiceItemID
join sls.Invoice as inv
on InvoiceId = InvoiceRef
join acc.dl as dl
on inv.CustomerRealName like dl.Title
join inv.ItemStock as itemst
on invitem.ItemRef = itemst.ItemRef
where invent.BaseInvoiceItem  = @BaseInvoiceItem

第二个:

SELECT @GuID=[bartar_newpaitientId]
  FROM [192.168.0.15].[Bartar_MSCRM].[dbo].[bartar_newpaitientBase]
    as newPatient
  where newPatient.bartar_CustomerCode = @CustomerCode

所以你的变量值得。

如果您收到此错误Msdtc on server is unavailable,这就是解决方案: fix error