批量插入而不是光标

时间:2016-06-07 03:13:55

标签: sql sql-server cursor

我们有这样的结构:

Deposit 
PrimaryKey depositId
Depositofficerid 


1-> M Depositworker 
ForeignKey depositId
WorkerId
WorkerRoleGroupId = 1

对于Depositofficerid表格中的每个DepositDepositworker表格中应该有workerid = Depositofficerid的记录。

这是我使用cursor完成的方式。我想知道是否有办法在Depositworker表中进行批量插入。

IF OBJECT_ID('tempdb..#tempdeposits') IS NOT NULL
    DROP TABLE dbo.#tempdeposits;

CREATE TABLE #tempdeposits (
    DepositId int
)
INSERT INTO #tempdeposits (DepositId)
    SELECT
        DepositId
    FROM Deposit
    WHERE
        CreatedDate = '2005-01-14 16:05:51.920'


DECLARE @DepositId int
DECLARE @getloans CURSOR
SET @getloans = CURSOR FOR
SELECT
    DepositId
FROM #tempdeposits
OPEN @getdeposits
FETCH NEXT FROM @getdeposits INTO @DepositId
WHILE @@FETCH_STATUS = 0
BEGIN
    IF NOT EXISTS (SELECT
            Depositworkerid
        FROM Depositworker
        WHERE DepositId = @DepositId
        AND WorkerRoleGroupId = 1)
    BEGIN
        PRINT @DepositId

        INSERT INTO DepositWorker (DepositId, WorkerId, WorkerRoleGroupId, CreatedBy, CreatedDate, UpdateCounter)
            SELECT
                @DepositId,
                Depositofficerid,
                1,
                1,
                GETDATE(),
                1
            FROM Deposit
            WHERE
                DepositId = @DepositId
    END
    FETCH NEXT
    FROM @getdeposits INTO @DepositId
END
CLOSE @getdeposits
DEALLOCATE @getdeposits

可以某种方式帮助我将其作为批量插入而不是cursor

1 个答案:

答案 0 :(得分:0)

是的,您可以使用相关NOT EXISTS

以基于集合的方式执行此操作
INSERT INTO DepositWorker (DepositId, WorkerId, WorkerRoleGroupId, CreatedBy, CreatedDate, UpdateCounter)
SELECT  
    d.DepositId,
    d.Depositofficerid,
    1,
    1,
    GETDATE(),
    1
FROM Deposit d
WHERE 
    CreatedDate = '2005-01-14 16:05:51.920'
    AND NOT EXISTS(
        SELECT 1
        FROM DepositWorker dw
        WHERE
            dw.DepositId = d.DepositId
            AND dw.WorkerRoleGroupId = 1
    )