[英]How does SqlParameter know the type
I was wondering how does SqlParameter
know the type when it is not specified? 我想知道当未指定
SqlParameter
时如何知道类型?
For example, when instantiating a parameter object you don't need to specify the DB Type. 例如,在实例化参数对象时,无需指定数据库类型。 Somehow when the command is executed .net handles this for you.
当执行命令时,.net会为您处理此问题。 Behind the scenes is there some sort of conversion taking place?
幕后是否发生某种转换? Is there a cost when you do / don't specify the type explicitly?
当您不明确指定类型时,是否需要付费?
Is there a cost when you do / don't specify the type explicitly?
当您不明确指定类型时,是否需要付费?
Yes, and the cost can be huge . 是的,代价可能是巨大的 。 It has nothing to do with client side cast, but everything with server side execution.
它与客户端强制转换无关,但与服务器端执行无关。 You should read Under the Table - How Data Access Code Affects Database Performance .
您应该阅读下表:数据访问代码如何影响数据库性能 。 Some problems that can occur are:
可能发生的一些问题是:
SqlCommand.Parameters.AddWithValue("@someparam", "somestring")
the resulted parameter is NVARCHAR
type. SqlCommand.Parameters.AddWithValue("@someparam", "somestring")
则结果参数为NVARCHAR
类型。 If your query has a clause WHERE somecolumn = @someparam
and somecolumn
is of type VARCHAR and indexed then the type mismatch will prevent the index use. WHERE somecolumn = @someparam
并且somecolumn
的类型为VARCHAR并已建立索引,则类型不匹配将阻止使用索引。 SqlCommand.Parameters.AddWithValue("@someparam", "somestring")
it will result in a query that has a parameter type NVARCHAR(10)
and when you use SqlCommand.Parameters.AddWithValue("@someparam", "anotherstring")
it will result in a query that has a parameter of type NVARCHAR(13)
and this will be considered a different query, and produce a different plan. SqlCommand.Parameters.AddWithValue("@someparam", "somestring")
,它将导致查询的参数类型为NVARCHAR(10)
并且当您使用SqlCommand.Parameters.AddWithValue("@someparam", "anotherstring")
将导致查询的参数类型为NVARCHAR(13)
,这将被视为不同的查询,并产生不同的计划。 In time you can pollute the server plan cache with hundreds of plans, one for each possible length of the parameter. There are possible problems with other types too, but strings are the most notorious culprits. 其他类型也可能存在问题,但是字符串是最臭名昭著的元凶。 Again, read the linked article, is highly relevant.
再次,阅读链接的文章,具有高度相关性。
The type is figured out based on the data type of the parameter value that is passed so the SqlParameter constructor. 根据传递的参数值的数据类型确定类型,以便使用SqlParameter构造函数。
You can find more info at this link Configuring Parameters and Parameter Data Types 您可以在此链接中找到更多信息。 配置参数和参数数据类型
Go to the "Specifying Parameter Data Types" section. 转到“指定参数数据类型”部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.