I have c# web application that submits a query to sql server. The query has three parameters, two are ints and one is nchar. I’m getting a different query plan for each length of the nchar parameter. Is there a way to only get one plan?
Some more details:
The query is fairly large and complex, so I won’t inlcude it all here. However, there WHERE part is
WHERE gp.Control=@Control AND r.RegionType=@RegionType
r.RegionType is a column in a table defined as nchar(10). My c# code, sets the parameter with the following:
cmd.Parameters.Add(parmRegionType, System.Data.SqlDbType.NChar).Value = rgn.Key;
where rgn.key may have one of the following four values: “All”, “County”, “DGP”, or “State”.
When I dump the query plan with
SELECT usecounts, cacheobjtype, objtype, text, query_plan
FROM sys.dm_exec_cached_plans
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_query_plan(plan_handle)
WHERE text LIKE '%(@RegionType nchar(%),@CacheCnt int,@Control int)%'
AND text NOT LIKE '%this query%'
I get the following results (edited format and truncated text)
usecounts cacheobjtype objtype text query_plan
--------- ------------- -------- -----------------------------------------------
1 Compiled Plan Prepared (@RegionType nchar(5),@CacheCnt int,@Control...
1 Compiled Plan Prepared (@RegionType nchar(6),@CacheCnt int,@Control...
2 Compiled Plan Prepared (@RegionType nchar(3),@CacheCnt int,@Control...
(3 row(s) affected)
So you can see that there is a query plan for when @RegionType is three characters long (“All” and “DGP”), five characters long (“State”) and six characters long (“County”).
Is there a way to code this so that only one query plan is prepared independent of the length of the @RegionType parameter?
Use
NVarCharand set the length to the maximum expected possible value (e.g. whatever the max length of theRegionTypecolumn is).Looks like
6in your case as that is the length ofCounty