The issue you're encountering with the `DATEADD` function is related to the behavior of quarter calculations in SQL Server. The `DATEADD` function with the 'q' or 'qq' parameter does not always return the exact quarter end date you expect.
In SQL Server, the 'q' parameter used with `DATEADD` calculates the number of quarters based on an integer input. However, it does not necessarily align the result with the end of the quarter. Instead, it adds the specified number of quarters to the given date.
To ensure that you get the exact quarter end date, you can use an alternative approach. One option is to use the `EOMONTH` function to find the end of the month and then adjust it to the end of the quarter.
Here's an example of how you can achieve this:
DECLARE @inputDate DATE = '1997-09-30';
-- Find the end of the month
DECLARE @endOfMonth DATE = EOMONTH(@inputDate);
-- Calculate the end of the quarter
DECLARE @endOfQuarter DATE = DATEADD(DAY, -1, DATEADD(MONTH, (MONTH(@endOfMonth) - 1) / 3 * 3 + 3, DATEFROMPARTS(YEAR(@endOfMonth), 1, 1)));
SELECT @endOfQuarter;
In this example, the `EOMONTH` function is used to find the end of the month for the given input date. Then, using the `DATEADD` function along with some calculations, the end of the quarter is determined by subtracting one day from the calculated quarter-end month.
Running the above code will yield the result you expect: '1997-12-31'.
By utilizing this alternative approach, you can reliably obtain the quarter end date in SQL Server.