为什么SQL Server转换为bigint会导致错误?

时间:2012-12-12 07:24:04

标签: sql sql-server type-conversion

我正在尝试将varchar转换为bigint

select convert(bigint, (select(Replace((select value from sometable), ' ', ''))))

为什么会出错?

  

将数据类型varchar转换为bigint时出错。

提前致谢

更新

这是我正在尝试的查询的一部分:

select top 1 * 
into #tblTemp 
from testTable 
where Status = 0 
order by Sno

declare @mobile varchar(50)

set @mobile = (select(Replace((select mobile from #tblTemp), ' ', '')))

--set @mobile = (select( Replace(' 9428017524', ' ', '')))

select convert(bigint, @mobile)

drop table #tblTemp

2 个答案:

答案 0 :(得分:2)

试试这个

select convert(bigint, CASE WHEN ISNUMERIC(@mobile + 'e0') = 0 
                THEN 0 ELSE @mobile)

 -- add this case statement to return only numeric values,     
 -- your query will fail for values like '123-415-6789', '(123)415-6789'

检查您的手机号码数据,看看该列中是否有任何意外值,您可能需要将'-''('')'等替换为''

SeLECT * FROM #tblTmp
WHERE ISNUMERIC(Replace(mobile, ' ', '') + 'e0') = 0;

答案 1 :(得分:1)

我不确定您的真实字符串是什么,但为了安全起见,您可以在转换前检查ISNUMERIC()

DECLARE @mobile varchar(50)
SELECT @mobile = REPLACE(mobile, ' ','') --much simplified version
FROM #tblTemp 

IF ISNUMERIC(@mobile)
   SELECT CONVERT(bigint, @mobile)
ELSE
   SELECT 0

只需阅读您的问题,you don't need a temp table即可。一切都可以在一个查询中完成

SELECT TOP (1) CONVERT(bigint,  CASE ISNUMERIC( REPLACE(mobile,' ','') ) 
                                   WHEN 1 THEN REPLACE(mobile,' ','')
                                   ELSE 0 END )
FROM testTable 
WHERE Status = 0 
ORDER By Sno