SQL查询每行循环两次?

时间:2018-03-27 13:06:33

标签: sql sql-server

当我从Web应用程序触发存储过程时,它会循环两次并创建同一行的两个相同条目。我无法解释原因:/

该查询应该INSERT(重新安排)所有提交的行。它使用光标遍历每一行SELECT,然后INSERT,每行都有正确的数据。

这是我的SQL:

CREATE PROCEDURE [cil].[executeCIL_updateComplDate_And_ReSchedule]
    @equipID INT,
    @date DATE,
    @ip VARCHAR(15)
AS   
    /* add completion date */
    UPDATE cil.schedule 
    SET completionDate = CAST(GETUTCDATE() AS SMALLDATETIME), 
        complIP = @ip
    WHERE schedule.id IN (SELECT schedule.id 
                          FROM cil.schedule
                          LEFT JOIN cil.task ON cil.schedule.taskFK = cil.task.id
                          --WHERE CAST(scheduledDate AS DATE)<=CAST(GetDate() AS DATE)
                          WHERE CAST(scheduledDate as DATE) = @date
                            AND completionDate IS NULL
                            AND result IS NOT NULL
                            AND equipFK = @equipID);

    /* reschedule tasks */
    DECLARE @nextTaskID AS INT;
    DECLARE @nextScheduledDate AS DATETIME2(6);
    DECLARE @nextRotaCycle AS INT;

    DECLARE db_cursor CURSOR FOR
        SELECT taskFK, scheduledDate, rotaCycle
        FROM cil.schedule 
        LEFT JOIN cil.task ON cil.schedule.taskFK = cil.task.id
        WHERE completionDate = CAST(GETUTCDATE() AS SMALLDATETIME)
          AND equipFK = @equipID;

    OPEN db_cursor;

    FETCH NEXT FROM db_cursor INTO @nextTaskID, @nextScheduledDate, @nextRotaCycle;

    WHILE @@FETCH_STATUS = 0  
    BEGIN  
        --Do stuff with scalar values
        INSERT INTO cil.schedule (taskFK, scheduledDate, rotaCycle)
        VALUES (@nextTaskID, 
                DATEADD(dd, @nextRotaCycle, @nextScheduledDate),
                @nextRotaCycle)

        FETCH NEXT FROM db_cursor INTO @nextTaskID, @nextScheduledDate, 
@nextRotaCycle;
    END;

    CLOSE db_cursor;
    DEALLOCATE db_cursor;
GO

1 个答案:

答案 0 :(得分:1)

您似乎有一个由光标查询的连接引起的重复

如果从外部运行此查询,在SSMS中,它是否只生成一行?

SELECT taskFK, scheduledDate, rotaCycle
FROM cil.schedule 
LEFT JOIN cil.task ON cil.schedule.taskFK=cil.task.id
WHERE completionDate=CAST(GETUTCDATE() AS SMALLDATETIME)
AND equipFK=@equipID ;

和双打来自一个表格任务。 如果未使用此表,请考虑将其删除