SQL Stored procedure to delete multiple tables data from the database older than 1 years. Deletion should be performed in specified month after every 1 year
Loading
SQL Stored procedure to delete multiple tables data from the database older than 1 years. Deletion should be performed in specified month after every 1 year
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Naimish MakwanaRank #324 · 7.7K reputationPosted Jun 2, 2023, 2:48 AM EDT
Try below code:
CREATE PROCEDURE DeleteOldData AS BEGIN -- Variables DECLARE @DeletionDate DATE; -- Set the deletion date to the specified month after every 1 year SET @DeletionDate = DATEADD(YEAR, -1, DATEADD(MONTH, 6, GETDATE())); -- Change the month value (6) to the desired month -- Delete data from Table1 DELETE FROM Table1 WHERE DateColumn < @DeletionDate; -- Delete data from Table2 DELETE FROM Table2 WHERE DateColumn < @DeletionDate; -- Delete data from Table3 DELETE FROM Table3 WHERE DateColumn < @DeletionDate; -- Repeat the delete statements for additional tables -- Commit the transaction COMMIT; ENDThanks
Brahma Prakash ShuklaRank #633 · 3.8K reputationPosted Jun 2, 2023, 8:18 AM EDT
CREATE PROCEDURE DeleteOldData AS BEGIN -- Set the specified month and year for deletion DECLARE @deletionMonth INT = 6; -- June DECLARE @deletionYear INT = YEAR(GETDATE()) - 1; -- One year ago -- Disable foreign key checks SET FOREIGN_KEY_CHECKS = 0; -- Start the deletion process BEGIN TRANSACTION; -- Delete data from the first table DELETE FROM table1 WHERE YEAR(date_column) < @deletionYear OR (YEAR(date_column) = @deletionYear AND MONTH(date_column) <= @deletionMonth); -- Delete data from the second table DELETE FROM table2 WHERE YEAR(date_column) < @deletionYear OR (YEAR(date_column) = @deletionYear AND MONTH(date_column) <= @deletionMonth); -- Delete data from the third table DELETE FROM table3 WHERE YEAR(date_column) < @deletionYear OR (YEAR(date_column) = @deletionYear AND MONTH(date_column) <= @deletionMonth); -- ... repeat the DELETE statement for other tables ... -- Enable foreign key checks SET FOREIGN_KEY_CHECKS = 1; -- Commit the transaction and make the changes permanent COMMIT; END;Prasad RaveendranRank #320 · 7.8K reputationPosted Jun 2, 2023, 3:43 PM EDT
The deletion process can be done in batches using a WHILE loop. Here's how it works:
By deleting data in batches, you can manage the impact on system resources and reduce the likelihood of long-running transactions or excessive log growth. Adjust the @BatchSize value based on performance testing and system capacity to find the optimal balance between deletion speed and resource usage.
CREATE PROCEDURE DeleteOldDataInBatches AS BEGIN DECLARE @BatchSize INT = 10000; -- Number of records to delete in each batch DECLARE @CurrentDate DATETIME; DECLARE @DeletionMonth INT; DECLARE @DeletionYear INT; DECLARE @DeletionDate DATETIME; DECLARE @RowCount INT; -- Set the current date SET @CurrentDate = GETDATE(); -- Set the month for deletion SET @DeletionMonth = 2; -- Specify the month for deletion (e.g., February) -- Calculate the deletion year SET @DeletionYear = YEAR(DATEADD(YEAR, -1, @CurrentDate)); -- Create the deletion date using the deletion month and year SET @DeletionDate = DATEFROMPARTS(@DeletionYear, @DeletionMonth, 1); -- Delete data from the tables older than 1 year in batches BEGIN TRY BEGIN TRANSACTION; -- Delete data from Table1 SET @RowCount = 1; WHILE @RowCount > 0 BEGIN DELETE TOP (@BatchSize) FROM Table1 WHERE CreatedDate 0 BEGIN DELETE TOP (@BatchSize) FROM Table2 WHERE CreatedDate 0 BEGIN DELETE TOP (@BatchSize) FROM Table3 WHERE CreatedDate 0 ROLLBACK; -- Throw the error message THROW; END CATCH ENDAmit MohantyRank #112 · 20K reputationPosted Jun 5, 2023, 2:36 AM EDT
CREATE PROCEDURE usp_DeleteOldRecords() BEGIN DECLARE @CutoffDate DATETIME; SET @CutoffDate = DATEADD(YEAR, -1, GETDATE()); BEGIN TRY BEGIN TRAN -- Delete data from Tables DELETE FROM Table1 WHERE CreatedDate < @CutoffDate; DELETE FROM Table2 WHERE CreatedDate < @CutoffDate; DELETE FROM Table3 WHERE CreatedDate < @CutoffDate; COMMIT TRAN END TRY BEGIN CATCH -- An error occurred, rollback the transaction ROLLBACK; END CATCH; END;To run a stored procedure in a specified month after every 1 year, you can use a combination of SQL Server Agent and a scheduled job.
Open SQL Server Management Studio and connect to your SQL Server instance.
Expand the "SQL Server Agent" folder in the Object Explorer.
Right-click on the "Jobs" folder and select "New Job". This will open the New Job dialog box.
In the "General" tab of the New Job dialog box, provide a name for the job in the "Name" field.
In the "Steps" tab, click on the "New" button to create a new step for the job. This will open the New Job Step dialog box.
In the New Job Step dialog box, provide a name for the step in the "Step name" field.
In the "Type" section, select "Transact-SQL script (T-SQL)" as the type.
In the "Database" field, select the appropriate database where your stored procedure exists.
In the "Command" field, enter the code to execute your stored procedure. Here's an example:
EXEC usp_DeleteOldRecords;Click on the "OK" button to save the job step.
In the "Schedules" tab of the New Job dialog box, click on the "New" button to create a new schedule for the job. This will open the New Job Schedule dialog box.
In the New Job Schedule dialog box, configure the schedule as follows:
Click on the "OK" button to save the job schedule.
Review the job settings in the "Notifications", "Targets", and "History" tabs as per your requirements.
Click on the "OK" button to create the job.
Janarthanan SRank #224 · 11K reputationPosted Jun 2, 2023, 5:03 AM EDT
CREATE PROCEDURE DeleteOldData
AS
BEGIN
-- Check if the current month is January
IF MONTH(GETDATE()) = 1
BEGIN
-- Delete data from the first table
DELETE FROM table1
WHERE date_column < DATEADD(YEAR, -1, GETDATE());
-- Delete data from the second table
DELETE FROM table2
WHERE date_column < DATEADD(YEAR, -1, GETDATE());
-- Delete data from the third table
DELETE FROM table3
WHERE date_column < DATEADD(YEAR, -1, GETDATE());
-- Continue deleting from other tables as needed
-- Add more DELETE statements for each table you want to delete data from
END
END
To execute
EXEC DeleteOldData;
Anandu G NathRank #681 · 3.5K reputationPosted Dec 26, 2023, 10:50 PM EST
CREATE PROCEDURE Sp_DeleteOldData AS BEGIN DECLARE @CurrentDate DATETIME = GETDATE(); DECLARE @TargetMonth INT = 6; -- Specify the month for deletion (e.g., June) -- Check if it's the specified month for deletion IF MONTH(@CurrentDate) = @TargetMonth BEGIN DECLARE @CutoffDate DATETIME = DATEADD(YEAR, -1, @CurrentDate); -- Calculate cutoff date -- Table 1 deletion DELETE FROM Table1 WHERE DateColumn < @CutoffDate; -- Table 2 deletion DELETE FROM Table2 WHERE DateColumn < @CutoffDate; -- Add more DELETE statements for other tables as needed PRINT 'Old data older than 1 year has been deleted.'; END ELSE BEGIN PRINT 'Not the specified month for data deletion.'; END ENDYou can use the above query as a refrence, according to your needs you can change.@Meghana M
Subarta RayRank #336 · 7.4K reputationPosted Dec 26, 2023, 7:57 AM EST
CREATE PROCEDURE DeleteOldData
AS
BEGIN
DECLARE @CurrentDate DATETIME = GETDATE();
DECLARE @RetentionDate DATETIME;
-- Set the retention date to the first day of January of the previous year
SET @RetentionDate = DATEADD(YEAR, DATEDIFF(YEAR, 0, @CurrentDate) - 1, 0);
-- Check if the current month is January before proceeding with deletion
IF MONTH(@CurrentDate) = 1
BEGIN
-- Delete data from Table1
DELETE FROM Table1 WHERE CreatedDate < @RetentionDate;
-- Delete data from Table2
DELETE FROM Table2 WHERE CreatedDate < @RetentionDate;
-- Add more tables as needed
PRINT 'Data older than 1 year deleted successfully.';
END
ELSE
BEGIN
PRINT 'Deletion is only performed in January.';
END
END;
Jayraj ChhayaRank #304 · 8.2K reputationPosted Dec 27, 2023, 2:43 AM EST
Please refer this one
CREATE PROCEDURE DeleteOldData AS BEGIN DECLARE @CurrentDate DATE = GETDATE(); DECLARE @TargetDate DATE = DATEADD(YEAR, -1, @CurrentDate); DECLARE @TargetMonth INT = MONTH(@TargetDate); -- Table 1 DELETE FROM Table1 WHERE YEAR(DateColumn) <= YEAR(@TargetDate) AND MONTH(DateColumn) = @TargetMonth; -- Table 2 DELETE FROM Table2 WHERE YEAR(DateColumn) <= YEAR(@TargetDate) AND MONTH(DateColumn) = @TargetMonth; -- Table 3 DELETE FROM Table3 WHERE YEAR(DateColumn) <= YEAR(@TargetDate) AND MONTH(DateColumn) = @TargetMonth; -- Add more tables as needed END