SQL 表中的列的类型不能用作索引中的键列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13137246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Column in table is of a type that is invalid for use as a key column in an index
提问by hitesh.gawhade
I have a table where I am storing employee details. I want to alter the table and set one of the column emp_code
as primary key. Its datatype is nvarchar(max)
, but I am not able to set it as primary key.
我有一张表,用于存储员工详细信息。我想更改表并将其中一列设置emp_code
为主键。它的数据类型是nvarchar(max)
,但我无法将其设置为主键。
I run the following query :
我运行以下查询:
ALTER TABLE user_master
ADD PRIMARY KEY (emp_code)
but it gives me an error :
但它给了我一个错误:
Msg 1919, Level 16, State 1, Line 1
Columnemp_code
in tableuser_master
is of a type that is invalid for use as a key column in an index.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
消息 1919,级别 16,状态 1,第 1 行表中的
列的类型不能用作索引中的键列。emp_code
user_master
消息 1750,级别 16,状态 0,行 1
无法创建约束。请参阅以前的错误。
How can I overcome this?
我怎样才能克服这个问题?
回答by ta.speot.is
An index's key cannot exceed a total size of 900 bytes. Change the data type to NVARCHAR(450)
. If that is not suitable, use a surrogate key (typically an IDENTITY
column).
索引的键不能超过 900 字节的总大小。将数据类型更改为NVARCHAR(450)
. 如果这不合适,请使用代理键(通常是一IDENTITY
列)。
回答by Paul Alan Taylor
You can't use varchar(max)
. It isn't designed to store primary keys.
你不能使用varchar(max)
. 它不是为存储主键而设计的。
Find out what the longest employee code, and create a sized nvarchar that covers your longest case.
找出最长的员工代码,并创建一个涵盖最长案例的大小的 nvarchar。
e.g. longest employee code is 70 characters, try:-
例如最长的员工代码是 70 个字符,请尝试:-
nvarchar(100)
...just to cover yourself.
……只是为了掩饰自己。
回答by dheeraj
Yes you are correct.Warning! The maximum key length is 900 bytes. The index PK__bookmark__2DFA2B0E164452B1
has maximum length of 2000 bytes. For some combination of large values, the insert/update operation will fail.
not use of varchar(max)
是的,你是对的。警告!最大密钥长度为 900 字节。索引的PK__bookmark__2DFA2B0E164452B1
最大长度为 2000 字节。对于某些大值组合,插入/更新操作将失败。不使用varchar(max)