Sql 无法在游标循环中获取第一个插入行标识

Sql 无法在游标循环中获取第一个插入行标识,sql,sql-server-2008,sql-server-2008-r2,cursor,temporary,Sql,Sql Server 2008,Sql Server 2008 R2,Cursor,Temporary,我一直在尝试将一些行插入到临时表中,该临时表需要表a中的标识…这是从游标插入的表。。 这里的一切都很好,但唯一的问题是我没有得到表A中插入的第一行的标识 假设我在表A中插入3行…我在临时表中得到最后2行..而不是第一行..如果我只在表A中发送一行,则临时表为空 这是我的存储过程。表A是tblClients Create PROCEDURE [dbo].[lsp1_propAdmClnt] ( @usrprflId bigint, @pr

我一直在尝试将一些行插入到临时表中,该临时表需要表a中的标识…这是从游标插入的表。。 这里的一切都很好,但唯一的问题是我没有得到表A中插入的第一行的标识 假设我在表A中插入3行…我在临时表中得到最后2行..而不是第一行..如果我只在表A中发送一行,则临时表为空 这是我的存储过程。表A是tblClients

Create PROCEDURE [dbo].[lsp1_propAdmClnt]          
(          
@usrprflId bigint,          
@preClient tpClient readonly           

)          
as            
declare @err int         
CREATE TABLE #tblids(      
clntid int,      
imgname nvarchar(350)  

)  
declare @clntid as int      
declare @clntname nvarchar(300)      
declare @imgname nvarchar(300)     
Begin Transaction        




declare transfclntid cursor for select  clntname, [imgname] from @preClient      
open transfclntid      
fetch next from transfclntid into @clntname, @imgname      
while @@fetch_status=0      
begin      

insert into tblClients (usrprflId,Name,Img,cdate) 
values(@usrprflId, @clntname, @imgname,GETDATE())      

SET @clntid = (SELECT SCOPE_IDENTITY())    
insert into #tblids (clntid, imgname) values (@clntid, @imgname)      
fetch next from transfclntid into @clntname, @imgname      
end      
close transfclntid      
deallocate transfclntid      


 select * from  #tblids                        
select @err=@@TOTAL_ERRORS          
if(@err<>0)          
Begin          
Rollback Transaction          
return 0          
End          

Commit transaction 

首先,应使用以下INSERT SELECT语句替换该游标:

declare @tblids table
(
    clntid INT NOT NULL,
    imgname NVARCHAR(350)
);
insert into tblClients (usrprflId, Name, Img, cdate) 
output inserted.clntid, inserted.Img into @tblids (clntid, imgname)
select  @usrprflId, clntname, [imgname], GETDATE()
from @preClient
然后,如果需要第一个标识值,可以使用:

SELECT MIN(clntid)
FROM @tblids