根据第二个表值

时间:2017-06-05 11:13:05

标签: sql sql-server

技术:SQL Server Management Studio 2012

坚持:流程的WHERE部分。

目标:

  1. 使用Col1和Col2作为参考(在TblImportData中保存),基于新导入数据从实时系统归档数据

  2. 从Live系统中删除存档数据

  3. 将导入的数据移至实时

  4. 示例工作流程:

    TblData     
    
    Col1 Col2   Col3
    1    Horse  Brown
    1    Cat    Ginger
    2    Fish   Gold
    2    Dog    White
    3    Cat    Mixed
    3    Cat    Black
    3    Fish   Yellow
    
    TblImport       
    
    Col1  Col2       Col3
    1     Elephant  Grey
    
    TblDataAFTERSQL     
    
    Col1    Col2   Col3
    1    Elephant  Grey
    2    Fish      Gold
    2    Dog       White
    3    Cat       Mixed
    3    Cat       Black
    3    Fish      Yellow
    
    TblArchiveAFTERSQL      
    
    1   Horse   Brown
    1   Cat     Ginger
    

    查询是:

     INSERT INTO [DBArchive].dbo.TblDataArchive  ([Col1],[Col2],[Col3]) 
        SELECT  [Col1],[Col2],[Col3]
        FROM  [DBLive].dbo.TblData
        WHERE (SELECT DISTINCT [Col1],[Col2] FROM [DBImport].dbo.TblImportData)
    

1 个答案:

答案 0 :(得分:2)

我认为这就是你想要的:

INSERT INTO [DBArchive].dbo.TblDataArchive  ([Col1], [Col2], [Col3]) 
    SELECT [Col1], [Col2], [Col3]
    FROM [DBLive].dbo.TblData td
    WHERE EXISTS (SELECT 1
                  FROM [DBImport].dbo.TblImportData tid
                  WHERE tid.[Col1] = td.[Col1] AND tid.[Col2] = td.[Col2]
                 );