T-sql - determine if value is integer

后端 未结 20 2121
情深已故
情深已故 2020-11-30 12:11

I want to determine if a value is integer (like TryParse in .NET). Unfortunatelly ISNUMERIC does not fit me because I want to parse only integers a

相关标签:
20条回答
  • 2020-11-30 12:34

    Use TRY_CONVERT which is an SQL alternative to TryParse in .NET. IsNumeric() isn’t aware that empty strings are counted as (integer)zero, and that some perfectly valid money symbols, by themselves, are not converted to (money)zero. reference

    SELECT @MY_VAR = CASE WHEN TRY_CONVERT(INT,MY_FIELD) IS NOT NULL THEN MY_FIELD
                     ELSE 0
                     END
    FROM MY_TABLE
    WHERE MY_OTHER_FIELD = 'MY_FILTER'
    
    0 讨论(0)
  • 2020-11-30 12:35

    Here's a blog post describing the creation of an IsInteger UDF.

    Basically, it recommends adding '.e0' to the value and using IsNumeric. In this way, anything that already had a decimal point now has two decimal points, causing IsNumeric to be false, and anything already expressed in scientific notation is invalidated by the e0.

    0 讨论(0)
  • 2020-11-30 12:35

    The following is correct for a WHERE clause; to make a function wrap it in CASE WHEN.

     ISNUMERIC(table.field) > 0 AND PATINDEX('%[^0123456789]%', table.field) = 0
    
    0 讨论(0)
  • 2020-11-30 12:35
    declare @i numeric(28,5) = 12.0001
    
    
    if (@i/cast(@i as int) > 1)
    begin
        select 'this is not int'
    end
    else
    begin
        select 'this is int'
    end
    
    0 讨论(0)
  • 2020-11-30 12:39

    With sqlserver 2005 and later you can use regex-like character classes with LIKE operator. See here.

    To check if a string is a non-negative integer (it is a sequence of decimal digits) you can test that it doesn't contain other characters.

    SELECT numstr
      FROM table
     WHERE numstr NOT LIKE '%[^0-9]%'
    

    Note1: This will return empty strings too.

    Note2: Using LIKE '%[0-9]%' will return any string that contains at least a digit.

    See fiddle

    0 讨论(0)
  • 2020-11-30 12:39

    Why not just do something like:

    CASE
    WHEN ROUND(MY_FIELD,0)=MY_FIELD THEN CAST(MY_FIELD AS INT)
    ELSE MY_FIELD
    END
    as MY_FIELD2
    
    0 讨论(0)
提交回复
热议问题