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, 0005042800138or 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