Error converting data type varchar

前端 未结 8 1491
既然无缘
既然无缘 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:32

    Ideally, you want to try to avoid storing the data in this form - would be worth splitting the BIGINT data out in to a separate column for both performance and ease of querying.

    However, you can do a JOIN like this example. Note, I'm not using ISNUMERIC() to determine if it's a valid BIGINT because that would validate incorrect values which would cause a conversion error (e.g. decimal numbers).

    DECLARE @MyTable TABLE (MyCol VARCHAR(20))
    DECLARE @OtherTable TABLE (Id BIGINT)
    
    INSERT @MyTable VALUES ('1')
    INSERT @MyTable VALUES ('Text')
    INSERT @MyTable VALUES ('1 and some text')
    INSERT @MyTable VALUES ('1.34')
    INSERT @MyTable VALUES ('2')
    INSERT @OtherTable VALUES (1)
    INSERT @OtherTable VALUES (2)
    INSERT @OtherTable VALUES (3)
    
    SELECT *
    FROM @MyTable m
        JOIN @OtherTable o ON CAST(m.MyCol AS BIGINT) = o.Id
    WHERE m.MyCol NOT LIKE '%[^0-9]%'
    

    Update: The only way I can find to get it to work for having a WHERE clause for a specific integer value without doing another CAST() on the supposedly bigint column in the where clause too, is to use a user defined function:

    CREATE  FUNCTION [dbo].[fnBigIntRecordsOnly]()
    RETURNS @Results TABLE (BigIntCol BIGINT)
    AS
    BEGIN
    INSERT @Results
    SELECT CAST(MyCol AS BIGINT)
    FROM MyTable
    WHERE MyCol NOT LIKE '%[^0-9]%'
    RETURN
    END
    
    SELECT * FROM [dbo].[fnBigIntRecordsOnly]() WHERE BigIntCol = 1
    

    I don't really think this is a great idea performance wise, but it's a solution

提交回复
热议问题