简体   繁体   中英

SQL server update table with missing values

I have 2 similar tables, one with all the data and the other contains a subset of the first. Every 2-3 days I need to insert in the second table the missing values, and I use this code

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
    )

It always worked but now I have some rows with NULL in column VoSe or VoBu and those values are not inserted correctly (even if executing only the SELECT statement seems to return all the differences). How can I handle these?

Add explicit check for NULL for both of these columns:

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's answer (+1) should work for your problem. However, making some assumptions on the problem you describe, I suspect the following would work just as well:

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]

Use ISNULL to handle the NULL values.

NOTE: Use some random value in ISNULL function which will not come in those two columns. For example i have kept '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')
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM