I have a situation where I have an incoming data value that may or may not have leading zeroes. I need to match that to a field/row in a SQL Server table. The field value in the SQL Server database may or may not have leading zeroes as well.
So, I might have:
-
incoming = 5042800138
and the value in db can be any of 5042800138, 05042800138, 005042800138, 0005042800138 -
or the incoming might be 005042800138
and the value in db can be any of 5042800138, 05042800138, 005042800138, 0005042800138
The solution I came up with was to strip off the leading zeroes (always) on the incoming data and use SQL like the following example:
-- this simulates the incoming value to check
-- i strip out the leading zeroes.
declare @tryUPC as varchar(40)
set @tryUPC = '5042800138'
-- try to find it in the database and ignore leading zeroes
select prod_uid, prod_partno, prod_upc
from products as p
where (prod_upc = @tryUPC) or
(
len(prod_upc) > len(@tryUPC)
and right(prod_upc, len(@tryUPC)) = @tryUPC
and stuff(prod_upc, 1, len(prod_upc) - len(@tryUPC), '0') = prod_upc
)
This seems to work. My question is, am I missing something? Does SQL Server have a better way of dealing with this? I am using SQL Server 2005.
tia,
don
If you aren’t able to change existing data to strip the leading zeroes / convert to INT, it might be faster to just do something like so:
That’s about as elegant as my foot, but it would be more static & legible, and (probably) more likely to get at any relevant index.
That’s assuming there’s a finite limit on how many leading zeroes you have, mind. Converting the data to INT (or adding a new INT column and calculating it on insert) would probably be the best fix for the problem.