【问题标题】:Multiple insert in already existing table with missing identity column在缺少标识列的现有表中多次插入
【发布时间】:2018-05-06 11:35:57
【问题描述】:

在 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)

【问题讨论】:

  • 创建SEQUENCE
  • 你能解释一下吗?
  • 你也许可以做这样的事情...select @id + ROW_NUMBER() Over (Partition By Column1 Order by Column1)
  • 超过一百万行的表并不意味着您不能更改该列,仅意味着更改该列可能需要一些(可能很多)时间。您不能使用每周维护窗口吗?创建一个序列也不是那么苛刻
  • 这里不需要序列@jean

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


【解决方案1】:

不如直接使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-20
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多