【问题标题】:SQL need to insert into table which only consists of a primary key but no auto incrementSQL 需要插入到只包含主键但没有自增的表中
【发布时间】:2016-11-29 02:30:52
【问题描述】:

我需要在一个只包含一列的表中插入一个值,即primary key

此外,NULL 是不允许的,Identity 设置为 FALSEIdentity SeedIdentity Increment 都设置为 0

我尝试使用INSERT INTO table(id) VALUES (null) 插入,这显然不起作用。 INSERT INTO table(id) default values 也不起作用。

如何使用正确递增的 ID 填充此列?

【问题讨论】:

  • 没有配置身份,什么定义了“正确递增的 ID”?
  • 由谁递增?如果Identity 为假并且没有设置值的默认值,则您的代码必须提供一个值
  • 不太明白,要不要身份?
  • 表格由递增的数字组成。不知道为什么increment被设置为0

标签: sql-server sql-server-2012 insert


【解决方案1】:

实现标识或序列将是最好的解决方案,但如果您确实无法更改架构,则替代方法是在事务中锁定表,创建新值,解锁表。请注意,这可能会对性能产生影响。

create table dbo.ids ( id int primary key clustered );
GO

insert dbo.ids values  ( 1 ), ( 2 ), ( 3 ), ( 4 ) ;
GO

declare @newid int;

begin transaction

    set @newid = ( select top( 1 ) id from dbo.ids with ( tablockx, holdlock ) order by id desc ) + 1 ;

    insert into dbo.ids values ( @newid );

    select @newid;

commit

GO 20

【讨论】:

    【解决方案2】:

    您可以在该插入中使用 while 函数

    declare @id int    
    select @id = max(id) from table    
    
    while @id <= (... put here max nuber of your id you want to insert)  
    begin
        insert into table values (@id) 
        set @id = @id+1 end
    end
    

    【讨论】:

    • 这仅对单个客户端连接是安全的。想象一下来自不同连接的多个插入 - max(id) 不再可靠。
    • 如果我们不能更改表并将 id 列定义为 idedntity,那么合理的做法是创建具有标识列的第二个表并在基表上触发,该表将从新表中获取下一个已插入的标识?跨度>
    【解决方案3】:

    这也可以是一个解决方案。

    declare @newid integer
    
    begin tran 
    
    select @newid = isnull(max(id), 0) + 1 from table with (xlock,holdlock)
    insert into table values(@newid)
    select @newid
    
    commit tran
    

    【讨论】:

      猜你喜欢
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 2019-01-09
      • 2012-02-22
      相关资源
      最近更新 更多