The Problem you are experiencing is (almost certainly) due to a cached query plan, which is appropriate for some version of parameters passed to the query, but not for others (aka Parameter Sniffing).
This is a common occurance, and is often made worse by out of date statistics and/or badly fragmented indexes.
First step: ensure you have rebuilt all your indexes and that statistics on non-indexed columns are up to date. (Also, make sure your client has a regularly scheduled index maintenance job)
exec sp_msforeachtable "DBCC DBREINDEX('?')"
go
exec sp_msforeachtable "UPDATE STATISTICS ? WITH FULLSCAN, COLUMNS"
go
This is the canonical reference: Slow in the Application, Fast in SSMS?
If the problem still exists after rebuilding indexes and updating statistics, then you have a few options:
-
Use dynamic SQL (but read this first: The Curse and Blessings of
Dynamic SQL) -
Use
OPTIMIZE FOR
-
Use
WITH(RECOMPILE)