SQL,如何将 VARCHAR 转换为 bigint?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14636282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:24:59  来源:igfitidea点击:

SQL, How to convert VARCHAR to bigint?

sqlsql-server

提问by Jaylen

I have a field that is VARCHAR(6)I am trying to insert it into another table of type bigintit is giving me an error

我有一个字段,VARCHAR(6)我试图将它插入另一个类型的表中,bigint它给了我一个错误

(Error Converting from data type varchar to bigint

(从数据类型 varchar 转换为 bigint 时出错

here is what i am doing

这是我在做什么

CONVERT(bigint, seconds) as seconds

Can anybody help with this issue?

有人可以帮忙解决这个问题吗?

回答by Jaylen

This is the answer

这就是答案

(CASE
  WHEN
    (isnumeric(ts.TimeInSeconds) = 1) 
  THEN
    CAST(ts.TimeInSeconds AS bigint)
  ELSE
    0
  END) AS seconds

回答by SQLGuru

an alternative would be to do something like:

另一种方法是执行以下操作:

SELECT
   CAST(P0.seconds as bigint) as seconds
FROM
   (
   SELECT
      seconds
   FROM
      TableName
   WHERE
      ISNUMERIC(seconds) = 1
   ) P0

回答by manoj

I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.

我认为你的代码是正确的。如果您运行以下代码,它将转换被视为 varchar 的字符串 '60' 并返回整数 60,如果在第二个中有包含字符串的整数,则它可以工作。

select CONVERT(bigint,'60') as seconds 

and it returns

它返回

60