我需要创建一个存储过程,用于将生产数据库中某些表中的数据移动到 2010 年之前的存档数据库(使用与生产相同的结构创建)。我使用的方法是将生产中的数据复制到存档并删除存档中存在的生产中的数据。这是代码:
--## INSERT data from Production DB to Archive DB
--tableMaster
INSERT INTO [DB_Archive].[dbo].[tableMaster]
select * from [DB_Production].[dbo].[tableMaster]
where QuoDate < '2010-01-01 00:00:00.000'
--tableDetail
INSERT INTO [DB_Archive].[dbo].[tableDetail]
select * from [DB_Production].[dbo].[tableDetail] tblDet
where exists (select tblMaster.QuoNo,tblMaster.AgentCode from [DB_Archive].[dbo].[tableMaster] tblMaster
where tblDet.QuoNo = tblMaster.QuoNo)
--tableSubDetail1
INSERT INTO [DB_Archive].[dbo].[tableSubDetail1]
select * from [DB_Production].[dbo].[tableSubDetail1] tblsub1
where exists (select tblMaster.QuoNo,tblMaster.AgentCode from [DB_Archive].[dbo].[tableMaster] tblMaster
where tblsub1.QuoNo = tblMaster.QuoNo)
--tableSubDetail2
INSERT INTO [DB_Archive].[dbo].[tableSubDetail2]
select * from [DB_Production].[dbo].[tableSubDetail2] tblsub2
where exists (select tblMaster.QuoNo,tblMaster.AgentCode from [DB_Archive].[dbo].[tableMaster] tblMaster
where tblsub2.QuoNo = tblMaster.QuoNo)
--## DELETE data from Production DB
--tableMaster
DELETE tblM FROM [DB_Archive].[dbo].[tableMaster] tblM
Where exists (select bmas.QuoNo from [DB_Archive].[dbo].[tableMaster] bmas
where tblM.QuoNo = bmas.QuoNo)
--tableDetail
DELETE tblD FROM [DB_Archive].[dbo].[tableDetail] tblD
Where exists (select bmas.QuoNo from [DB_Archive].[dbo].[tableDetail] bmas
where tblM.QuoNo = bmas.QuoNo)
--tableSubDetail1
DELETE tblS1 FROM [DB_Archive].[dbo].[tableSubDetail1] tblS1
Where exists (select bmas.QuoNo from [DB_Archive].[dbo].[tableSubDetail1] bmas
where tblM.QuoNo = bmas.QuoNo)
--tableSubDetail2
DELETE tblS2 FROM [DB_Archive].[dbo].[tableSubDetail2] tblS2
Where exists (select bmas.QuoNo from [DB_Archive].[dbo].[tableSubDetail2] bmas
where tblM.QuoNo = bmas.QuoNo)
以上仅适用于 4 张桌子,我有 30++ 张桌子可以使用相同的脚本。你能告诉我如何让这段代码更简单更短吗?谢谢