删除超过2个月的行并级联到3个表

时间:2017-02-17 12:36:29

标签: sql-server tsql

我在SQL Server 2014数据库上有以下SQL方案:

create table dbo.Media ( 
  Id int identity not null
    constraint PK_Media_Id primary key clustered (Id),
  Created datetime not null,
)

create table dbo.MediaFile (
  MediaId int not null, 
  FileId int not null
)    

create table dbo.[File]
(
  Id int identity not null
    constraint PK_File_Id primary key clustered (Id),
  Content varbinary (max) filestream null
    constraint DF_File_Content default (0x)
) filestream_on [FILE]

alter table dbo.MediaFile
add constraint FK_MediaFile_MediaId foreign key (MediaId) references [Media](Id) on delete cascade on update cascade,
    constraint FK_MediaFile_FileId foreign key (FileId) references [File](Id) on delete cascade on update cascade;

我使用以下内容删除超过2个月的所有媒体行:

DELETE 
FROM dbo.Media
WHERE Created < GETDATE() - 60

这会删除MediaFile,因为我有删除Cascade但没有删除相应的文件......

如何在2个月以上的媒体中删除Media,MediaFiles及其文件?

2 个答案:

答案 0 :(得分:0)

这将删除将删除相关Files的所有Media除非它们也与Media相关但不会被删除

delete f 
from dbo.[File] as f
  inner join dbo.MediaFiles as mf
     on mf.FileId = f.FileId
  inner join dbo.Media as m
     on m.MediaId = mf.MediaId
    and m.Created < dateadd(day,-60,getdate())
  where not exists (
      select 1
      from dbo.Media as m
        inner join dbo.MediaFiles as mf
          on m.MediaId = mf.MediaId
         and m.Created >  dateadd(day,-60,getdate())
      where mf.FileId = f.FileId
  );

delete 
from dbo.Media
where Created <  dateadd(day,-60,getdate());

这将删除将删除相关Files的所有Media

delete f 
from dbo.[File] as f
  inner join dbo.MediaFiles as mf
     on mf.FileId = f.FileId
  inner join dbo.Media as m
     on m.MediaId = mf.MediaId
    and m.Created <  dateadd(day,-60,getdate());

delete 
from dbo.Media
where Created < dateadd(day,-60,getdate());

使用exists()代替:

delete f 
from dbo.[File] as f
where exists (
  select 1 
  from dbo.Media as m
    inner join dbo.MediaFiles as mf
      on m.MediaId = mf.MediaId
     and m.Created <  dateadd(day,-60,getdate())
  where mf.FileId = f.FileId
  );

delete 
from dbo.Media
where Created <  dateadd(day,-60,getdate());

答案 1 :(得分:-1)

如果您想要更通用的解决方案,请查看here。 但是对于你的情况,这应该做

DELETE FROM MediaFile WHERE MediaID IN (
   SELECT Id FROM Media WHERE Created < dateadd(dd, -60, GetDate())
)

DELETE FROM Media WHERE Created < dateadd(dd, -60, GetDate())

DELETE FROM File WHERE NOT EXISTS (SELECT 1 FROM MediaFile WHERE File.Id = FileId)