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


当前回答

把它当做另一个安全等级。您可以设计没有外键关系的表(完全有效),并确保完全在业务层上存在关联实体。然而,外键被认为是很好的设计实践,因为它们增加了另一个约束级别,以防业务层出现问题。同样,字段大小限制和不使用varchar MAX。

其他回答

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

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

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

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.

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

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

这将使屏幕设计变得更加困难,因为你将不再能够预测你的控制应该有多宽。