A cross-platform database tool for data professionals using on-premises and cloud data platforms on Windows, macOS, and Linux.
It seems that the issue with your SQL code is related to how you are determining which records to delete from the FFF_GOLD_WH.Finance.GLStatisticsFact table. Currently, your code deletes records based on the fiscal date range defined by @mindate and @maxdate, which is calculated based on the current date and the fiscal months. If the fiscal month is not present in the silver_WH table, it should not trigger a deletion in the gold_WH table.
To prevent the deletion of fiscal month 11 when it is not present in the silver_WH table, you need to add a condition that checks for the existence of the fiscal month in the silver_WH table before executing the delete operation. Here’s a suggestion to modify your code:
DECLARE @maxdate date
DECLARE @mindate date
;WITH dd AS
(SELECT * FROM dbo.DateDim WHERE CAST(DateValue AS date) = CAST(GETDATE() AS date))
SELECT
@maxdate = [maxmonth],
@mindate = [minMonth]
FROM
(
SELECT
CAST(FiscalMonthNumber AS varchar(max)) + '/01/' + CAST(FiscalYear AS varchar(max)) AS [minMonth],
(SELECT CAST(FiscalMonthNumber AS varchar(max)) + '/01/' + CAST(FiscalYear AS varchar(max)) FROM dd) AS [maxmonth]
FROM dbo.DateDim
WHERE
CAST(DateValue AS date) = (SELECT DATEADD(MONTH, -3, DateValue) FROM dd)
) a
-- Check if fiscal months exist in silver_WH before deleting
IF EXISTS (SELECT 1 FROM silver_WH WHERE FiscalMonthNumber BETWEEN @mindate AND @maxdate)
BEGIN
DELETE FROM FFF_GOLD_WH.Finance.GLStatisticsFact
WHERE FiscalDate BETWEEN @mindate AND @maxdate
END
This modification includes an IF EXISTS check to ensure that the fiscal months you are about to delete from the gold_WH table exist in the silver_WH table. If they do not exist, the delete operation will not be executed, thus preserving the data for fiscal month 11.
Make sure to test this code in a safe environment before applying it to your production database to ensure it behaves as expected.