ker*_*vin 4 sql sql-server stored-procedures cursor
我正在使用SQL Server 2008中的存储过程来重置数据库表中的整数列.此整数列存储或保持项行的显示顺序.用户可以按特定的排序顺序拖放项目,我们使用此"订单排名整数"在数据库表中保留该顺序.
在检索数据时,对项目的显示查询始终附加"ORDER BY OrderRankInt",以便用户按照先前指定的顺序查看项目.
问题是这个整数列在表项重新排序后收集了大量重复值.因此...
Table
--------
Name | OrderRankInt
a | 1
b | 2
c | 3
d | 4
e | 5
f | 6
Run Code Online (Sandbox Code Playgroud)
经过用户的大量重新排序后......
Table
--------
Name | OrderRankInt
a | 1
b | 2
c | 2
d | 2
e | 2
f | 6
Run Code Online (Sandbox Code Playgroud)
这些重复主要是因为插入和用户指定的订单号.我们并没有试图阻止重复的订单排名,但我们想要一种方法在项目插入/修改上"修复"表格.
有没有办法可以使用单个UPDATE查询重置OrderRankInt列?或者我需要使用光标吗?该光标的语法是什么样的?
谢谢,凯文
编辑
使用Remus Rusanu解决方案进行更新.谢谢!!
CREATE PROCEDURE EPC_FixTableOrder
@sectionId int = 0
AS
BEGIN
-- "Common Table Expression" to append a 'Row Number' to the table
WITH tempTable AS
(
SELECT OrderRankInt, ROW_NUMBER() OVER (ORDER BY OrderRankInt) AS rn
FROM dbo.[Table]
WHERE sectionId = @sectionId -- Fix for a specified section
)
UPDATE tempTable
SET OrderRankInt = rn; -- Set the Order number to the row number via CTE
END
GO
Run Code Online (Sandbox Code Playgroud)
with cte as (
select OrderId, row_number() over (order by Name) as rn
from Table)
update cte
set OrderId = rn;
Run Code Online (Sandbox Code Playgroud)
这并不能解释任何外键关系,我希望你能得到这些关系.
| 归档时间: |
|
| 查看次数: |
1551 次 |
| 最近记录: |