我有一種情況,即傳入的數據值可能有或沒有前導零。我需要將它匹配到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