夸服务器sqlserver批量插入 返回自增主键ID 把所有主键ID插入到从表中
declare @ids int
declare @rowcount int
declare @StartId int
insert into srv_lnk.数据库.表2(name,password)
select name,password
from 数据库.表1
where not exists(select b.name,b.password from srv_lnk.数据库.表2 b where name= b.name)
select @ids=SCOPE_IDENTITY(),@rowcount=@@ROWCOUNT
set @StartId=@ConsultationId-@rowcount+1
while @StartId<=@ConsultationId
begin
insert into srv_lnk.数据库.表3(id,createtime)
select @StartId,GETDATE()
set @StartId=@StartId+1
end
为什么SCOPE_IDENTITY()为空
我写点伪代码:
private InsertData(){
var StartId = exec("select max(id) from table1");
for(var i =1;i<10;i++){
exec("insert Table1(Name) values('Name"+i.ToString()+"')")
}
var EndId = exec("select max(id) from table1");
for(var i =StartId;i<=EndId;i++){
exec("insert Table2(MainId) values('"+i.ToString()+"')")
}
}
改造1楼的伪代码:
private InsertData(){ var idList=new List<int>(); for(var i =1;i<10;i++){ var id=exec("insert Table1(Name)values('Name"+i.ToString()+"') select @@identity"); idList.Add(id); } foreach(var id in idList){ exec("insert Table2(MainId) values('"+id.ToString()+"')") } }