我有一个表,它将保存将在同一服务器上更新另一个表的待处理数据。此挂起表从另一个服务器存储过程获取数据。一旦数据在此挂起表中,存储过程将尝试基于挂起表中的tinyint列插入,更新或删除。
除非需要发生某些事情,否则此待处理表将保持为空。在程序结束时,我们从此待处理表中删除。
如果在程序运行时需要更新的同一记录从另一台服务器插入两次,会出现问题。最后,两个记录都将被清除。我试图通过在挂起的表上添加增量id来解决这个问题,但是我无法在插入中输出id:
insert into config.table (col1, col2, col3)
output inserted.col3, pendingId into @table
select p.col1, p.col2, p.col3
from pendingTable p
left join config.table t on p.col1 = t.col1
where t.col1 is null
我在pendingId上收到错误。我计划使用@table变量从挂起中删除,以避免删除未触及的记录(在程序运行时添加的新插入记录)。
delete p
from pendingTable p
inner join @table t on p.pendingId = t.pendingId and p.col3 = t.col3
答案 0 :(得分:2)
您需要缓存待处理记录并在之后删除它们。
begin tran
select p.pendingid
into #pendingcache
from pendingTable p
left join config.table t on p.col1 = t.col1
where t.col1 is null
insert into config.table (col1, col2, col3)
output inserted.col3, pendingId into @table
select ...
from #pendingcache
delete p
from pendingTable p
inner join #pendingcache c on c.pendingId = p.pendingId
commit
<小时/> 以下的原始答案
您在inserted
之前遗失pendingid
,即inserted.pendingid
。要明确inserted
和deleted
之间的歧义。
以下作品。
哦,你也错过了整个SELECT语句,或者我假设它实际上是由于创建了&#34; mock&#34;这个问题的表格?
create table configtable (col1 int, col2 int, col3 int, pendingid int identity)
create table pendingtable (col1 int, col2 int, col3 int, pendingid int identity)
insert pendingtable values (1,2,3)
declare @table table (col3 int, pendingid int)
insert into configtable (col1, col2, col3)
output inserted.col3, inserted.pendingId into @table
select col1, col2, col3
from pendingTable p