SQL Server 2000中最长的前缀匹配

时间:2012-06-01 05:46:17

标签: sql sql-server-2000

我有2张桌子。我们只想说出它的记录和数字

records.number包含一个数字,我想在SQL Server 2000中的numbers.prefix中找到最长的关联前缀

我将如何做到这一点?

e.g。

records.number = '0841234567'

numbers.prefix = '084'
                 '0841'
                 '08412'

我想选择08412

1 个答案:

答案 0 :(得分:4)

select top 1 N.Prefix
from Numbers as N
  inner join Records as R
    on R.Number like N.Prefix+'%'
order by len(N.Prefix) desc

<强>更新

Records中每个数字的最长前缀。

select R.Number,
       (select top 1 N.Prefix
        from Numbers as N
        where R.Number like N.Prefix+'%'
        order by len(N.Prefix) desc) as Prefix
from Records as R

SE-Data