用增量值更新列

时间:2018-08-18 00:22:09

标签: sql sql-server

我目前有一个表,可以说它有约100行数据。其中一列“ UserName”目前在88行中为空。包含数据的12行如下所示:

User1
User2
User3
User4
User5
User6
etc

我想用User13,User14等填充88行中的其余行。如何更新这些行以使用递增的值?

2 个答案:

答案 0 :(得分:4)

我建议您更新CTE。这有点棘手,因为您需要继续编号,但是我认为这可行:

with toupdate as (
      select t.*,
             row_number() over (order by (select null)) as seqnum,
             max(convert(int, stuff(username, 1, 4, ''))) over () as maxnum
      from t
     )
update toupdate
    set username = 'User' + convert(varchar(255), seqnum + maxnum)
    where username is null;

如果不提醒您更新所有行,则可以使用:

with toupdate as (
      select t.*,
             row_number() over (order by case when username is not null then convert(int, stuff(username, 1, 4, '')) else 999999 end) as seqnum
      from t
     )
update toupdate
    set username = 'User' + convert(varchar(255), seqnum);

这应该保持现有的顺序,但是如果有差距,那就可以消除它们。

答案 1 :(得分:2)

会进行以下工作吗?

;WITH UserTable
AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY [user] DESC) as [row], 
           [UserName] as [user]
    FROM MyUserTable
) 
UPDATE u
SET 'User' + CAST(row AS varchar(10)) 
FROM UserTable u
WHERE u.[user] IS NULL