door #1
You can slap an OPTION(RECOMPILE)
hint on the end of your query. The downside here is that SQL Server will have to compile a plan for it each time, and you won't have much of a trail in the plan cache (which isn't as big of a deal if you have Query Store enabled).
The upside is that every time this runs, the optimizer will effectively execute your query with the literal values replacing parameter or variable placeholders. This will allow for seeks when indexes are suitable.
door #2
You can use parameterized dynamic SQL to generate a where clause for any non-NULL parameters. Here's a loose example based on the limited information you've provided.
DECLARE
@s nvarchar(MAX) = N'',
@parameters nvarchar(MAX) = N'@PlatformId integer, @platformPayeeId integer, @Gcid integer';
SELECT
@s += N'
SELECT
columns
/*Put the name of your stored procedure in a comment so people know where it comes from*/
FROM dbo.YourTable AS p
JOIN dbo.YourOtherTable AS pba
ON p.Id = pba.Id
JOIN dbo.YourOtherOtherTable AS a
ON p.Id = a.Id
WHERE p.PayeeStsId = 1
AND pba.PayeeBankStsId = 1';
IF @PlatformId IS NOT NULL
BEGIN
SELECT
@s += N'
AND p.PlatformId = @PlatformId'
END;
IF @platformPayeeId IS NOT NULL
BEGIN
SELECT
@s += N'
AND p.PlatformPayeeId = @platformPayeeId'
END;
IF @Gcid IS NOT NULL
BEGIN
SELECT
@s += N'
AND a.Gcid = @Gcid'
END;
EXEC sys.sp_executesql
@s,
@parameters,
@PlatformId,
@platformPayeeId,
@Gcid;
You'll need to adapt it to your specific situation, of course, but this should get you going in the right direction.
ISNULL()
is your root problem?...show the full query and actual execution plan when you have a performance question. The only thing that can be advised otherwise is just re-write your query to not useISNULL()
with a series ofOR
s orUNION ALL
s for each case yourISNULL()
code currently covers.WHERE (p.PlatformId = @PlatformId OR @PlatformId IS NULL) AND p.PayeeStsId = 1 AND (p.PlatformPayeeId = @platformPayeeId OR @platformPayeeId IS NULL) AND pba.PayeeBankStsId=1 AND (a.Gcid = @Gcid OR @Gcid IS NULL) OPTION (RECOMPILE)
. This will facilitate a sargable expression and eliminate the predicate entirely when the parameter isNULL
.