Insert INTO NOT EXISTS SQL access

眉间皱痕 提交于 2020-01-10 05:41:10

问题


I am trying to insert records from another table into a table in Access using sql. I have pasted the statement below. I want to insert the records that exist in ImportMetricsIDs01262015 but not in ShouldImportMetricsIDs. It runs perfectly without any errors but it won't insert anything even when I physically add a new record.

INSERT INTO ShouldImportMetricsIDsTable ( [Formulary ID], [Market Segment] )
SELECT ImportMetricsIDs01262015.[Formulary ID], ImportMetricsIDs01262015.[Market Segment]
FROM ImportMetricsIDs01262015
WHERE NOT EXISTS (SELECT *
FROM ShouldImportMetricsIDsTable);

回答1:


You need a correlation clause. The subquery just checks whether or not the table is empty. Something like:

INSERT INTO ShouldImportMetricsIDsTable( [Formulary ID], [Market Segment] )
    SELECT im.[Formulary ID], im.[Market Segment]
    FROM ImportMetricsIDs01262015 as im
    WHERE NOT EXISTS (SELECT 1
                      FROM ShouldImportMetricsIDsTable as sim
                      WHERE im.[Formulary ID] = sim.[Formulary ID] AND
                            im.[Market Segment] = sim.[Market Segment]
                     );



回答2:


You need to correlate your NOT Exist query with the ImportMetricsIDs01262015 table

This code is on the assumption that FormularyID is the key in both the tables.

INSERT INTO ShouldImportMetricsIDsTable (
    [Formulary ID]
    ,[Market Segment]
    )
SELECT ImportMetricsIDs01262015.[Formulary ID]
    ,ImportMetricsIDs01262015.[Market Segment]
FROM ImportMetricsIDs01262015
WHERE NOT EXISTS (
        SELECT *
        FROM ShouldImportMetricsIDsTable
        where ShouldImportMetricsIDsTable.[Formulary ID] = ImportMetricsIDs01262015.[Formulary ID]
        );



回答3:


The keyword "TOP" is necessary in access which is made bold and italic in the code

INSERT INTO ShouldImportMetricsIDsTable( [Formulary ID], [Market Segment] )
SELECT im.[Formulary ID], im.[Market Segment]
FROM ImportMetricsIDs01262015 as im
WHERE NOT EXISTS (SELECT 
***TOP*** 1
                  FROM ShouldImportMetricsIDsTable as sim
                  WHERE im.[Formulary ID] = sim.[Formulary ID] AND
                        im.[Market Segment] = sim.[Market Segment]
                 );


来源:https://stackoverflow.com/questions/28282127/insert-into-not-exists-sql-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!