MS Access Insert where not exists

Viewed 6254

I have the following table:

+-----------+--------+
| FirstName | Active |
+-----------+--------+
| Rob       | TRUE   |
| Jason     | TRUE   |
| Mike      | FALSE  |
+-----------+--------+

I would like to insert 'John' (with Active=True) only if an entry for John doesn't exist already where Active=True. I try the following:

insert into testTable (FirstName, Active) values ('John',True) where not exists (select 1 from testTable where FirstName='John' and Active=True)

but i get 'Query input must contain at least one table or query'.

Can anybody help with what I am trying to achieve?

2 Answers

You can't combine Values with a WHERE clause. You need to use INSERT INTO ... SELECT instead.

Since you don't want to insert values from a table, you need to use a dummy table. I use MSysObjects for that purpose (that's a system table that always exists and always contains rows):

INSERT INTO testTable (FirstName, Active) 
SELECT 'John', True
FROM (SELECT First(ID) From MSysObjects) dummy
WHERE NOT EXISTS (select 1 from testTable where FirstName='John' and Active=True)

In my case the field already exist in the table so I changed it from an INSERT to an UPDATE query and it worked.

Related