为什么要费心设置命令对象参数的大小参数?
我们的数据访问层使用命令对象与sql server 进行通信。
在大多数情况下,我已将字段大小(与 sql server 中的列大小匹配)硬编码到命令参数生成器中。
例如:
SqlParameter param = new SqlParameter("@name", NVarChar, 4000);
与仅将其保留为 0 相比,在此处指定一个值(本例中为 4000)有什么优势?当列大小发生变化时必须重新编译,这很痛苦。
Our data access layer uses command objects to communicate with sql server.
In most cases I've hard-coded the field size (that matches the column size in sql server) into the command param builder.
Such as:
SqlParameter param = new SqlParameter("@name", NVarChar, 4000);
What's the advantage to specifying a value here (4000 in this example) versus just leaving it as 0? It's a pain when you have to recompile when a column size changes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
其实是相当重要的。使用不同参数长度发出的相同请求最终会在过程缓存中作为不同查询。随着时间的推移,这会导致缓存污染和过度活跃的编译事件。此问题是 Linq2SQL 和 EF 提供程序的实现方式中的主要设计缺陷之一,例如。请参阅数据访问代码如何影响数据库性能。另请参阅 未正确指定相关问题的参数长度时的查询性能和计划缓存问题。
Is actually quite important. Identical requests issued with different parameter length end up as different queries in the procedure cache. In time, this leads to cache pollution an over-active compilation events. This issue is one of the major design flaws in how both Linq2SQL and the EF providers were implemented, eg. see How Data Access Code Affects Database Performance. Also see Query performance and plan cache issues when parameter length not specified correctly for a related problem.
没有性能或执行时间优势 - 如果未显式传递,则会推断大小:
我想您可能会说,通过显式声明参数的大小以匹配 SQL Server 中字段的大小,您可以更好地告知代码的读者有关数据模型的限制。这有多有用,仁者见仁智者见智。
There is no performance or execution-time advantage - size is inferred if it is not explicitly passed:
I guess you could say that by explicitly declaring the size of the parameter to match the size of the field in SQL Server you are better informing readers of your code as to the limits of the data model. How useful that may be is in the eye of the beholder.
如果您指定的大小与 SQL 列的宽度相匹配,那么您可能还有另一个层来检测和/或防止数据丢失。 (当用户输入或应用程序生成的字符多于数据库中可以存储的字符时会发生什么?)
也许问题与所有这些 Microsoft 缓冲区溢出有关?
If you specify a size that matches the width of the SQL column, then presumably you have another layer that detects and/or prevents data loss. (What happens when a user enters or an application generates more characters than can be stored in the database?)
Perhaps the problem is related to all those Microsoft Buffer Overflows?