Sql 存储过程查询循环
我有这个存储过程来查找英国邮政编码Sql 存储过程查询循环,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,我有这个存储过程来查找英国邮政编码 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
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
基本上我有一个数据库,里面有主要地区及其地理位置。。所以w140df的邮政编码将属于数据库中的w14。。。有时它只会回到一封信。。我该如何做才能使存储过程在前两次搜索中不返回空白记录您可以假设您确实想要最长的匹配,因为它更精确:
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子句中参数和列的倒序。您可以假设您确实想要最长的匹配,因为它更精确:
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子句中参数和列的倒序。+1。将其分解为一组子串是多么聪明的想法啊+1.将其分解为一组子串是多么聪明的想法啊!