You can't use IF EXISTS
in Access. EXISTS() is allowed but only as an evaluative expression, not a procedural one. The EXISTS() expression returns True or False (in the form of -1 and 0).
Imagine that you could use a procedural expression... where are you trying to PRINT the result? There is no place for text results to be printed.
Please describe more clearly what problem you're trying to solve, and where you want the results to appear, and we can help you better.
Taking a wild guess, if you did want a query to return 'Yes' or 'No' then this can do it for you:
SELECT Iif(EXISTS (SELECT * FROM MyTable), "Yes", "No") AS MyTableHasRows
FROM Numbers
WHERE Num = 1;
There's a problem here, though: Access doesn't allow SELECT statements that don't refer to a table. (SQL Server allows this, and Oracle offers the fake DUAL table to select from.) One way around this is to select from a table that has only one row. My query above selects from a Numbers table that's in my test database, where only one row has Num = 1
. Selecting from a table with many rows makes the engine do extra work for no reason.
If you want to do this checking in code, here's the best-performing way I can think of:
If CurrentDb().OpenRecordset("SELECT Top 1 * FROM MyTable").RecordCount > 0 Then
Debug.Print "Yes"
Else
Debug.Print "No"
End If
This is logically identical to EXISTS and will perform better than COUNT(*) which has to look at every row in the table.