I have a query that runs against a pretty large table, I need to do a count on it.
If I use a literal the query runs in a few seconds but when I put the values in as variables (which I need to do) the query takes forever and presumably does a full table scan.
I've done quite a lot of reading about this and I understand it most likely to do with parameter sniffing, which I can't pretend that I understand it, I just want to know how I can fix it, otherwise, I'm going to have to fall back on calling it in c# with generated query strings.
This query runs in a few seconds..
SELECT Count(Id) FROM dbo.BeaconScan WHERE State = 'Archived' AND LastSeen < '29 February 2020';
This one takes forever
DECLARE @Date DATE = '31 March 2020'
DECLARE @Status NVARCHAR(256) = 'Archived'
SELECT Count(Id) FROM dbo.BeaconScan WHERE State = @Status AND LastSeen < @Date;