带有GUID全零的MS SQL表

问题描述 投票:1回答:2

我继承了一个Web应用程序,其中一个后端MS SQL表有一个字段:

允许Nulls =否,DataType = uniqueidentifier,DefaultValue = newid(),Condensed Data = Type uniqueidentifier

在数千行中,有些行为GUID全部为零。它似乎不是遗留数据,因为有些人最近创建了日期。

当应用程序创建新记录时,SQL Server如何在该字段中放置正确的GUID?

编辑:此字段的EF上下文具有:

entity.Property(e => e.ThreadId).HasDefaultValueSql("newid()");
sql-server guid
2个回答
2
投票

uniqueidentifier数据类型并不意味着它将是唯一的。如果你生成NEWID()然后它生成唯一的id,但同样总是有可能生成相同的id。

为0

insert into t values ('00000000-0000-0000-0000-000000000000');
insert into t values ('00000000-0000-0000-0000-000000000000');
insert into t values (newid());

陈述是有效的。如果您的uid列不是主键或具有唯一索引,则可以将dublicate键添加到表中。


如果向表中添加检查约束,则可以限制并确定问题的根本原因

create table t (
  id uniqueidentifier unique
  CONSTRAINT CHK_uid CHECK (id != '00000000-0000-0000-0000-000000000000')
);
GO
insert into t values ('00000000-0000-0000-0000-000000000000');
insert into t values ('00000000-0000-0000-0000-000000000000');
insert into t values ('00000000-0000-0000-0000-000000000000');
insert into t values (newid());
GO
Msg 547 Level 16 State 0 Line 1
The INSERT statement conflicted with the CHECK constraint "CHK_uid". The conflict occurred in database "fiddle_80c5a5fe96ab4e73ac5dafbb2256025d", table "dbo.t", column 'id'.
Msg 547 Level 16 State 0 Line 2
The INSERT statement conflicted with the CHECK constraint "CHK_uid". The conflict occurred in database "fiddle_80c5a5fe96ab4e73ac5dafbb2256025d", table "dbo.t", column 'id'.
Msg 547 Level 16 State 0 Line 3
The INSERT statement conflicted with the CHECK constraint "CHK_uid". The conflict occurred in database "fiddle_80c5a5fe96ab4e73ac5dafbb2256025d", table "dbo.t", column 'id'.
Msg 3621 Level 0 State 0 Line 1
The statement has been terminated.
Msg 3621 Level 0 State 0 Line 2
The statement has been terminated.
Msg 3621 Level 0 State 0 Line 3
The statement has been terminated.
select * from t
GO
| id                                   |
| :----------------------------------- |
| ddeb79f6-dc0f-4c6a-a065-2083d39a78c1 |

db <>小提琴here


1
投票

如果SQL列可以为空,则问题出在C#代码中。确保POCO类也使用可以为空的Guid。还要确保在创建新实例时初始化属性。非可空Guid的C#默认值是一个全零Guid。如果问题仅存在于旧数据中,则代码可能已经修复。

© www.soinside.com 2019 - 2024. All rights reserved.