【问题标题】:computed hashybtes column used as primary key计算的 hashbtes 列用作主键
【发布时间】:2013-10-08 01:21:45
【问题描述】:

我有可能是自然主键的长基因序列,但我正在寻找一种方法来找到自然键的更简洁的替代表示。不想使用代理键。不用担心性能,因为不会有很多join担心PK的效率问题。

这可能吗?

        create table foo(
           myvalue varchar(2000) not null,
           md5 as hashbytes('MD5',myvalue) PERSISTED   PRIMARY KEY  NOT NULL   -- bad syntax
         )

如果是这样,正确的语法是什么?以上不正确。

我还可以创建子表并设置 FK 关系吗?我没有发现文档中的限制部分明确说明了这一点:

          create table fooChild(
          id int primary key not null,
          md5 varbinary(16)
           )

         alter table fooChild add constraint FK_FOOCHILD_FOO
         foreign key(md5) references FOO(md5)

【问题讨论】:

    标签: tsql md5 calculated-columns


    【解决方案1】:

    这就是答案。 http://www.devx.com/tips/Tip/15397

    基本上,您必须确保函数不能返回 null,因此将 hashbytes 包装在 isnull 或 coalesce 中。

    【讨论】:

    • SQL Server 允许我以这种方式创建 PK。但是创建 FK 是个问题——Column 'FOO.md5' is not the same length or scale as referencing column 'fooChild.md5' in foreign key 'FK_FOOCHILD_FOO'. Columns participating in a foreign key relationship must be defined with the same length and scale. 看起来 PK 是 varbinary(8000)。
    • 这直接来自 MSDN,希望对您有所帮助。允许的输入值限制为 8000 字节。输出符合算法标准:MD2、MD4、MD5为128位(16字节); SHA 和 SHA1 为 160 位(20 字节); SHA2_256 为 256 位(32 字节),SHA2_512 为 512 位(64 字节)。
    • 只是一个想法,您可以尝试使用 CONVERT(VARBINARY(16),[formula here]) 包装您的主键公式,然后您的 FK 可能会起作用。
    猜你喜欢
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    相关资源
    最近更新 更多