将Varchar 3转换为int

时间:2017-07-06 21:03:51

标签: sql sql-server type-conversion

当我在下面的代码中输入最后一个连接时,我收到一条错误消息,指出“将varchar值'3'转换为数据类型int时转换失败。” (MSG 245,Level 16,State 1,Line 1)有人可以帮帮我吗?在一个表中,它确实在我尝试与另一个表中的另一个数字连接的数字前面有奇怪的字符。

SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, ad.fdaddr1 AS [Address]
, pe.fdssn AS SSN
FROM OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbperson') AS pe
ON pt.fdperson = pe.fdid
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbaddress') AS ad
ON ad.id = pe.fdaddress
WHERE ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, pt.fdmedrecnum, pe.fdssn, ad.fdaddr1

1 个答案:

答案 0 :(得分:0)

我认为你在pe.fdaddress中推荐的一条记录不是数字 为了避免这种情况,你最好将整数转换为char 像这样的东西

SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, ad.fdaddr1 AS [Address]
, pe.fdssn AS SSN
FROM OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbperson') AS pe
ON pt.fdperson = pe.fdid
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbaddress') AS ad
ON CAST(ad.id AS varchar(10)) =  CAST(pe.fdaddress AS varchar(10))
WHERE ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, pt.fdmedrecnum, pe.fdssn, ad.fdaddr1