Skip to content

Instantly share code, notes, and snippets.

@mattmc3
Last active April 10, 2017 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmc3/a324d3d212bdf3fea40433aeb67cd1b9 to your computer and use it in GitHub Desktop.
Save mattmc3/a324d3d212bdf3fea40433aeb67cd1b9 to your computer and use it in GitHub Desktop.
MSSQL robust isnumeric() for try_cast test prior to 2012
select
@val as str_val
,case
when isnumeric(@val + '.0e0') = 1 then
case
when convert(float, @val) between 0 and 255
then cast(@val as tinyint)
else null
end
else null
end as tinyint_val
,case
when isnumeric(@val + '.0e0') = 1 then
case
when convert(float, @val) between -32768 and 32767
then cast(@val as smallint)
else null
end
else null
end as smallint_val
,case
when isnumeric(@val + '.0e0') = 1 then
case
when convert(float, @val) between -2147483648 and 2147483647
then cast(@val as int)
else null
end
else null
end as int_val
,case
when isnumeric(@val + '.0e0') = 1
then cast(@val as bigint)
else null
end as bigint_val
,case
when isnumeric(@val + 'e0') = 1
then cast(@val as decimal(38, 10))
else null
end as dec_val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment