SQL Server中的Cursor有替代方法吗?

时间:2017-04-17 06:01:06

标签: sql-server stored-procedures sql-server-2012 sql-server-2008-r2 cursor

ALTER PROCEDURE [dbo].[sp_Curing_log_data] 
AS
BEGIN

SET NOCOUNT ON;
BEGIN TRY

DECLARE @Rdatetime AS Datetime
DECLARE @Barcode AS Varchar(15)
DECLARE @Cavity AS Varchar(5)
DECLARE @IPLH AS Float
DECLARE @IPRH AS Float
DECLARE @ITLH AS Float
DECLARE @ITRH AS Float
DECLARE @PTLH AS Float
DECLARE @PTRH AS Float
DECLARE @SPLH AS Float
DECLARE @SPRH AS Float
DECLARE @MachineID AS Varchar(15)
DECLARE @ShiftID AS Varchar(5)
DECLARE @C_Flag AS Int


DECLARE @MyCursor CURSOR

SET @MyCursor = CURSOR FAST_FORWARD

FOR

select TOP (10000) * from [10.65.84.4].[CEAT].dbo.Curing_Trend with(NOLOCK) order by Rdatetime asc

OPEN @Mycursor

FETCH NEXT FROM @MyCursor
INTO 
@Rdatetime,@Barcode,@Cavity,@IPLH,@IPRH,@ITLH,@ITRH,@PTLH,@PTRH,@SPLH,@SPRH,@MachineID,@ShiftID,@C_Flag
        WHILE @@FETCH_STATUS = 0
        BEGIN

            INSERT INTO dbo.Curing_Trend (Rdatetime, Barcode, Cavity, IPLH, IPRH, ITLH, ITRH, PTLH, PTRH, SPLH, SPRH, MachineID, ShiftID)
            values(@Rdatetime,@Barcode,@Cavity,@IPLH,@IPRH,@ITLH,@ITRH,@PTLH,@PTRH,@SPLH,@SPRH,@MachineID,@ShiftID)

            Update [10.65.84.4].[CEAT].dbo.Curing_Trend SET C_Flag = 0 where Rdatetime = @Rdatetime and Barcode = @Barcode

            FETCH NEXT FROM @MyCursor
            INTO @Rdatetime,@Barcode,@Cavity,@IPLH,@IPRH,@ITLH,@ITRH,@PTLH,@PTRH,@SPLH,@SPRH,@MachineID,@ShiftID,@C_Flag
        END
        CLOSE @MyCursor
        DEALLOCATE @MyCursor
        Delete from [10.65.84.4].[CEAT].dbo.Curing_Trend  where C_Flag =0
    END TRY
    BEGIN CATCH
            EXEC [dbo].[sp_InsertErrorDetails]
            Return 2
        END CATCH
    END

这是我将数据从一台服务器传输到另一台服务器的过程,因为大约有数百万的数据游标无效。

请任何人都可以建议替代游标而不是光标。

提前致谢

2 个答案:

答案 0 :(得分:0)

您可以按批次使用Insertdelete

INSERT INTO dbo.Curing_Trend (Rdatetime, Barcode, Cavity, 
IPLH, IPRH, ITLH, ITRH, PTLH, PTRH, SPLH, SPRH, MachineID, ShiftID)      
    SELECT TOP (10000) 
        t.Rdatetime, t.Barcode, t.Cavity, t.IPLH,
        t.IPRH, t.ITLH, t.ITRH, t.PTLH, t.PTRH,
        t.SPLH, t.SPRH, t.MachineID, t.ShiftID 
    FROM
        [10.65.84.4].[CEAT].dbo.Curing_Trend ct  
    ORDER BY
        Rdatetime ASC

; WITH cte AS
(
   SELECT TOP 10000 *
   FROM [10.65.84.4].[CEAT].dbo.Curing_Trend ct  
   ORDER BY Rdatetime ASC
)
DELETE FROM cte

答案 1 :(得分:0)

使用OUTPUT子句,您可以在一个查询中执行此操作。如果需要,您也可以按C_Flag进行过滤。

; WITH cte AS
(
   SELECT TOP 10000 *
   FROM [10.65.84.4].[CEAT].dbo.Curing_Trend ct  
   ORDER BY Rdatetime ASC
)
DELETE
FROM cte
OUTPUT Rdatetime, Barcode, Cavity, IPLH, IPRH, ITLH, ITRH, PTLH, PTRH, SPLH, SPRH, MachineID, ShiftID
INTO [CEAT].dbo.Curing_Trend (Rdatetime, Barcode, Cavity, IPLH, IPRH, ITLH, ITRH, PTLH, PTRH, SPLH, SPRH, MachineID, ShiftID)