ADO.NET: Safe to specify -1 for SqlParameter.Size for all VarChar parameters?

后端 未结 1 708
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-28 16:18

We have an existing body of C# code that calls parameterized ad-hoc SQL Server queries in many places. We never specify SqlParameter.Size, and it\'s documented that in this

相关标签:
1条回答
  • 2020-12-28 16:51

    It is not ideal in that it is best to specify a parameter that matches the datatype of the column(s) involved.

    You would need to check your query plans to see if they still look reasonable.

    Trying the following test

    CREATE TABLE #T
    (
    X VARCHAR(10) PRIMARY KEY
    )
    
    
    DECLARE @A VARCHAR(MAX) = CAST('A' AS VARCHAR(MAX))
    
    SELECT *
    FROM #T 
    WHERE X = @A
    

    Gives a plan like

    Plan

    SQL Server adds a compute scalar to the plan which calls the internal function GetRangeWithMismatchedTypes and still manages to perform an index seek (more details on implicit conversions here).

    A counter example where it does matter is shown in the article Why Doesn’t Partition Elimination Work?. The behaviour described in that article also applies for a varchar(max) parameter against a table partitioned on a varchar(n) column.

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