简体   繁体   中英

Difference between the both parameter assignment

actually I have a doubt, so please clear it. I have 2 line do the same work, see below

1. cmd.Parameters.AddWithValue("@UserName",objBELUserDetails.UserName);

2. cmd.Parameters.Add("@UserName",SqlDbType.Nvarchar,50).
                                      Value=objBELUserDetails.UserName;

Both lines work the same thing.

If you don't supply a size then the size defaults to the length of the string that is the parameter's value and If you omit the type then it looks at the type of the parameter value and uses a big case statement to map the object's type to the relevant Sql type. Obviously is helps the performance of your code if you supply the type yourself so that it doesn't have to work it out.

So don't you think that the second line of code would take more time than first and affect the performance of the code where as the first line have specific type and the size so that compiler don't take time to find out the type and size of the parameters. Isn't it ?

So don't you think that the second line of code would take more time than first and affect the performance of the code where as the first line have specific type and the size so that compiler don't take time to find out the type and size of the parameters. Isn't it ?

Firstly, I think you've got your "first" and "second" the wrong way round here. It's the second version which has a specific type and size.

Secondly, the performance isn't going to be significantly impacted at all if the implicit type is the same as the one you're specifying explicitly. You're making a database query - do you really think that finding the type of an object and the length of a string will be even measurable compared with the rest of the call, which almost certainly involves network activity? If the type is inferred incorrectly you may end up causing extra conversions elsewhere which can be avoided.

There's a much more important reason to specify the type and size of the parameter: it makes the information about the parameter explicit, and anyone can then check that it matches what the database expects. There are multiple types which a string can be converted to - and ditto with numbers. By stating the type explicitly, you're taking away any ambiguity.

command.Parameters.Add Without explicitly providing the type as in , it will try to implicitly convert the input to expected type.

And this implicit conversion may not optimal of conversions, so it may cause a performance hit.

check here : Parameters.AddWithValue vs. Parameters.Add

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM