sql邮政编码空间

时间:2015-07-16 14:38:21

标签: sql sql-server tsql postal-code

我试图做到这一点,无论邮政编码有多长,它总是在最后3个字符之前有空格。有时我会收到邮政编码,人们只输入4个字符,所以代码如下:

def age_finder():
    while True:
        try:
            birthday = input("Enter your Birth date in MM/DD/YYYY format: ")
            birth_date = datetime.strptime(birthday, '%m/%d/%Y')
            break
        except ValueError:
            print("Oops!  That was not a valid date. Try again...") 

    if (((datetime.today() - birth_date).days)/365.2425) > 110:        
        print("Sorry You are older than 110 year i cannot do that math.") 

    elif ((datetime.today() - birth_date).days) < 0:
        print("Sorry you entered a date in the furture.") 

    elif ((datetime.today() - birth_date).days) == 0:
        print("OMG You were just born, tomorrow you will be one day old.") 
    else:
        print("Age: %d days " % ((datetime.today() - birth_date).days))

if __name__ == '__main__':
    try:
        while True:
            age_finder()
    except KeyBoardInterrupt:
        print()
        print('Thanks for using my app')
        exit()

不是很有用。我得到了这个网站,它确实有效,但不是我想要的。我对SQL很新,但在访问中我可以使用它:

更新至:UPDATE [DataTool].[dbo].[EH10414 Summer Events] SET postcode = CASE WHEN LEN(postcode) = 6 THEN STUFF(postcode, 4, 0, ' ') WHEN LEN(postcode) = 7 THEN STUFF(postcode, 5, 0, ' ') END WHERE CHARINDEX(' ', postcode, 1) = 0 AND LEN(postcode) BETWEEN 6 AND 7

这完美无缺,但我不知道如何将其实现为SQL。

任何帮助都会很棒:) 谢谢

2 个答案:

答案 0 :(得分:1)

您的Access代码在SQL Server中几乎可以使用:

Left(PostCode, Len(PostCode) - 3) + ' '  + Right(PostCode, 3)

我先检查一下是否有空格:

(case when PostCode like '% ___' then PostCode
      else Left(PostCode, Len(PostCode) - 3) + ' '  + Right(PostCode, 3)
 end)

答案 1 :(得分:0)

将此实现为SQL的一种方法(通过一些小的调整来获得SQL Server的语法)将创建一个用户定义的函数来获取输入的Postcode,并返回一个添加了空格的新版本:

CREATE FUNCTION SpacePostcode  ( @inputPostcode VARCHAR(8) )
RETURNS VARCHAR(8)
BEGIN
  RETURN Left(@inputPostcode ,Len(@inputPostcode)-3) + ' ' + Right(@inputPostcode,3)
END
GO

然后可以在select语句中使用它来格式化输出,例如

SELECT dbo.fnSpacePostcode('EH78PP') AS postCode

或使用更新语句(如

)更新现有数据
UPDATE myTable
SET PostCode = dbo.fnSpacePostcode(PostCode)