Error converting data type varchar

前端 未结 8 1486
既然无缘
既然无缘 2020-12-20 15:07

I currently have a table with a column as varchar. This column can hold numbers or text. During certain queries I treat it as a bigint column (I do

相关标签:
8条回答
  • 2020-12-20 15:35

    Try using this:

    SELECT 
      ID, 
      CAST(MyCol AS bigint) as MyCol
    FROM
    (
      SELECT TOP (100) PERCENT 
          ID, 
          MyCol 
      FROM 
          MyTable 
      WHERE 
          (isnumeric(MyCol) = 1)
    ) as tmp
    

    This should work since the inner select only return numeric values and the outer select can therefore convert all values from the first select into a numeric. It seems that in your own code SQL tries to cast before executing the isnumeric function (maybe it has something to do with optimizing).

    0 讨论(0)
  • 2020-12-20 15:43

    Try doing the select in 2 stages.

    first create a view that selects all columns where my col is nummeric.

    Then do a select in that view where you cast the varchar field.

    The other thing you could look at is your design of tables to remove the need for the cast.

    EDIT

    • Are some of the numbers larger than bigint?
    • Are there any spaces, leading, trailing or in the number?
    • Are there any format characters? Decimal points?
    0 讨论(0)
提交回复
热议问题