如何提取美国邮政编码和检查范围
How to extract US zip codes and check range
我有 table 个地址,其中包含美国和加拿大的邮政编码。在我们的系统中,我们根据邮政编码范围分配区域,因此我需要提取美国地址并检查它们是否在给定范围内。 table 看起来像这样:
Key Postalcode
---------------------------
1 58230
2 49034-9731
3 98801
4 M5H 4E7
我运行一个select声明
SELECT
key, CONVERT(int, LEFT(LTRIM(RTRIM(Postalcode)),5)) AS pcode
FROM
Table
WHERE
LEFT(Postalcode, 5) NOT LIKE '%[^0-9]%'
并且结果 return 符合预期 table。
Key Postalcode
--------------------------
1 58230
2 49034
3 98801
然后我包装别名并尝试检查范围。
select
key, pcode
from
(select
key, convert(int, LEFT(ltrim(rtrim(Postalcode)),5)) as pcode
from
Table
where
LEFT(Postalcode,5) not like '%[^0-9]%') x
where
x.pcode between 58000 and 59000
SQL Server 2008 return 这个错误
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'M5H 4' to data type int.
有人能告诉我发生了什么事吗?别名中的 select 似乎正在扫描原始 table 并遇到加拿大邮政编码。任何帮助将不胜感激。
如果你想要pcode
,那么使用:
select key, pcode
from (select key,
(case when postalcode like '[0-9][0-9][0-9][0-9][0-9]%'
then cast(left(postalcode, 5) as int)
end) as pcode
from t
) t
where t.pcode between 58000 and 59000;
然而,转换为int确实是不必要的。你冷就用:
select key, left(postalcode, 5)
from table t
where postalcode like '[0-9][0-9][0-9][0-9][0-9]%' and
postalcode between '58000' and '59000';
将邮政编码视为字符串而不是数字更有意义。
而且,您的代码不起作用的原因是 SQL 服务器不保证 select
和 where
中表达式的计算顺序。因此,它将 pcode
的计算推到过滤之前。从性能的角度来看这是一件好事,但我确实认为这是一个错误。使用 case
很容易变通(这确实保证了其条件的评估顺序)。
我有 table 个地址,其中包含美国和加拿大的邮政编码。在我们的系统中,我们根据邮政编码范围分配区域,因此我需要提取美国地址并检查它们是否在给定范围内。 table 看起来像这样:
Key Postalcode
---------------------------
1 58230
2 49034-9731
3 98801
4 M5H 4E7
我运行一个select声明
SELECT
key, CONVERT(int, LEFT(LTRIM(RTRIM(Postalcode)),5)) AS pcode
FROM
Table
WHERE
LEFT(Postalcode, 5) NOT LIKE '%[^0-9]%'
并且结果 return 符合预期 table。
Key Postalcode
--------------------------
1 58230
2 49034
3 98801
然后我包装别名并尝试检查范围。
select
key, pcode
from
(select
key, convert(int, LEFT(ltrim(rtrim(Postalcode)),5)) as pcode
from
Table
where
LEFT(Postalcode,5) not like '%[^0-9]%') x
where
x.pcode between 58000 and 59000
SQL Server 2008 return 这个错误
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'M5H 4' to data type int.
有人能告诉我发生了什么事吗?别名中的 select 似乎正在扫描原始 table 并遇到加拿大邮政编码。任何帮助将不胜感激。
如果你想要pcode
,那么使用:
select key, pcode
from (select key,
(case when postalcode like '[0-9][0-9][0-9][0-9][0-9]%'
then cast(left(postalcode, 5) as int)
end) as pcode
from t
) t
where t.pcode between 58000 and 59000;
然而,转换为int确实是不必要的。你冷就用:
select key, left(postalcode, 5)
from table t
where postalcode like '[0-9][0-9][0-9][0-9][0-9]%' and
postalcode between '58000' and '59000';
将邮政编码视为字符串而不是数字更有意义。
而且,您的代码不起作用的原因是 SQL 服务器不保证 select
和 where
中表达式的计算顺序。因此,它将 pcode
的计算推到过滤之前。从性能的角度来看这是一件好事,但我确实认为这是一个错误。使用 case
很容易变通(这确实保证了其条件的评估顺序)。