首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

插入相同记录有关问题(identity)

2012-02-28 
插入相同记录问题(identity)有2张表A表中有3个字段idFirstClassSecondClass110121023103(id为从B表中取得

插入相同记录问题(identity)
有2张表
A表中有3个字段   id     FirstClass   SecondClass  
              1           1                       01
                                2           1                       02
                                3           1                       03
(id为从B表中取得的MaxId值而不是自增字段,   FirstClass为大类编号,SecondClass为小类编号)

B表中有2个字段           MaxId       Name
    4               A

(MaxId存当前最大的id+1,以供下次加记录时使用,Name为表名)

现在想根据A表中这3条大类编号为1的相同记录插入到大类编号为2、3   里,也就是想得到以下结果
              id     FirstClass   SecondClass  
              1           1                       01
                                2           1                       02
                                3           1                       03
              4           2                       01
                                5           2                       02
                                6           2                       03
              7           3                       01
                                8           3                       02
                                9           3                       03

请高手帮忙给个SQL语句

[解决办法]
是这样?
declare @ta table (id int, FirstClass int, SecondClass varchar(2))
insert @ta select 1, 1, '01 '
insert @ta select 2, 1, '02 '
insert @ta select 3, 1, '03 '

declare @a int,@b int,@i int,@j int,@s varchar(2)
select @a=isnull(max(firstclass),0),@j=1,@b=isnull(max(id),0) from @ta
set @a=@a+1
while @a <4


begin
select @b=@b+1,@s=right(100+@j,2)

insert @ta select @b,@a,@s

select @j=case when @j+1 <4 then @j+1 else 1 end,@a=case when @j=1 then @a+1 else @a end

end

select * from @ta

id FirstClass SecondClass
----------- ----------- -----------
1 1 01
2 1 02
3 1 03
4 2 01
5 2 02
6 2 03
7 3 01
8 3 02
9 3 03

(所影响的行数为 9 行)



[解决办法]
declare
@idint,
@sqlnvarchar(200)

select @id=max(id) from a
set @sql= 'select IDENTITY(int, '+cast((@id+1) as nvarchar(50))+ ',1) as id ,2,SecondClass into t1 from a '
exec sp_executesql @sql
insert into a select * from t1

select @id=max(id) from a
set @sql= 'select IDENTITY(int, '+cast((@id+1) as nvarchar(50))+ ',1) as id ,3,SecondClass into t2 from a '
exec sp_executesql @sql
insert into a select * from t2

drop table t1
drop table t2

我偷懒

热点排行