如何在Insert into ..select中处理增量标识

golden24kcn 2008-07-24 05:38:39
表1

id
name
sex

这时表1的id列要求不能是自增长列,添加一条新数据时要从get_sequence存储过程中取出。

表2

name
sex

问题:
insert into 表1 (name, sex) select * from 表2

这样的批量处理如何为ID列赋值?

做insert之后再做update也可以,只是不允许用游标实现,求助。

...全文
328 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
ChinaJiaBing 2008-07-25
  • 打赏
  • 举报
回复

触发器....
ydage 2008-07-24
  • 打赏
  • 举报
回复
--楼主试下这个,我自己建立了存储过程测试的
--建立存储过程
create proc get_sequence (@i int output)
as
begin
select @i = isnull(max(id),0)+1 from table1
end

--结合存储过程返回值,从table2插入数据到table1
if object_id('#tempdb..#t') is not null
drop table #t

select id = identity(int),* into #t from table2

declare @i int,@id int,@num int

select @id = 1,@num =count(*) from table2

while @id <= @num
begin
exec get_sequence @i output

insert into table1 select @i,name,sex from #t where id = @id
set @id = @id + 1
end

select * from table1
cxmcxm 2008-07-24
  • 打赏
  • 举报
回复
存储过程生成记录时,先取表的最大值,再加上1,2,4,5,6这样顺序的记录
ChinaITOldMan 2008-07-24
  • 打赏
  • 举报
回复
把get_sequence变成函数可以吗,用函数就容易了
anshixiaozi 2008-07-24
  • 打赏
  • 举报
回复
不知道你的不能用游标是什么意思,但是提供一个思路
若真的不能用游标,你可以把结果全部取出来(批量,不用游标)
在外部把id准备好(循环即可实现)
然后批量插入
golden24kcn 2008-07-24
  • 打赏
  • 举报
回复
新ID要求从get_sequence存储过程中取出
golden24kcn 2008-07-24
  • 打赏
  • 举报
回复
没人会吗?
ydage 2008-07-24
  • 打赏
  • 举报
回复
--建立测试数据
create table table1(id int ,name varchar(10),sex int)

insert into table1 select 1,'ax',0
union all select 2,'bd',1

create table table2 (name varchar(10),sex int)

insert into table2 select '201',0
union all select '202',1
union all select '203',1

--将table2的数据插入table1(ID在原表基础上增加)
declare @id varchar(100)
select @id =convert(varchar,isnull(max(id),0)+1) from table1

if object_id('t') is not null
drop table t

exec('select id = identity(int,'+@id+',1),name,sex into t from table2')

insert into table1 select * from t

--查询
select * from table1

--结果
id name sex
--------------------
1 ax 0
2 bd 1
3 201 0
4 202 1
5 203 1
golden24kcn 2008-07-24
  • 打赏
  • 举报
回复
自己顶
golden24kcn 2008-07-24
  • 打赏
  • 举报
回复
楼上,试了一下你的方法,提示语法错误
utpcb 2008-07-24
  • 打赏
  • 举报
回复
insert into 表1 (id ,name, sex)

select (exec(get_sequence))as a,* from 表2
utpcb 2008-07-24
  • 打赏
  • 举报
回复
exec('insert into 表1 (name, sex) 

select'+ get_sequence+',* from 表2' )
青锋-SS 2008-07-24
  • 打赏
  • 举报
回复
用触发器.

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧