我有一个更新某些行的SP,我想更新我在其中的位置选择的SortOrder列 - 这是我的代码的一部分:
UPDATE StagingCategoryItems
SET IsDeleted = 0,
ModifiedOn = GETDATE(),
ModifiedBy = 'DragDropSP'
WHERE ItemID IN (
SELECT ItemID
FROM StagingCategoryItems
WHERE ManufacturerID=@ManufacturerID
AND CategoryID=@CategoryID
AND ItemID IN
(
SELECT items
FROM dbo.Split(@InIds,',')
)
AND IsDeleted=1
)
AND ManufacturerID=@ManufacturerID AND CategoryID=@CategoryID
所以我想添加一个:
SortOrder = POSITION_IN_SELECT_RESULT
我将如何做到这一点?
答案 0 :(得分:2)
如果您正在讨论@InIds
中的输入顺序,则可能需要更改功能以在输出中包含排名。假设一个数字表:
SET NOCOUNT ON;
DECLARE @UpperLimit INT;
SET @UpperLimit = 200000;
;WITH n AS
(
SELECT rn = ROW_NUMBER() OVER (ORDER BY s1.[object_id])
FROM sys.objects AS s1
CROSS JOIN sys.objects AS s2
CROSS JOIN sys.objects AS s3
)
SELECT [Number] = rn - 1 INTO dbo.Numbers
FROM n WHERE rn <= @UpperLimit + 1;
CREATE UNIQUE CLUSTERED INDEX n ON dbo.Numbers([Number]);
您可以创建如下函数:
CREATE FUNCTION dbo.Split
(
@List VARCHAR(MAX),
@Delimiter VARCHAR(10)
)
RETURNS TABLE
AS
RETURN
(
SELECT
[Position] = ROW_NUMBER() OVER (ORDER BY [Number]),
[Value] = CONVERT(INT,
SUBSTRING(@List, [Number],
CHARINDEX
(
@Delimiter, @List + @Delimiter, [Number]
) - [Number]))
FROM dbo.Numbers
WHERE Number <= LEN(@List)
AND SUBSTRING
(
@Delimiter + @List, [Number], LEN(@Delimiter)
) = @Delimiter
);
GO
所以现在你的UPDATE
看起来像这样:
UPDATE i SET
[Order] = f.[Position],
IsDeleted = 0,
ModifiedOn = GETDATE(),
ModifiedBy = 'DragDropSP'
FROM dbo.StagingCategoryItems AS i
INNER JOIN dbo.Split(@InIds, ',') AS f
ON i.ItemID = f.[Value]
WHERE IsDeleted = 1
AND ManufacturerID = @ManufacturerID
AND CategoryID = @CategoryID;
(我也删除了对同一张桌子的冗余支票。)