代码之家  ›  专栏  ›  技术社区  ›  GateKiller

如何阻止13的倍数出现在标识列中

sql
  •  9
  • GateKiller  · 技术社区  · 16 年前

    假设我有下表:

    Create Table Comments (
        ID Int Identity(1,1) Not Null Primary Key Clustered,
        Comment Text Not Null
    )
    

    既然我迷信,我怎么才能阻止13的倍数出现在ID列中?

    非常感谢MySQL或MSSQL解决方案。

    5 回复  |  直到 16 年前
        1
  •  6
  •   Hi I am a troll Hi I am a troll    16 年前

    每次序列中出现13n-1时,创建一个触发器跳到下一个触发器

    布拉德,这是给你的。在不了解SQL Server的情况下,我将在Oracle中执行此操作。 This

    CREATE OR REPLACE TRIGGER trigname 
      AFTER INSERT ON Comments
      FOR EACH ROW 
      IF (:new.ID % 13 = 12) THEN
        -- increase the sequence
        SELECT comment_ID_sequence.NEXTVAL FROM dual;
      END IF;   
    END;
    

    如果不进行实际测试,这可能不起作用,但是通过少量的尝试和错误,您可以让它工作。Oracle的sequence对象根本不与表绑定,如果需要,您可以整天对sequence进行碰撞,而无需触摸表。我不知道SQL Server中是否存在这种情况。

        2
  •  4
  •   Alex Fort    16 年前

    编辑:前面的答案完全错了。

    您可以这样做:

    Identity(1, 13)
    

    由以下人员测试:

    for (int i = 1; i < 10000000; i += 13)
    {
        if (i % 13 == 0)
        {
            Console.WriteLine(i);
        }
    }
    

    从1开始递增13永远不会得到13的倍数,至少是1000万的倍数。

        3
  •  3
  •   Aaron Digulla    16 年前

    身份(79194966)

    这返回了32位整数内的432'436个唯一ID,没有一个是13的倍数。

    更多对:

    171040-产生2'064'889个值

    [编辑]要测试的小型python程序:

    import sys
    
    def x(start, step):
        count = 0
        i = start
        N = 1 << 31
        while i < N:
            #print i
            if i % 13 == 0:
                break
            i += step
            count += 1
        print i, i/13.0, count
    
    if __name__ == '__main__':
        x(int(sys.argv[1]), int(sys.argv[2]))
    

    我只是用了几个素数,但这并没有真正起作用;对于素数,我只能得到1-12个数字的序列。所以我从一对随机数开始,改变第二个数,直到脚本停止返回。

    我不知道这两个数的数学性质;)任何人

        4
  •  2
  •   mbillard    16 年前

    在插入时创建触发器。

    当插入13减1(12、25、38等)的倍数时,立即插入并删除另一行。

    CREATE TRIGGER ON [table_name]
    AFTER INSERT
    AS
        -- Get the last inserted identifier
        DECLARE @LastID INT -- or whatever type is your identity column
        SET @LastID = SELECT ID FROM inserted -- inserted holds the inserted entry
    
        -- Check if the ID is a multiple of thirteen minus 1
        IF ((@LastID + 1) % 13 = 0) -- not sure it would work, but something like that
        BEGIN
            INSERT INTO [table_name]
            -- dummy values
    
            DELETE FROM [table_name] WHERE ID = (@LastID + 1)
        END
    
    GO
    
        5
  •  0
  •   ctrlalt3nd    16 年前
    Create Table Comments (    
        ID Int Identity(2,2) Not Null Primary Key Clustered,    
        Comment Text Not Null
    )