We have a stored procedure that executes dynamic sql via sp_executesql
.
We have observed via the SQL Server profiler and looking at the execution plans the profiler shows that when this procedure is called via SSMS (SQL Server Management Studio) it uses a good combination of indexes, therefore returning in 2 secs.
On the other hand, when we call this procedure via our .NET application (called via Entity Framework) - and exactly the same parameters are used compared to the call in SSMS - then SQL Server uses a much worse choice for the indexes.
And this behaviour is deterministic. Called via our app - bad index. Called via SSMS - good index.
Does anybody have an idea why this could be the case?
Many thanks.
Update:
The stored procedure call looks like this:
EXEC [schema].[sp] @a=123,@b=NULL
The dynamic SQL inside the procedure is executed like this:
`EXEC sp_executesql
@sql,
N'@a int, @b smallint',
@a = @a,
@b = @b`