我数据库的ID是自动ID如:
表A
ID 字段1 字段2
1 DD AAA
2 BB BBB
怎么把ID 为1 和 2 中间插入一个新记录,新记录的ID 为2 把2 自动调成3呢?
------解决方案--------------------
identity列是不允许UPDATE操作的
------解决方案--------------------
用代码交换行位置就好了
------解决方案--------------------
看我编写的存储过程是否和您意思~~~前提是要先把ID字段改回INT数据类型
create proc spinsertany
@n int --定义一个参数,[email protected]
as
declare @count int
select @count=(select count(ID) from 表1)+1 --统计插入新行后的总行数
if exists(select * from 表1 where [email protected]) --判断插入的记录数字是否超出范围
begin
declare @col1 varchar(100), @col2 varchar(100) --定义两个做交换容器的变量
insert into 表1 values(@count, 'nnn ', 'nnn ') --插入行
while @n <[email protected] --2 --循环次数
begin
select @col1=字段1 from 表1 where [email protected]+1 --取得要插入行的字段1的数据
select @col2=字段2 from 表1 where [email protected]+1
update 表1 set 字段1=(select 字段1 from 表1 where [email protected]) where [email protected]+1 --与最后一条记录交换
update 表1 set 字段2=(select 字段2 from 表1 where [email protected]) where [email protected]+1
update 表1 set [email protected] where [email protected] --把刚才取得的行数据替换给最后行
update 表1 set [email protected] where [email protected]
select @[email protected]+1 --循环增量,循环在需插入行以后行都与最后行做交换操作~
end
end
else
print '请输入正确的参数或者参数超出范围 '
go
我这里写了一个存储过程~~ 希望对您有用~~~~~~~~以后大家多交流交流~
谢谢先~~~~