I’m trying to query a string to match within a range in the database. The table has 2 columns FromCode and ToCode.
Below is the sample data (assume the table is called CodeList):
FromCode ToCode
IV1 0AA IV9 9ZZ
IV10 0AA IV28 9ZZ
IV30 0AA IV32 9ZZ
IV36 0AA IV36 9ZZ
IV40 0AA IV49 9ZZ
IV51 0AA IV56 9ZZ
IV63 0AA IV63 9ZZ
So, if I run the query
SELECT *
FROM CodeList
WHERE FromCode <= 'IV1 1AB' AND ToCode >= 'IV1 1AB'
It would return the result
IV1 0AA IV9 9ZZ
which is correct. But, when I run this:
SELECT *
FROM CodeList
WHERE FromCode <= 'IV2 1AB' AND ToCode >= 'IV2 1AB'
The result I get back is
IV1 0AA IV9 9ZZ
IV10 0AA IV28 9ZZ
So, to a human the string IV2 2AB is within IV1 0AA - IV9 9ZZ not IV10 0AA - IV28 9ZZ.
If anyone could suggest a better way to search through the data it’d be much appreciated. Also, the engine I’m running this on is SQL Server 2012.
Many thanks!
set it in a function to make use more easy