在SQL Server 2005中,将所有字符字段设置为nvarchar(MAX)而不是显式指定长度(例如nvarchar(255))有什么缺点吗?(除了不能在数据库级别限制字段长度之外)


当前回答

同样的问题也出现在MSDN论坛上:

Varchar(max) vs Varchar(255)

原文(更多信息):

When you store data to a VARCHAR(N) column, the values are physically stored in the same way. But when you store it to a VARCHAR(MAX) column, behind the screen the data is handled as a TEXT value. So there is some additional processing needed when dealing with a VARCHAR(MAX) value. (only if the size exceeds 8000) VARCHAR(MAX) or NVARCHAR(MAX) is considered as a 'large value type'. Large value types are usually stored 'out of row'. It means that the data row will have a pointer to another location where the 'large value' is stored...

其他回答

根据已接受的答案中提供的链接,似乎是:

存储在nvarchar(MAX)字段中的100个字符将与存储在nvarchar(100)字段中的100个字符没有区别-数据将内联存储,并且您不会有“行外”读取和写入数据的开销。所以不用担心。 如果大小大于4000,数据将自动“行外”存储,这是你想要的。所以也不用担心。

然而……

不能在nvarchar(MAX)列上创建索引。可以使用全文索引,但不能在列上创建索引以提高查询性能。对我来说,这就决定了……总是使用nvarchar(MAX)是一个明显的缺点。

结论:

如果你想要一种贯穿整个数据库的“通用字符串长度”,它可以被索引,并且不会浪费空间和访问时间,那么你可以使用nvarchar(4000)。

我有一个udf填充字符串,并把输出varchar(max)。如果直接使用它,而不是将其转换回正在调整的列的适当大小,则性能非常差。我最终将udf设置为一个任意长度的大音符,而不是依赖udf的所有调用者将字符串重新转换为较小的大小。

一个问题是,如果你必须使用多个版本的SQL Server, MAX并不总是有效的。因此,如果您正在使用遗留DB或涉及多个版本的任何其他情况,您最好非常小心。

同样的问题也出现在MSDN论坛上:

Varchar(max) vs Varchar(255)

原文(更多信息):

When you store data to a VARCHAR(N) column, the values are physically stored in the same way. But when you store it to a VARCHAR(MAX) column, behind the screen the data is handled as a TEXT value. So there is some additional processing needed when dealing with a VARCHAR(MAX) value. (only if the size exceeds 8000) VARCHAR(MAX) or NVARCHAR(MAX) is considered as a 'large value type'. Large value types are usually stored 'out of row'. It means that the data row will have a pointer to another location where the 'large value' is stored...

有时您希望数据类型对其中的数据强制执行一些意义。

例如,你有一列不应该超过20个字符。如果您将该列定义为VARCHAR(MAX),一些恶意应用程序可能会向其中插入一个长字符串,而您永远不会知道,或者没有任何方法来阻止它。

下次应用程序使用该字符串时,假设字符串的长度对于它所代表的领域来说是适度和合理的,那么您将体验到一个不可预测和令人困惑的结果。