I want to speed up the following query
There are two conditions in the WHERE clause (see below query for reference)
Currently, it takes about 60 seconds. However
In case where @query is a parameter of a stored procedure, then the delay could be due to Parameter sniffing:
When a stored procedure is compiled or recompiled, the parameter values passed for that invocation are "sniffed" and used for cardinality estimation. The net effect is that the plan is optimized as if those specific parameter values were used as literals in the query.
The work-around used in this case is to declare a dummy local variable inside the stored procedure and assign this variable the contents of the parameter being sniffed, e.g.
CREATE PROCEDURE [dbo].[usp_MySproc](@Query nvarchar(255)
AS
BEGIN
-- Declare dummy variable
DECLARE @localQuery nvarchar(255)
-- Disable parameter sniffing
SET @localQuery = @Query
-- etc ...
END