-2

我需要创建一个存储过程,用于将生产数据库中某些表中的数据移动到 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++ 张桌子可以使用相同的脚本。你能告诉我如何让这段代码更简单更短吗?谢谢

4

1 回答 1

0

您可以在单个语句中组合 INSERT 和 DELETE:

DELETE [DB_Production].[dbo].[tableDetail]
output deleted.col1, deleted.col2, etc into [DB_Archive].[dbo].[tableDetail]
where exists (select * from [DB_Archive].[dbo].[tableMaster] tblMaster where [DB_Production].[dbo].[tableDetail].QuoNo = tblMaster.QuoNo)
于 2014-04-04T07:54:08.057 回答