SQL 服务器更新 table 缺少值

SQL server update table with missing values

我有 2 个相似的 table,一个包含所有数据,另一个包含第一个的子集。每 2-3 天我需要在第二个 table 中插入缺失值,我使用此代码

INSERT INTO [SRVDB2].[dbt].[curve].[curve_value]
SELECT *
FROM [SRVDB1].[dbt].[curve].[curve_value] as DB01
WHERE TargetDate >= '20150505'
    and NOT EXISTS (SELECT *
        FROM [SRVDB2].[dbt].[curve].[curve_value] as DB02
        WHERE DB02.TargetDate = DB01.TargetDate
            and DB02.[Hour] = DB01.[Hour]
            and DB02.[id_Mkt] = DB01.[id_Mkt]
            and DB02.[Price] = DB01.[Price]
            and DB02.VoSe = DB01.VoSe
            and DB02.VoBu = DB01.VoBu
    )

它总是有效,但现在我在 VoSeVoBu 列中有一些带有 NULL 的行,并且这些值没有正确插入(即使只执行 SELECT 语句似乎return 所有差异)。我该如何处理这些?

使用ISNULL 来处理NULL 值。

注意:ISNULL 函数中使用一些不会出现在这两列中的随机值。例如我保留了 'AAA'

SELECT *
FROM [SRVDB1].[dbt].[curve].[curve_value] as DB01
WHERE TargetDate >= '20150505'
    and NOT EXISTS (SELECT *
        FROM [SRVDB2].[dbt].[curve].[curve_value] as DB02
        WHERE DB02.TargetDate = DB01.TargetDate
            and DB02.[Hour] = DB01.[Hour]
            and DB02.[id_Mkt] = DB01.[id_Mkt]
            and DB02.[Price] = DB01.[Price]
            and ISNULL(DB02.VoSe,'AAA') = ISNULL(DB01.VoSe,'AAA')
            and ISNULL(DB02.VoBu,'AAA') = ISNULL(DB01.VoBu,'AAA')
    )

为这两列添加 NULL 的显式检查:

INSERT INTO [SRVDB2].[dbt].[curve].[curve_value]
SELECT *
FROM [SRVDB1].[dbt].[curve].[curve_value] as DB01
WHERE TargetDate >= '20150505'
    and NOT EXISTS (SELECT *
        FROM [SRVDB2].[dbt].[curve].[curve_value] as DB02
        WHERE DB02.TargetDate = DB01.TargetDate
            and DB02.[Hour] = DB01.[Hour]
            and DB02.[id_Mkt] = DB01.[id_Mkt]
            and DB02.[Price] = DB01.[Price]
            and ((DB02.VoSe IS NULL AND DB01.VoSe IS NULL) OR DB02.VoSe = DB01.VoSe)
            and ((DB02.VoBu IS NULL AND DB01.VoBu IS NULL) OR DB02.VoBu = DB01.VoBu)
    )

@dotnetom 的回答 (+1) 应该可以解决您的问题。但是,根据您描述的问题做出一些假设,我怀疑以下方法同样有效:

INSERT INTO [SRVDB2].[dbt].[curve].[curve_value]
SELECT *
FROM [SRVDB1].[dbt].[curve].[curve_value]
WHERE TargetDate >= '20150505'
EXCEPT SELECT *
FROM [SRVDB2].[dbt].[curve].[curve_value]