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


当前回答

一个缺点是,您将围绕一个不可预知的变量进行设计,您可能会忽略而不是利用内部SQL Server数据结构,逐步由Row(s)、Page(s)和Extent(s)组成。

这让我想到了C中的数据结构对齐,并且通常认为知道对齐是一件好事(TM)。相似的想法,不同的背景。

页面和区段的MSDN页面

行溢出数据的MSDN页面

其他回答

这将导致性能问题,尽管如果数据库较小,可能永远不会导致任何实际问题。每条记录将占用硬盘驱动器上更多的空间,如果您一次搜索大量记录,数据库将需要读取更多的磁盘扇区。例如,一个小的记录可以适合50个扇区,而一个大的记录可以适合5个扇区。如果使用大记录,则需要从磁盘读取10倍的数据。

起初我是这么想的,但后来又想了想。这样做会影响性能,但同样地,它也可以作为一种文档形式来了解字段的实际大小。当数据库位于更大的生态系统中时,它确实会强制执行。在我看来,关键是要在合理的范围内宽容。

ok, here's my feelings simply on the issue of business and data layer logic. It depends, if your DB is a shared resource between systems that share business logic then of course it seems a natural place to enforce such logic, but its not the BEST way to do it, the BEST way is to provide an API, this allows the interaction to be tested and keeps business logic where it belongs, it keeps systems decoupled, it keeps your tiers within a system decoupled. If however your database is supposed to be serving only one application, then lets get AGILE in thinking, what's true now? design for now. If and when such access is needed, provide an API to that data.

显然,这只是理想情况,如果您正在使用现有系统,那么您可能需要至少在短期内以不同的方式进行操作。

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

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

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

同样的问题也出现在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...

一个缺点是,您将围绕一个不可预知的变量进行设计,您可能会忽略而不是利用内部SQL Server数据结构,逐步由Row(s)、Page(s)和Extent(s)组成。

这让我想到了C中的数据结构对齐,并且通常认为知道对齐是一件好事(TM)。相似的想法,不同的背景。

页面和区段的MSDN页面

行溢出数据的MSDN页面