AddWithValue without DBType causing queries to run slowly

后端 未结 3 1133
眼角桃花
眼角桃花 2020-12-07 05:04

I\'ve been using cmd.Parameters.AddWithValue, and not specifying a DBType (int, varchar,...) to run queries. After looking at SQL Profiler, it seems that queries run with t

相关标签:
3条回答
  • 2020-12-07 05:24

    What is the SQL statement generated in both the cases?

    I am suspecting that it assumes the value as varchar when you don't explicitly specify it.

    e.g. SELECT OrderId FROM Orders WHERE OrderId = 1001
    vs SELECT OrderId FROM Orders WHERE OrderId = '1001'

    0 讨论(0)
  • 2020-12-07 05:32

    I just ran into this EXACT problem. I've got a legacy database with a lot of char columns. Without specifying the type of column the results took a couple of minutes on one of my queries. (It default to nvarchar.) Specifying the column type caused the results to take seconds.

    cmd.Parameters.AddWithValue("charcolumn", "stringvalue");
    cmd.Parameters[0].SqlDbType = SqlDbType.Char;
    

    I think I'm going to try having every string query as a char type and see how that goes.

    [edit]

    Actually... after reading this: http://www.u2u.info/Blogs/U2U/Lists/Posts/Post.aspx?ID=11

    I've decided to go with this solution:

    cmd.Parameters.AddWithValue(colName, val);
    if(val is string)
      cmd.Parameters[i].DbType = DbType.AnsiString;
    
    0 讨论(0)
  • 2020-12-07 05:39

    The problem is related to how SQL server does implicit type conversions. If you filter a VARCHAR column using an NVARCHAR value (ie. N'some text'), SQL has no choice but to convert the column to NVARCHAR as NVARCHAR cannot be implicitly converted back to VARCHAR.

    Your best workaround is either to specify the type or to change your database column to be NVARCHAR.

    0 讨论(0)
提交回复
热议问题