SQL Server中的CURSOR不会停止

时间:2016-05-02 07:00:34

标签: sql-server cursor

我制作游标以从一个表中获取值并插入第二个表。只插入35个条目。但我的光标不会停止。 一分钟后它就不会停止。我必须停止执行。 请告诉我的错误。

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 个答案:

答案 0 :(得分:1)

我不认为游标处理速度很慢,但是其他贡献者暗示你的select语句中的旧样式连接可能需要很长时间,具体取决于2个表的大小。尝试将其更改为

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