2016-05-02 76 views
-1

我的光標從一個表中取值並插入到第二個表中。只有35個條目要插入。但我的光標不停止。 即使一分鐘後也不會停止。我必須停止執行。 請告訴我的錯誤。在sql server中的CURSOR不停止

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

ALTER Procedure [dbo].[Insert_Details_In_CForm_From_Orders] 
as Begin 

    Declare @CF_B_ID [int], 
      @CF_Date [date], 
      @CF_Invoice_No [int], 
      @CF_Quantity [decimal](18, 2), 
      @CF_Amount [decimal](18, 2), 
      @CF_Tax [decimal](18, 2), 
      @CF_Total_Amount [decimal](18, 2), 
      @Financial_Year [nvarchar](25), 
      @Quater [int] 

    Select @Financial_Year = Financial_Year, 
      @Quater = Quater 
    From Company 

    --Select a.O_B_ID,a.O_B_LR_Datetime,a.O_B_Bill_No,a.Total_Quantity,a.Total_Duty_Plus,a.Total_CST,a.Total_CST_Plus From Orders a , C_Form b where a.CST_TF=1 AND a.O_B_Bill_No!=b.CF_Invoice_No 
    Declare @CFormCursor CURSOR 
    SET @CFormCursor = CURSOR FAST_FORWARD 
    FOR 
     Select a.O_B_ID as CF_B_ID, 
       a.O_B_LR_Datetime as CF_Date, 
       a.O_B_Bill_No as CF_Invoice_No, 
       a.Total_Quantity as CF_Quantity, 
       a.Total_Duty_Plus as CF_Amount, 
       a.Total_CST as CF_Tax, 
       a.Total_CST_Plus as CF_Total_Amount 
     From Orders a , C_Form b 
     where a.CST_TF = 1 
     AND a.O_B_Bill_No != b.CF_Invoice_No 

    OPEN @CFormCursor 
    FETCH NEXT FROM @CFormCursor 
    INTO @CF_B_ID ,@CF_Date ,@CF_Invoice_No ,@CF_Quantity ,@CF_Amount ,@CF_Tax ,@CF_Total_Amount 

    WHILE @@FETCH_STATUS = 0 
    BEGIN 
     INSERT INTO [dbo].[C_Form] ([CF_B_ID],[CF_Date],[CF_Invoice_No],[CF_Quantity],[CF_Amount],[CF_Tax],[CF_Total_Amount],[Financial_Year],[Quater]) 
     VALUES(@CF_B_ID ,@CF_Date ,@CF_Invoice_No,@CF_Quantity,@CF_Amount,@CF_Tax,@CF_Total_Amount,@Financial_Year,@Quater) 
     FETCH NEXT FROM @CFormCursor 
     INTO @CF_B_ID ,@CF_Date ,@CF_Invoice_No ,@CF_Quantity ,@CF_Amount ,@CF_Tax ,@CF_Total_Amount 
    END 
    CLOSE @CFormCursor 
    DEALLOCATE @CFormCursor 
End 
+1

爲什麼你需要一個光標?爲什麼不使用'insert ... select'? –

+0

但我應該知道我在哪裏滯後 – Shantnu

+0

另外,閱讀Aaron Bertrand的這篇文章:[踢壞的習慣:使用舊式JOIN](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08 /bad-habits-to-kick-using-old-style-joins.aspx) –

回答

1

我不認爲光標處理是緩慢的,但其他的貢獻者已經暗示了老款在SELECT語句加入取決於兩個表的大小可能需要很長的時間。嘗試改變它爲

Select a.O_B_ID as CF_B_ID, 
       a.O_B_LR_Datetime as CF_Date, 
       a.O_B_Bill_No as CF_Invoice_No, 
       a.Total_Quantity as CF_Quantity, 
       a.Total_Duty_Plus as CF_Amount, 
       a.Total_CST as CF_Tax, 
       a.Total_CST_Plus as CF_Total_Amount 
     From Orders a 
     join C_Form b on a.O_B_Bill_No = b.CF_Invoice_No 
     where a.CST_TF = 1 
     AND b.CF_Invoice_No is null 
+0

這個連接並不等同於問題中的連接。 –

+0

@Zohar。我認爲不應該。原始選擇在我看來,只有沒有出現在C_Form中的訂單纔有意義。所以等價的連接與在C_form中沒有出現的訂單的等價性被空測試捕獲。 A!= join會導致與原始相同的問題。 –

+0

這是由OP來決定的。我只是陳述一個事實:-) –