When should “SqlDbType” and “size” be used when adding SqlCommand Parameters?

ぃ、小莉子 提交于 2019-11-26 08:48:19
marc_s

In my experience, I would make sure I do these things:

  • make sure it's you that defines the data type for the parameter. ADO.NET does a decent job at guessing, but in some cases, it can be terribly off - so I would avoid this method:

    cmd.Parameters.Add("@Name").Value = "Bob";
    cmd.Parameters.AddWithValue("@Name", "Bob");
    

    Letting ADO.NET guess the type of the parameter by the value passed is tricky, and if it's off for any reason, those are really tricky bugs to track and find! Imagine what happens when you pass in a DBNull.Value - what datatype should ADO.NET pick for that?

    Just be explicit - say what type it is you want!

  • if you're using string parameters, make sure to explicitly define the length - so I would avoid this method, too:

    cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = "Bob";
    

    If you don't provide a length, ADO.NET might default to some arbitrary value, or the length of the string passed in as a value, or something else - you're never quite sure. And if your length doesn't match what the stored proc really expects, you might see conversion and other unpleasant surprises. So if you define a string, define its length, too!

So in your case, the only approach that really works for me is this one here:

cmd.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = "Bob";

because it a) defines the data type to use explicitly, and b) defines the length of the string explicitly.

StefanE

By adding the type, your requests are more likely to improve performance by using cached query plan.

Here's a quote from MSDN:

Parameterized commands can also improve query execution performance, because they help the database server accurately match the incoming command with a proper cached query plan.

More to read in Execution Plan Caching and Reuse.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!