sql - 使用转换保留列引发非确定性错误

标签 sql sql-server sql-server-2016

使用 SQL Server 2016,我遇到了一些问题。

这是我的用例,它给我带来了问题......

create table dbo.Example (
    Id int identity (1, 1) not null,
    [Name] nvarchar(100) not null,
    Email nvarchar(255) not null,
    DOB datetime2(7) not null,
    RowHash as convert(nvarchar(66), hashbytes('SHA1', coalesce(
        convert(nvarchar(max), [Name]), 
        convert(nvarchar(max), Email), 
        convert(nvarchar(max), DOB)
    ))) persisted
    constraint [PK_Example] primary key clustered (Id asc)
);
drop table dbo.Example;

我收到的消息是:

Msg 4936, Level 16, State 1, Line 1 Computed column 'RowHash' in table 'Example' cannot be persisted because the column is non-deterministic.

当我将列设置为不保留时,数据类型被正确解释为 nvarchar(66),但我希望保留它。该问题似乎与 datetime2 列有关,但我的表上有多种数据类型。

因此,目标是使用持久的 hashbytes 列来保存表中所有值的哈希值。

有什么想法吗?

谢谢!

最佳答案

为什么是coalesce()而不是concat()

示例

create table dbo.Example (
    Id int identity (1, 1) not null,
    [Name] nvarchar(100) not null,
    Email nvarchar(255) not null,
    DOB datetime2(7) not null,
    RowHash as convert(nvarchar(66), hashbytes('SHA1', concat(
        [Name], 
        Email, 
        DOB
    ))) persisted
    constraint [PK_Example] primary key clustered (Id asc)
);

Select * from [dbo].[Example]
--drop table dbo.Example;

结果

enter image description here

关于sql - 使用转换保留列引发非确定性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51071903/

相关文章:

mysql - 指定mysql上最多两个值相等的字段

sql-server - IIS 10/SQL Server 2017/与经典 ASP 的连接速度非常慢

c# - 你会如何制作一个 "Favorite Pages"系统

r - SQL Server 2016 与 R 服务集成

sql-server - 将相关的逗号分隔字符串转换为具有多列的单独行

php - 如何在 while 循环内的 <li> 标记内创建一个自动递增的 ID?

mysql - 将日期保存到 MySql 时 SQL 语法错误

Mysql - 性能问题

sql - 如何获取SQL Server 2008 R2 服务包?

sql - 从表列名称和数据创建 json 键值