The logic is correct, but it is a really bad way to do it. Wherever possible to you should avoid calling functions on your data, especially in the where clause, because it means that any indexes on the underlying columns can not be used.
Your predicate would be better written as:
WHERE peSubmitDate >= CAST(GETDATE() AS DATE)
AND peSubmitDate < DATEADD(DAY, 1, CAST(GETDATE() AS DATE));
This way indexes can be used, and your query is sargable
As it happens, converting DATETIME
to DATE
(and vice versa) is actually an exception to the rule of not using functions, so you can shorten this to:
WHERE CONVERT(DATE, peSubmitDate) = CONVERT(DATE, GETDATE())
Another point is that although it might look better to use OR
to accommodate both your options (of filtering by year or returning all records), you will find that having two separate queries will perform better. so your final SP might be:
ALTER PROC [dbo].[pr_Report] @YearOfRegistration INT
AS
BEGIN
IF (@YearOfRegistration = 0)
BEGIN
SELECT peCountryID,
peCountryName as coName,
ISNULL(SUM(CASE WHEN peIsSubmittedFL = 1 THEN 1 ELSE 0 END ),0) AS rdValue1,
ISNULL(SUM(CASE WHEN peIsSubmittedFL = 0 THEN 1 ELSE 0 END ),0) AS rdValue2,
COUNT(*) AS Total
FROM vPerson
WHERE CONVERT(DATE, peSubmitDate) = CONVERT(DATE, GETDATE())
GROUP BY peCountryofResidencyID,peCountryOfResidencyName
END
ELSE
BEGIN
SELECT peCountryID,
peCountryName as coName,
ISNULL(SUM(CASE WHEN peIsSubmittedFL = 1 THEN 1 ELSE 0 END ),0) AS rdValue1,
ISNULL(SUM(CASE WHEN peIsSubmittedFL = 0 THEN 1 ELSE 0 END ),0) AS rdValue2,
COUNT(*) AS Total
FROM vPerson
WHERE CONVERT(DATE, peSubmitDate) = CONVERT(DATE, GETDATE())
AND peYearOfRegistration = @YearOfRegistration
GROUP BY peCountryofResidencyID,peCountryOfResidencyName;
END
END