我有一个简化的表格,如下所示:
group index value
1 1 text 1
1 2 text 2
1 3 text 3
2 1 text 4
2 2 text 5
2 3 text 6
Group 是一个外键,也用于对表中的项目进行分组。
索引是用于对组内的项目进行排序的内部索引。
文本只是一个值。
然后,如果我执行插入或运行存储过程来执行插入
INSERT INTO Table VALUES (1, 2, 'new text')
我想更新第 1 组项目的索引,使表格如下所示:
group index value
1 1 text 1
1 2 new text (inserted)
1 3 text 2 (index updated)
1 4 text 3 (index updated)
2 1 text 4
2 2 text 5
2 3 text 6
(在 MS SQL-Server 2008 上运行)
最佳答案
这是一个您可以使用的存储过程。采用 3 个参数:grp、idx 和值:
CREATE PROCEDURE ReIndex
@grp int,
@idx int,
@value nvarchar(30)
AS
IF NOT EXISTS(SELECT 1 FROM [tbl] WHERE grp = @grp and idx =@idx)
INSERT INTO tbl VALUES (@grp, @idx, @value)
else
update tbl
set idx = idx+1
where
grp =@grp and
idx >= @idx
INSERT INTO tbl VALUES (@grp, @idx, @value)
用法:
exec reindex 1, 2, 'new text'
sqlfiddle:http://sqlfiddle.com/#!3/3323d/11
关于sql - SQL 插入时更新子索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34465624/