2011-02-04 70 views
1

我有這個存儲過程來查找英國的郵政編碼..存儲過程查詢循環

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

ALTER PROCEDURE [dbo].[sp_postcode_UK] 
    -- Add the parameters for the stored procedure here 
    @post_code varchar(10) 

AS 
DECLARE @intFlag INT 
SET @intFlag = 4 
WHILE (@intFlag >=1) 
BEGIN 

    SET NOCOUNT ON; 

    SELECT top 1 id,lat,lng from [postcodes].[dbo].UKREGIONS 
    where postcode = left(@post_code,@intFlag) 
    order by newid() 

    IF @@rowcount > 0 
    BREAK; 
    SET @intFlag = @intFlag - 1 
    END 
GO 

基本上我havea與主要區域和他們的地緣位置數據庫..所以w140df的郵政編碼將屬於W14在數據庫...有時它只能回到一個字母..我怎麼做,所以存儲過程不會返回第一個搜索幾個空白記錄

回答

7

你可以這樣做(假設你真的想要最長匹配,因爲它更精確):

SELECT top 1 id,lat,lng from [postcodes].[dbo].UKREGIONS 
where postcode IN (
    left(@post_code,1), left(@post_code,2), 
    left(@post_code,3), left(@post_code,4) 
) 
ORDER BY LEN(postcode) DESC 

無需循環。

你也可以使用like,但我認爲它會表現得更差。

SELECT top 1 id,lat,lng from [postcodes].[dbo].UKREGIONS 
where @post_code LIKE postcode+'%' 
ORDER BY LEN(postcode) DESC 

請注意LIKE子句中參數和列的顛倒順序。

+0

哇..這很聰明,謝謝堆! – Alessandro 2011-02-04 16:25:22