Fixing an SQL where statement that is ugly and confusing

Posted by Mike Wills on Stack Overflow See other posts from Stack Overflow or by Mike Wills
Published on 2010-05-13T21:16:54Z Indexed on 2010/05/13 21:34 UTC
Read the original article Hit count: 190

Filed under:
|

I am directly querying the back-end MS SQL Server for a software package. The key field (vehicle number) is defined as alpha though we are entering numeric value in the field. There is only one exception to this, we place an "R" before the number when the vehicle is being retired (which means we sold it or the vehicle is junked). Assuming the users do this right, we should not run into a problem using this method. (Right or wrong isn't the issue here)

Fast forward to now. I am trying to query a subset of these vehicle numbers (800 - 899) for some special processing. By doing a range of '800' to '899' we also get 80, 81, etc. If I cast the vehicle number into an INT, I should be able to get the right range. Except that these "R" vehicles are kicking me in the butt now.

I have tried where vehicleId not like 'R%' and cast(vehicleId as int) between 800 and 899 however, I get a casting error on one of these "R" vehicles.

What does work is where vehicleId not between '800' and '899' and cast(vehicleId as int) between 800 and 899', but I feel there has to be a better way and less confusing way.

I have also tried other variations with HAVING and a sub-query all producing a casting error.

© Stack Overflow or respective owner

Related posts about sql-server

Related posts about sql