简体   繁体   中英

MS Access SQL 'Data type mismatch in criteria expression' due to null value filtered out in subquery

I have a table in an Access database with a short text column that has the format '0000', '0000-00' or null. I need to query based on the first four numbers, and have tried the following:

SELECT *
FROM 
(
SELECT *
FROM Table1
WHERE Field1 IS NOT NULL
)
WHERE Val(LEFT(Field1,4)) > 1002

This query returns a 'Data type mismatch in criteria expression'. I am almost certain that this arises from the null values, as in a test case I can get the query to work by removing the null values (ie deleting the records) from a copy of the table.

I have also verified that the inner query returns only records where Field1 is not null.

It seems to me perhaps that the query engine is executing out of the order specified in the query? Or is there something I am doing wrong?

Use LIKE :

SELECT *
FROM Table1
WHERE Field1 LIKE "1002*"

NULL values fail almost all comparisons, so there is no need for a separate NULL comparison. The subquery is unnecessary.

For inequality, you should just be able to use string comparisons:

WHERE field1 > "1002"

This will match "1002-00". If you don't want that, use LEFT() :

WHERE LEFT(field1, 4) > "1002"

Also works:

SELECT *
FROM Table1
WHERE IIF(Field1 IS NULL, 0, Val(LEFT(Field1,4))) > 1002

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