t-sql:按'in'表达式确定的特定顺序更新

时间:2011-10-28 14:17:17

标签: sql sql-server sql-server-2008 tsql

假设:

declare @counter int
set @counter = 0

update MyTable
set @counter = MyField = @counter + 1
where Some_ID in (select ID from SomeTable)

我想要的是更新与返回select ID from SomeTable ID的顺序相同。有没有一个很好的方法来做到这一点?

2 个答案:

答案 0 :(得分:5)

以下是使用带有ROW_NUMBER的CTE的解决方案...您可以确定SomeTable OVER ROW_NUMBER子句中返回的记录的顺序。< / p>

;WITH rn (ID, rowNumber) AS
(
    SELECT st.ID, ROW_NUMBER() OVER (ORDER BY st.ID)
    FROM SomeTable st
    WHERE EXISTS (
        SELECT 1
        FROM MyTable mt
        WHERE mt.Some_ID = st.ID
    )   
)
UPDATE mt
SET MyField = rowNumber
FROM 
    MyTable mt 
    JOIN rn ON rn.ID = mt.Some_ID

答案 1 :(得分:2)

假设您希望在更新的记录中包含一个包含递增编号的列,我认为您可以这样做的唯一方法是获取ID列表并进行一些更新。

在SQL Server中,您可能会使用游标执行此操作。

DECLARE @id int, @counter int
SET @counter = 0
DECLARE ids CURSOR
  FOR SELECT ID FROM SomeTable

OPEN ids
FETCH NEXT FROM ids INTO @id

WHILE @@FETCH_STATUS == 0
BEGIN
  UPDATE MyTable SET MyField = @counter WHERE Some_ID = @id
  SET @counter = @counter + 1
  FETCH NEXT FROM ids INTO @id
END

CLOSE ids
DEALLOCATE ids