2017-05-29 83 views
0

我正在同步我們的crm和erp。我將從我們的crm中獲得數百條記錄,每隔15分鐘插入一次,將它們分別放入我們的erp約20張表格中。我想要插入一條記錄,並記錄任何錯誤,如果插入在20個表中的任何一個上失敗並且反轉該記錄的插入。我可以看到如何使用遊標或while循環一次插入一條記錄。我將如何一次插入一條記錄並使用事務記錄錯誤?插入批記錄,許多插入查詢,遊標,while循環或事務記錄每個記錄更好

--transaction方法 --BEGIN TRANS

光標方法

--partial代碼清單,即工作

declare @cur cursor; 
declare @x nvarchar(9); 
begin 
    set @cur = cursor for 
    select people_id from powercampustest.dbo.PeopleChanges where (processed is null) 

    open @cur 
    fetch next from @cur 
    into @x 

    while @@FETCH_STATUS = 0 
    begin 
     /* add the rest here */ 
     begin try 
     --20 insert queries 


     end try 

     begin catch 
      --transaction method 
      --ROLLBACK 

      print 'Error on people id ' + @x 

      --cursor method 
      --if one insert fails delete all inserted 
      --do we want error out on first fail, or try all and report if each failed or not 
      --TableListForDelete, list of tables for delete 
      --write error in log table 
     end catch 
     fetch next from @cur 
     into @x 
    end; 

    close @cur; 
    deallocate @cur; 
end; 


=========================================================== 
--partial code list of while method 

select @loop = @@rowcount 
if @loop <= 0 Return 

Set @PersonId = 0 
Select @PersonId = 
     (Select Min([PersonId]) From inserted Where [PersonId] > @PersonId) 

While @PersonId Is Not Null 
    begin 
     SELECT ... 

    --Get Next Id 
    Select @PersonId = 
      (Select Min([PersonId]) From inserted Where [PersonId] > @PersonId) 

END 


    if @@error <> 0 
    begin 
     raiserror(1944115471, 16, 65, @MessageType) with nowait; 
     rollback tran; 
    end 
end 

回答

0

使用本:

set xact_abort on; 
begin tran 
    --all your inserts here 
commit tran 

將盡一切如果沒有錯誤或者沒有錯誤。 遊標是邪惡的,不要使用它們。這也不需要循環。

+0

我想嘗試每個插入,所以我可以看到所有的錯誤。現在需要很長時間才能發現一個錯誤。另外,我認爲如果我使用遊標並且可以在調試器中逐步查看內存中發生了什麼。有沒有辦法在交易中看到? – ERPISE