Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have 10,000 Tables,Views,group of objects and Primery key relation
How can i delete data from database means i want to delete one month data from all tables

Example i have Jan to Dec Month data in database
i want to delete Jan & Feb Months data without breaking table structure

Please suggest
Posted
Updated 4-Dec-15 1:07am
v2
Comments
John C Rayan 4-Dec-15 5:32am    
Explain a bit more clearer by improving the question.
phil.o 4-Dec-15 5:39am    
You may have to describe the relevant elements of your database schema if you want a meaningful answer. Please click the "Improve question" button.
_Asif_ 4-Dec-15 5:51am    
You need to provide schema information, specially how you going to filter data based on date. Do you have created_on type of column n all tables?

SQL
USE [MyDatabase]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[TblEmployee](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[EmpName] [varchar](20) NULL,
	[JoinDate] [datetime] NULL,
 CONSTRAINT [PK_TblEmployee] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

INSERT INTO [dbo].[TblEmployee]([EmpName],[JoinDate])VALUES('Mahesh Patel','2015-01-01')
INSERT INTO [dbo].[TblEmployee]([EmpName],[JoinDate])VALUES('Rajesh Koriya','2014-01-01')
INSERT INTO [dbo].[TblEmployee]([EmpName],[JoinDate])VALUES('Dhaval Patel','2014-01-01')
INSERT INTO [dbo].[TblEmployee]([EmpName],[JoinDate])VALUES('Krutarth Shah','2014-01-01')



Delete from table Dynamically


SQL
USE [MyDatabase]
GO
DECLARE @Query NVARCHAR(MAX)
DECLARE MyCursor CURSOR LOCAL FOR
SELECT 'DELETE FROM ' + NAME +' WHERE JoinDate = ' +CHAR(39)+ '2014-01-01' + CHAR(39) as Query from Sys.Objects where type = 'U'
OPEN MyCursor
	FETCH NEXT FROM MyCursor INTO @Query
	WHILE  @@Fetch_Status=0            
	BEGIN
		PRINT(@Query)
		EXEC(@Query)
		FETCH NEXT FROM MyCursor INTO @Query
	END
CLOSE MyCursor
DEALLOCATE MyCursor
 
Share this answer
 
v2
Try to run this:
Select  'delete from '
     ||  object_name
     ||' where created_datetime <='
     ||' TRUNC(SYSDATE,'||''''||'YEAR'||''''||');' 
     delete_old_rows
from user_objects
where object_type = 'TABLE';

May this helpful for you.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900