在SQL Server 2008中清理英国地址的邮政编码
创建一个SQL Server函数以清除,替换常见错误并使用正确的空格位置重新格式化UK邮政编码
语境
这篇文章很受欢迎,所以我已经更新了一些信息,并清理了格式,因为错过了几个空格,因此现在可以将其直接复制到SSMS中。
它使用以下步骤;
它使用以下步骤;
- 删除文本字符串(包括空格)中除数字和字母外的所有内容
- 替换标准的输入错误,例如;
- 朴次茅斯(Portsmouth)是PO,科尔切斯特(Colchester)是CO,但有时会以P0或C0(零)输入
- 伊尔福德(Ilford)和雷丁(Reading)是IG和RG,但有时会用6代替G
- 计算出邮政编码应采用的格式,并在其中插入一个空格。
- 检查格式是否正确,如果为true,则返回新值,否则返回旧格式。
请注意,这不会检查邮政编码是否确实存在,并且可以在以下链接中找到“英国邮政编码”以进一步阅读。
SQL
CREATE FUNCTION CleansePostCode (@PostCode VARCHAR(100)) RETURNS VARCHAR(100) AS BEGINDECLARE @OldPostCode VARCHAR(100)SET @OldPostCode=LTRIM(RTRIM(@PostCode))
--Clean to Numbers and LettersDECLARE @Letter INTSET @Letter = PATINDEX('%[^0-Z]%',@PostCode)BEGINWHILE @Letter>0BEGINSET @PostCode = STUFF(@PostCode,@Letter,1,'')SET @Letter = PATINDEX('%[^0-Z]%',@PostCode)ENDEND
--Replace obvious errorsSET @PostCode =(CASE WHEN LEFT(@PostCode,2)='P0' THEN STUFF(@PostCode,1,2,'PO')WHEN LEFT(@PostCode,2)='C0' THEN STUFF(@PostCode,1,2,'CO')WHEN LEFT(@PostCode,2)='I6' THEN STUFF(@PostCode,1,2,'IG')WHEN LEFT(@PostCode,2)='HO' THEN STUFF(@PostCode,1,2,'HD')WHEN LEFT(@PostCode,2)='C8' THEN STUFF(@PostCode,1,2,'CB')WHEN LEFT(@PostCode,2)='D0' THEN STUFF(@PostCode,1,2,'DO')WHEN LEFT(@PostCode,2)='H5' THEN STUFF(@PostCode,1,2,'HS')WHEN LEFT(@PostCode,2)='0L' THEN STUFF(@PostCode,1,2,'OL')WHEN LEFT(@PostCode,2)='0X ' THEN STUFF(@PostCode,1,2,'OX')WHEN LEFT(@PostCode,2)='P0' THEN STUFF(@PostCode,1,2,'PO')WHEN LEFT(@PostCode,2)='R6' THEN STUFF(@PostCode,1,2,'RG')ELSE @PostCode END)
--Works out correct pattern and insert spaceSET @PostCode = (CASE WHEN @PostCode LIKE '[A-Z][A-Z][0-9][0-9][A-Z][A-Z]' THEN LEFT(@PostCode,3)+' '+RIGHT(@PostCode,3)WHEN @PostCode LIKE '[A-Z][0-9][0-9][A-Z][A-Z]' THEN LEFT(@PostCode,2)+' '+RIGHT(@PostCode,3)WHEN @PostCode LIKE '[A-Z][0-9][0-9][0-9][A-Z][A-Z]' THEN LEFT(@PostCode,3)+' '+RIGHT(@PostCode,3)WHEN @PostCode LIKE '[A-Z][0-9][A-Z][0-9][A-Z][A-Z]' THEN LEFT(@PostCode,3)+' '+RIGHT(@PostCode,3)WHEN @PostCode LIKE '[A-Z][A-Z][0-9][0-9][0-9][A-Z][A-Z]' THEN LEFT(@PostCode,4)+' '+RIGHT(@PostCode,3)WHEN @PostCode LIKE '[A-Z][A-Z][0-9][A-Z][0-9][A-Z][A-Z]' THEN LEFT(@PostCode,4)+' '+RIGHT(@PostCode,3)ELSE @PostCode END)
--Update @NewPostCode to old value if pattern does not match, or else use new value.DECLARE @NewPostCode VARCHAR(100)IF (CASE WHEN @PostCode LIKE '[A-Z][A-Z][0-9] [0-9][A-Z][A-Z]' THEN 1WHEN @PostCode LIKE '[A-Z][0-9] [0-9][A-Z][A-Z]' THEN 2WHEN @PostCode LIKE '[A-Z][0-9][0-9] [0-9][A-Z][A-Z]' THEN 3WHEN @PostCode LIKE '[A-Z][0-9][A-Z] [0-9][A-Z][A-Z]'THEN 4WHEN @PostCode LIKE '[A-Z][A-Z][0-9][0-9] [0-9][A-Z][A-Z]' THEN 5WHEN @PostCode LIKE '[A-Z][A-Z][0-9][A-Z] [0-9][A-Z][A-Z]' THEN 6ELSE 0 END)=0BEGIN SET @NewPostCode=@OldPostCodeENDELSESET @NewPostCode=@PostCodeRETURN @NewPostCodeEND