我想自定义每条记录的序列号,这个序列号在客户端输入,假如表格里已经有如下序列号的存在了:id
1
2
3
5
8现在我想新插入一条记录,并把新插入的序列号值设为2,可现在2号记录已经存在了,所以我想先把2号记录加1,3号记录加1,5号记录和8号记录不变。这个存储过程该如何写呢?恳请各位朋友指教。
1
2
3
5
8现在我想新插入一条记录,并把新插入的序列号值设为2,可现在2号记录已经存在了,所以我想先把2号记录加1,3号记录加1,5号记录和8号记录不变。这个存储过程该如何写呢?恳请各位朋友指教。
1
2
3
5
8
这样很讨厌,你如果一开始就这样:
id
1
2
3
4
5插入记录:
update table set id=id+1 where id>=2
insert ....删除记录:
delete from tab where id=2
update table set id=id-1 where id>2这样就方便多了.不必去判断是否断号.处理也快.
不然就象自增ID一样,断号根本不用理它.
最后在update table set id=id+1 where id in(集合)
select id from table,把id取到dataset中,在用c#去分析哪些id要+1,再
update table set id=id+1 where id in(集合)
最后在insert
declare @YourTab table(id int)
insert @YourTab select 1
union all select 2
union all select 3
union all select 5
union all select 8
union all select 9
union all select 10declare @i intset @i=2 --@i是你要插入的id号
--主要是update 语句,先update后insert
update A set id=id+1 from @YourTab A where id=@i or (id>@i
and exists(select 1 from @YourTab where id=A.id-1 or A.id=1)
and not exists(select 1 from @YourTab where id>@i and id<A.id and (id+1 not in (select id from @YourTab) or id-1 not in (select id from @YourTab))))--你的insert语句:
insert @YourTab(id) values(@i)--查看结果:
select * from @YourTab order by id
你把update语句改成select 看看就知道每次被修改的记录了.你更改@i值,看看select 结果就知道了set @i=2 --@i是你要插入的id号select id from @YourTab A where id=@i or (id>@i
and exists(select 1 from @YourTab where id=A.id-1 or A.id=1)
and not exists(select 1 from @YourTab where id>@i and id<A.id and (id+1 not in (select id from @YourTab) or id-1 not in (select id from @YourTab))))