在现有表中多次插入,缺少标识列

时间:2017-11-22 16:30:15

标签: sql-server tsql sql-server-2012 sql-server-2008-r2 sql-insert

在SQL Server中,我试图在已存在的表中插入375行。

该表没有标识列,但ID列是唯一的,我想为每个375行输入唯一ID。我尝试了max(id)+1但是对于所有375行,它插入了相同的id并且数据搞砸了。我无法更改id列,因为表格有超过百万行。

代码如下:

declare @id int

set @id = select max(id) from tablename;

Insert into tablename (id, column 1, column 2, column 3, ..... column 20)
    select @id + 1, column1, column2, column 3, ........, column 20
    from tablename1
    where column15 IN (1,2,3,4,.........,375)

1 个答案:

答案 0 :(得分:0)

如何使用row_number

declare @id int

set @id = (select max(id) from tablename)

Insert into tablename (id, column 1, column 2, column 3, ..... column 20)

select
    row_number() over (order by (select null)) + @id,
    column1, 
    column2, 
    column 3, 
    ........, 
    column 20
from tablename1