我正在尝试使用存储过程更新某些列值:
CREATE PROCEDURE [dbo].[UpdataObjectivesPosition]
@idGoal int
AS
BEGIN
SET NOCOUNT ON;
DECLARE @count int
SET @count = 1
WHILE exists (SELECT * From Objective Where IDgoal = @idGoal)
Begin
Update [Tasks] Set Position=@count
SET @count = @count + 1
End
END
GO
但我得到一个无限循环,我认为它是因为while表达。 那么如何正确创建此过程呢?请帮帮我
示例:
tskA - 4
tskB - 5
tskc - 7
我希望程序将位置设置为1,2,3,.......
答案 0 :(得分:1)
您根本不需要循环来实现您想要的效果,您可以使用ROW_NUMBER()函数执行此操作:
WITH CTE AS
( SELECT *, rn = ROW_NUMBER() OVER(ORDER BY Name)
FROM Tasks
)
UPDATE CTE
SET Position = rn;
<强> Example on SQL Fiddle 强>
答案 1 :(得分:0)
这是我最近发现的SQL Server解决方案。
DECLARE @Count INT = (
SELECT ISNULL(MAX([Position]),0)
FROM [Objective]
)
UPDATE [Objective]
SET @Count = [Position] = @Count + 1
WHERE [Position] IS NULL
它使用双重赋值(SET @a = @b = @a + 1
)。