在存储过程中插入DataTable时重复条目插入

时间:2018-10-19 07:23:04

标签: c# sql asp.net

我正在使用DataTable在数据库中插入StoredProcedure,但是问题是,它插入了要插入的DataTable的实际条目数的两倍,操作步骤如下,请参考我,如果我使用错误的方法,为什么要复制行?所需的退货工作正常。 在此先感谢

ALTER PROCEDURE [dbo].[proc_InsertStore_Recvry]
(@dt_Recovery Recovery_Store READONLY)

AS
Declare @RecoveryIDs as Table (IDs int, ClientIds int)
declare @StoreID int
declare @ClientID int
declare @Arrears decimal(18, 2)
declare @NetDues decimal(18, 2)
declare @Received decimal(18, 2)
Declare @RecoveryRecID int

begin
select * into #tempTable from @dt_Recovery

declare @Count int
set @Count= (select COUNT(*) from #tempTable)

while(@Count > 0)
begin

set @Count = @Count-1
set @ClientID = (Select top 1 ClientID from #tempTable)
set @StoredID = (Select top 1 StoredID from #tempTable where ClientID=@ClientID)
set @Arrears = (Select top 1 Arrears from #tempTable where ClientID=@ClientID)
set @NetDues = (Select top 1 NDues from #tempTable where ClientID=@ClientID)
set @Received = (Select top 1 Received from #tempTable where ClientID=@ClientID)

Insert into tblRecovery (StoreID,  ClientID, Arrears, NetDues, Received)
values (@StoreID,@ClientID,@Arrears,@NetDues,@Received)

select @RecoveryID = Scope_Identity()

insert into @RecoveryIDs (IDs,ClientIds) values (@RecoveryID, @ClientID )

delete from #tempTable where ClientID=@ClientID

end
Select * from @RecoveryIDs

1 个答案:

答案 0 :(得分:0)

您似乎正在使用SQL Server。如果是,那么为什么要使用while循环将值插入表中并返回插入的ID? 可以通过OUTPUT子句以更好的方式完成相同操作: OUTPUT documentation

示例:

INSERT INTO tblRecovery(StoreID,  ClientID, Arrears, NetDues, Received) OUTPUT INSERTED.ID, INSERTED.CLientId INTO @RecoveryIDs(IDs, ClientIds) SELECT StoredID, ClientID, Arrears, NDues, Received FROM #tempTable

除此之外,您的SQL代码似乎没有问题。那么您也可以发布.NET代码吗?