MS Access Insert where not exists

不问归期 提交于 2019-12-20 03:17:02

问题


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?


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/52309940/ms-access-insert-where-not-exists

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