Conditional fork in SQL based on variable type

I select a value from a table, which can be an integer or nvarchar. It is stored as nvarchar. I want to conditionally call a function that converts this value if it is an integer (that is, if it can be converted to an integer), otherwise I want to select nvarchar without conversion.

This gets into the SQL Server 2005 database.

select case
    when T.Value (is integer) then SomeConversionFunction(T.Value)
    else T.Value
end as SomeAlias

from SomeTable T

Please note that this is the "(integer)" part that I'm having problems with. Thanks in advance.

UPDATE

Comment on Jan's answer. This explains why and what is a little better. Thanks to everyone for their thoughts.

+3
source share
7 answers
 select case
     when ISNUMERIC(T.Value) then T.Value 
     else SomeConversionFunction(T.Value)
 end as SomeAlias

, sql_variant?

+4

, , , , :

Msg 245, 16, 1, 1 nvarchar 'word' int.

, :

create table  testing
(
strangevalue   nvarchar(10)
)

insert into testing values (1)
insert into testing values ('word')
select * from  testing

select
    case
        when ISNUMERIC(strangevalue)=1 THEN CONVERT(int,strangevalue)
        ELSE strangevalue
     END
FROM testing

- :

select
    case
        when ISNUMERIC(strangevalue)=1 THEN CONVERT(int,strangevalue)
        ELSE NULL
     END AS StrangvalueINT
    ,case
        when ISNUMERIC(strangevalue)=1 THEN NULL
        ELSE strangevalue
     END AS StrangvalueString
FROM testing

.

+3

, , . int.TryParse() .

+2

ISNUMERIC. , +, - , .

: 2 .

, ISNUMERIC

+2

IsNumeric . , ,

:

select top 10 
    case 
        when isnumeric(mycolumn) = 1 then 
            case 
                when convert(int, mycolumn) = mycolumn then
                    'integer'
                else
                    'number but not an integer'
            end
        else 
            'not a number'
    end 
from mytable
+1

, SQL (, , - ).

, ISNUMERIC , , , strigns.

, , .

+1

... , . , , -, (, ).

0

Source: https://habr.com/ru/post/1705568/


All Articles