我有一种情况,即传入的数据值可能有或没有前导零。我需要将它匹配到SQL Server表中的字段/行。 SQL Server数据库中的字段值可能也可能不具有前导零。在SQL Server表中匹配具有可变数量前导零的字段
所以,我可能有:
传入= 5042800138
和分贝值可以是任何5042800138,05042800138,005042800138,0005042800138或传入的可能是005042800138
和db中的值可以是5042800138,05042800138,005042800138,0005042800138中的任何一个
我想出了解决的办法是去掉前导零(总是)上输入数据,并使用SQL像下面的例子:
-- 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
)
这似乎是工作。我的问题是,我错过了什么? SQL Server是否有更好的方式来处理这个问题?我使用SQL Server 2005的
TIA,
唐
看到我的编辑,它显示了你如何使用索引 – 2010-02-05 19:13:51