Delete large table in Batch and Update source table

  if object_id('Table1','U') is not null
  drop table Table1 ;

  create table Table1 ( id int, filename varchar(50));

  if object_id('Table2','U') is not null
  drop table Table2 ;
create table Table2 ( id int, filename varchar(50), FILE_DESC  varchar(50) , [Processed_date] datetime)

--drop table table1, table2
truncate table table1
truncate table table2

insert into Table1 values (1,'a1'),(2,'a2'), (3,'a3'),(4,'a4'), (5,'a5'),(6,'a6'), (7,'a7'),(8,'a8'), (9,'a9'),(10,'a10'),
(11,'a11'),(12,'a12'), (13,'a13'),(14,'a14'), (15,'a5'),(16,'a16'), (17,'a17'),(18,'a18'), (19,'a19'),(20,'a20')

insert into Table2 values (1,'a1', 'EDI', '1/1/2000' ),(2,'a2', 'EDI', '1/1/2000'), (3,'a3', 'EDI', '1/1/2000'),(4,'a4', 'EDI', '1/1/2000'), (5,'a5', 'EDI', '1/1/2000')
,(6,'a6', 'EDI', '1/1/2000'), (7,'a7', 'EDI', '1/1/2000'),(8,'a8', 'EDI', '1/1/2000'), (9,'a9', 'EDI', '1/1/2000'),(10,'a10', 'EDI', '1/1/2000'),
(11,'a11', 'EDI', '1/1/2000'),(12,'a12', 'EDI', '1/1/2000'), (13,'a13', 'EDI', '1/1/2000'),(14,'a14', 'EDI', '1/1/2000'), (15,'a5', 'EDI', '1/1/2000')
,(16,'a16', 'EDI', '1/1/2000'), (17,'a17', 'EDI', '1/1/2000'),(18,'a18', 'EDI', '1/1/2000'), (19,'a19', 'EDI', '1/1/2000'),(20,'a20', 'EDI', '1/1/2000')

select * from table1
select * from table2


declare @Chunk int=5,  @ToBeDeleted int = 1
  --if object_id('#MyTableVar','U') is not null
  --drop table #MyTableVar ;

--Create table #MyTableVar (filename VARCHAR(32))
WHILE @ToBeDeleted > 0

declare @myTableVar table (filename varchar(30)) ;

	  ;with mycte as (
	  select row_number() Over(Order by b.[Processed_date]) rn ,a.filename
	  FROM Table1 a
INNER JOIN Table2 b ON a.filename = b.filename
AND b.[Processed_date] < DATEADD (WEEK, -10, Getdate ()) )

	  DELETE  Table1
	  OUTPUT DELETED.filename into @myTableVar
	  From Table1 a
	  inner join mycte m On a.filename = m.filename

	  Where  rn< @Chunk ;

		   SET @ToBeDeleted = @@ROWCOUNT
	--Update the source table
	  Update t2 
	  Set [Processed_date] =getdate()
	  From Table2 t2 INNER JOIN @myTableVar m on  m.filename=t2.filename

delete from @myTableVar;

      PRINT 'Deleted/Updated rows: ' + Cast(@ToBeDeleted AS VARCHAR(10))



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s