1

我正在尝试转换varcharbigint

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
4

2 回答 2

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'

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

SeLECT * FROM #tblTmp
WHERE ISNUMERIC(Replace(mobile, ' ', '') + 'e0') = 0;
于 2012-12-12T08:24:32.553 回答
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
于 2012-12-12T08:37:42.407 回答