今天写了个复杂的sql语句,结果证明不符合项目要求,但是语法值得学习,记下来。
- declare @delId int --要删除的行
- declare @cid int
- set @delId='001002'
- begin transaction t1
- delete from ttest where 单位编号=@delId
- declare mycur cursor for select id from ttest where convert(int,单位编号)>convert(int,@delId)
- open mycur
- fetch next from mycur into @cid --类似datareader.Read(),向下移动
- WHILE (@@FETCH_STATUS = 0 ) --类似datareader.Read()
- BEGIN --在此处理逻辑
- update ttest set 单位编号='00'+convert(varchar(20),convert(int,单位编号)-1)where id=@cid
- fetch next from mycur into @cid --开始新一轮循环,少了这个则成死循环
- END
- close mycur
- deallocate mycur
- commit
我的数据表是:ttest
id int 单位编号 varchar(20)
2 001001
3 001002
4 001003
5 001004
6 001005
7 001006
我要实现的业务逻辑是:
如果删除某一行,比如001002
则更新编号大于001002的行,即编号减1
即保持编号整齐。
我没有考虑到的问题是,当我更新其他行的时候,其他行关联了很多表。
所以,删除的时候,不能更新其他行。
而是在增加的时候,找到被删除的最小的号,加进去。