【问题标题】:Why seed value not working fine?为什么种子价值不能正常工作?
【发布时间】:2014-01-06 05:10:08
【问题描述】:

我使用的是 SQL Server 2012,并且我有一个 bigint 类型的主键列。

有时在新插入时,新的主键需要 1000 或 10000 的巨大跳跃。

例如:

ID
--
1
2
3
4
5
6
7
8
9
10001
10002

为什么会这样?这是一个错误吗?

【问题讨论】:

    标签: sql sql-server-2012


    【解决方案1】:

    这是 SQL Server 2012 的行为。

    要解决此问题,您需要确保在序列创建/这样的属性中添加 NO CACHE 选项。

     create sequence Sequence1
        as int
        start with 1
        increment by 1
        no cache
    go
    create table Table1
        (
        id int primary key,
        col1 varchar(50)
        )
    go
    create trigger Trigger1
        on Table1
        instead of insert
    as
    insert  Table1
            (ID, col1)
    select  next value for Sequence1
    ,       col1
    from    inserted
    go
    insert Table1 (col1) values ('row1');
    insert Table1 (col1) values ('row2');
    insert Table1 (col1) values ('row3');
    
    select  * 
    from    Table1
    

    希望这会有所帮助..

    【讨论】:

    • 谢谢,真的很有帮助,将缓存参数设置为 NO CACHE 会在每次使用序列时将当前序列值写入系统表。这可能会通过增加磁盘访问来降低性能,但会减少意外间隙的机会。如果使用 NEXT VALUE FOR 或 sp_sequence_get_range 函数请求数字,仍然会出现差距,但这些数字要么未使用,要么用于未提交的事务。 more details
    猜你喜欢
    • 1970-01-01
    • 2016-07-16
    • 2019-01-04
    • 2020-09-03
    • 2016-10-10
    • 2016-10-24
    • 2017-02-27
    • 2017-07-08
    • 2014-11-23
    相关资源
    最近更新 更多