我正尝试将客户数据从旧供应商导入到我们的数据库中-而先前的供应商是varchar(10)字段,在该字段中我看到了诸如“)”和“(”和“-”之类的字符。 / p>
我正在尝试导入到我们的表中,该表将电话号码存储在两列中-phone1AreaCode和phone1Number。 phone1AreaCode是十进制(3,0)数据类型,phone1Number是十进制(7,0)。
我尝试了各种方式将子字符串转换或转换为十进制,但是我一直遇到错误。
这是我在SELECT中可以使用的内容,但是在尝试插入时失败了:
REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING(PHONE,1,3),'(',''),')',''),'-',''),' ','') AS phone1AreaCode,
REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING(PHONE,4,7),'(',''),')',''),'-',''),' ','') AS phone1Number ,
错误:
Error converting data type varchar to numeric.
我尝试了CAST或CONVERT的各种展示位置,但它们都给了我相同的错误:
Argument data type decimal is invalid for argument 1 of substring function.
尝试失败:
REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING(CAST(PHONE AS DECIMAL(3,0)),1,3),'(',''),')',''),'-',''),' ','') AS phone1AreaCode,
从Googling看来,SUBSTRING可能无法处理十进制数据类型。如果是这样,我该如何解决这个问题?
答案 0 :(得分:1)
我能够解决此问题,方法是先将字段转换为INT,然后将其转换为DECIMAL:
CASE
WHEN s.PHONE IS NULL OR s.PHONE = '' THEN NULL
ELSE CONVERT(DECIMAL(3,0),CONVERT(INT,REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING(PHONE,1,3),'(',''),')',''),'-',''),' ','')))
END AS phone1AreaCode,
CASE
WHEN s.PHONE IS NULL OR s.PHONE = '' THEN NULL
ELSE CONVERT(DECIMAL(7,0),CONVERT(INT,REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING(PHONE,4,7),'(',''),')',''),'-',''),' ','')))
END AS phone1Number,