Mejor equivalente para IsInteger en SQL Server


¿Cuál es la mejor manera de determinar si el valor de un campo es un entero en SQL Server (2000/2005/2008)?

IsNumeric devuelve true para una variedad de formatos que probablemente no se convertirían en un entero. Los ejemplos incluyen "15.000" y "15.1".

Puede usar una instrucción like, pero que solo parece funcionar bien para campos que tienen un número predeterminado de dígitos...

select * where zipcode like '[0-9][0-9][0-9][0-9][0-9]'

Podría escribir una función definida por el usuario que intente convertir un parámetro varchar a un int dentro de un bloque try/catch, pero estoy verificando con la comunidad para ver si alguien ha encontrado algún método exitoso para lograr este objetivo, preferiblemente uno que pueda usarse dentro de la cláusula where de una instrucción SQL sin crear otros objetos.

Author: OMG Ponies, 2010-03-01

11 answers

1 enfoque es

zipcode NOT LIKE '%[^0-9]%'

Doble negativo, tengo que amarlos!

 32
Author: AdaTheDev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-01 18:52:01

Entrada Tardía que maneja negativo

ISNUMERIC(zipcode + '.0e0') --integer
ISNUMERIC(zipcode + 'e0')  --decimal

Para más ver este

 50
Author: gbn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-03 05:35:28

Si SQL Server 2005+, activaría CLR y crearía la función para soportar expresiones regulares. Para SQL Server 2000, consulte este artículo para crear un UDF para hacer lo mismo.

Entonces usaría la expresión regular: ^\d{5}$

 6
Author: OMG Ponies,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-01 18:57:16

Esta expresión da 1 para un valor entero y 0 de lo contrario

floor((floor(abs(zipcode)))/abs(zipcode))
 3
Author: george,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-27 08:44:28

Se me ocurrió la respuesta perfecta para esto en otra pregunta de StackO.
También prueba que no puede usar ".0e0" como un usuario sugiere aquí.
Lo hace sin CLR o funciones no escalares.
Por favor compruébalo: https://stackoverflow.com/a/10645764/555798

 0
Author: MikeTeeVee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:19

¿Por qué no usar lo siguiente? No veo ningún caso en el que falle.

  • 1 = entero
  • 0 = no entero
  • null = no numérico
DECLARE @TestValue nvarchar(MAX)
SET @TestValue = '1.04343234e5'

SELECT CASE WHEN ISNUMERIC(@TestValue) = 1
        THEN CASE WHEN ROUND(@TestValue,0,1) = @TestValue
            THEN 1
            ELSE 0
            END
        ELSE null
        END AS Analysis
 0
Author: cjbarth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-04 23:36:47

Después de pasar a sql 2008, estaba luchando con isnumeric('\8') devolviendo true pero lanzando un error al convertirlo a un entero. Al parecer, la barra inclinada hacia adelante es una moneda válida para yen o won - (referencia http://www.louiebao.net/blog/200910/isnumeric/)

Mi solución fue

case when ISNUMERIC(@str) > 0 and not rtrim(@str) LIKE '[^0-9]%'  and not rtrim(@str) LIKE '%[^0-9]' and not rtrim(@str) LIKE '[^0-9]%' then rtrim(@str) else null end
 0
Author: jessieloo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-18 13:13:12

Vea si el siguiente código ayudará. En los siguientes valores solo 9, 2147483647, 1234567 son elegibles como Entero. Podemos crear esto como función y podemos usar esto.

CREATE TABLE MY_TABLE(MY_FIELD VARCHAR(50))
INSERT INTO MY_TABLE
VALUES('9.123'),('1234567'),('9'),('2147483647'),('2147483647.01'),('2147483648'), ('2147483648ABCD'),('214,7483,648')

SELECT *
FROM MY_TABLE
WHERE CHARINDEX('.',MY_FIELD) = 0 AND CHARINDEX(',',MY_FIELD) = 0       
AND ISNUMERIC(MY_FIELD) = 1 AND CONVERT(FLOAT,MY_FIELD) / 2147483647 <= 1
DROP TABLE MY_TABLE
 0
Author: Gopakumar N.Kurup,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-01 09:03:52

Lo hice usando una sentencia Case: Cast (Case When Quantity / [#of Days] = Cast (Quantity/[# of Days] as int) Then abs (Quantity/[# of Days]) Else 0 End as int)

 0
Author: Todd181,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-03 22:22:42

Para probar si el valor de entrada es un entero o no podemos usar la función SQL_VARIANT_PROPERTY de SQL SERVER.

El siguiente script SQL tomará la entrada y probará si el tipo de datos resulta ser entero o no

declare @convertedTempValue bigint, @inputValue nvarchar(255) = '1' --Change '1' to any input value
set @convertedTempValue = TRY_PARSE(@inputValue as bigint) --we trying to convert to bigint
declare @var3 nvarchar(255) = cast (SQL_VARIANT_PROPERTY(@convertedTempValue,'BaseType') as nvarchar(255)) --we using SQL_VARIANT_PROPERTY to find out datatype
if ( @var3 like '%int%')
    begin
    print 'value is integer'
    end
else
    begin
    print 'value is non integer'
    end
go
 0
Author: vibs2006,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-31 12:09:26

Tal vez solo debería almacenar datos enteros en tipos de datos enteros.

 -2
Author: HLGEM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-01 19:59:11