A few years ago I worked on a system where a numeric primary key was stored in a [SQL Server] varchar column, so I quickly came unstuck when querying with a BETWEEN operator:
SELECT ID FROM MyTable WHERE ID BETWEEN 100 AND 110;
Results:
100
102
103
109
110
11
This was simply bad design. However, I'm working on an 3rd-party ERP system, which as you can imagine needs to be generic and flexible; thus we have various tables where alphanumeric fields are provided where the business only uses numerics - so similar problems can occur.
I'm guessing that this is a common enough issue; I have a simple enough solution, but I'm curious as to how others approach such problems.
My simple solution is:
SELECT ID FROM MyTable
WHERE ID BETWEEN iStartValue AND iEndValue
AND (LENGTH(ID) = LENGTH(iStartValue)
OR LENGTH(ID) = LENGTH(iEndValue));
As you can possibly tell, this is an Oracle system, but I'm usually working in SQL Server - so perhaps database-agnostic solutions are preferable.
Edit 1: Scratch that - I don't see why proprietary solutions aren't welcomed as well.
Edit 2: Thanks for all the responses. I'm not sure whether I'm disappointed there is not an obvious, sophisticated solution, but I'm correspondingly glad that it doesn't appear that I've missed anything obvious!
I think I still prefer my own solution; it's simple and it works - is there any reason why I shouldn't use it? I can't believe it is much, if any, less efficient that the other solutions offered.
I realise that in an ideal world, this problem wouldn't exist; but unfortunately, I don't work in an ideal world, and often it's a case of making the best of a bad situation.