我们有这样的结构:
Deposit
PrimaryKey depositId
Depositofficerid
1-> M Depositworker
ForeignKey depositId
WorkerId
WorkerRoleGroupId = 1
对于Depositofficerid
表格中的每个Deposit
,Depositworker
表格中应该有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
?
答案 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
)