I would like to create a stored procedure that allows you to delete old rows from tables. I have a Parameter table that contains the name of the table, the name of the database where the table is located, the schema name, PartDate (Day, Month, Year) and duration.
I want to test on the parameter table if one or more tables exist with different parameters. I delete the lines that are stored by more than 3 years for example
BEGIN
SET NOCOUNT ON;
Declare @SourceDatabase nvarchar(255)
Declare @SourceSchema nvarchar(255)
Declare @SourceTable nvarchar(255)
Declare @DatePart nvarchar(255)
Declare @Duration bit
Set @SourceDatabase = 'DATABASE'
Set @SourceSchema = 'dbo%'
Set @SourceTable = 'TEXT_OLD'
Set @DatePart = 'Day'
Set @Duration = -75
Declare @SQL NVARCHAR(MAX)
BEGIN TRY
--Delete the rows in the table
SELECT @SQL =N'IF EXISTS (SELECT * FROM CORE.[dbo].[HistoryPeriod]
WHERE SourceSchema = @SourceSchema
AND SourceTable = @SourceTable
--AND Duration = @Duration
-- AND DatePart= @DatePart
)
BEGIN
-- DELETE row of table
EXEC('
DELETE FROM [' + @SourceDatabase + '].[' + @SourceSchema + '].[' + @SourceTable + ']
WHERE TIMESTAMP < DATEADD([' + @DatePart+ '],[' + @Duration+ '],GETDATE())
')
'
EXEC sp_executesql @SQL
END
END
Could you help me please?