如何在SQL Server 2012中添加行号列

我正在尝试向现有表添加一个新列,其中值是行号/排名.我需要一种方法生成行号/秩值,我还需要限制受影响的行 – 在这种情况下,字符串中存在子字符串.

现在我有

UPDATE table
SET row_id=ROW_NUMBER() OVER (ORDER BY col1 desc) FROM table
WHERE CHARINDEX('2009',col2) > 0

我得到这个错误

Windowed functions can only appear in the SELECT or ORDER BY clauses.

(RANK()的相同错误)

有没有办法用ROW_NUMBER()函数创建/更新列? FYI,这意味着取代不正确的已经存在的“等级”列.

解决方法

你可以用CTE这样做:
with cte as
(
  select *,new_row_id=ROW_NUMBER() OVER (ORDER BY col1 desc)
  from MyTable
  where charindex('2009',col2) > 0
)
update cte
set row_id = new_row_id

SQL Fiddle with demo.

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...