生成独特的价值观

时间:2010-11-15 10:16:27

标签: sql sql-server tsql

表格中有一列“钥匙”。使用像这样的数据

Key    Name
1      aaa
2      sads
null   asd
null   asd

现在我需要用3和4替换空值。我该怎么做。

2 个答案:

答案 0 :(得分:2)

根据您使用的SQL Server版本,您可以使用TOP或SET ROWCOUNT将UPDATE限制为单行。这样的事情会起作用:

select top 1 * from sysobjects
WHILE @@ROWCOUNT > 0
BEGIN
    UPDATE TOP 1 Keys SET Key = (SELECT MAX(Key) from Keys)+1 WHERE Key is null
END

但并不理想。我想不出另一种解决重复行的方法 - 除非这是一次性任务,在这种情况下临时添加IDENTITY列会起作用。

答案 1 :(得分:0)

如果您可以将数据(临时)放入单独的表中,则可以使用ROW_COUNT():

declare @Keys table ([Key] int not null, [Name] varchar(50) null);

insert into @Keys ([Key], [Name])
select [Key], [Name]
from   [Keys]
where  [Key] is not null
union all
select [Key] = row_number() over (order by [Name]) + 
               (select max([Key]) from [Keys]),
       [Name]
from   [Keys]
where  [Key] is null;

truncate table [Keys];
insert into [Keys] select * from @Keys;
相关问题