我有以下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个月的所有媒体行以及对应的MediaFile和文件行......所以我有:
DELETE
FROM dbo.Media
WHERE Created < GETDATE() - 60
我的问题是如何确保删除所有MediaFile和文件记录。
答案 0 :(得分:0)
delete [File]
join MediaFile
on [File].Id = MediaFile.FileId
join Media
on Media.ID = MediaFile.MediaId
and Media.Created < GETDATE() - 60
delete MediaFile
join Media
on Media.ID = MediaFile.MediaId
and Media.Created < GETDATE() - 60