简体   繁体   中英

Access97: INSERT INTO if not exists

I need to do a very simple task: execute an INSERT INTO query only if the record doesn't exist in the table. I found a lot of hints out there but none of them work in SQL Access97.

Example:

IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
BEGIN
    INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
END

this won't work because IF NOT EXISTS is not valid.

What is the right way to do this in one SQL clause?

You can build that into an insert . .. select insert . .. select :

INSERT INTO Users (FirstName, LastName)
    SELECT TOP 1 'John', 'Smith'
    FROM Users
    WHERE NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' );

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