我观看了 YouTube 视频教程,教如何创建唯一的 key
http://www.youtube.com/watch?v=oqrsfatxTYE&list=PL08903FB7ACA1C2FB&index=9
在视频中,他为电子邮件(nvarchar)列创建了一个唯一键,我可以在手动创建数据库时创建它,但是当我尝试为首先使用实体框架代码创建的数据库创建唯一键时,使用下一个查询
ALTER TABLE Peoples
ADD CONSTRAINT UQ_MyTable_Email UNIQUE (email)
它将生成一个错误:
Msg 1919, Level 16, State 1, Line 2
Column 'email' in table 'Peoples' is of a type that is invalid for use as a key column in an index.
有什么问题吗?我可以做什么来为 nvarchar(max) 列创建唯一键?
最佳答案
说如果你创建这个表
CREATE TABLE ConstTable
(ID INT,
Email VARCHAR(1000)
CONSTRAINT uc_Email UNIQUE (Email)
)
GO
您将收到警告:
Warning! The maximum key length is 900 bytes. The index 'uc_Email' has maximum length of 1000 bytes. For some combination of large values, the insert/update operation will fail
要定义唯一约束的列应小于或等于 900 字节,因此您可以使用 VARCHAR(900)
或 NVARCHAR(450)
列(如果您希望能够在该列上创建唯一约束)
上面使用 VARCHAR(450) 的同一个表在没有任何警告的情况下创建
CREATE TABLE ConstTable
(ID INT,
Email VARCHAR(900)
CONSTRAINT uc_Email UNIQUE (Email)
)
GO
结果
Command(s) completed successfully.
测试您的表
说这是你的 table
CREATE TABLE ConstTable
(ID INT,
Email VARCHAR(MAX)
)
GO
现在尝试在 VARCHAR(MAX) 数据类型上创建任何索引,您将得到相同的错误。
CREATE INDEX ix_SomeIdex
ON ConstTable (Email)
错误消息
Msg 1919, Level 16, State 1, Line 1 Column 'Email' in table 'ConstTable' is of a type that is invalid for use as a key column in an index.
关于sql - 如何为 Entity Framework 数据库的 varchar 列创建唯一键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20752849/