Home All Groups Group Topic Archive Search About
Author
23 Mar 2006 3:37 AM
Dan
I need to be able to check if the first 4 characters in a varchar field are a
valid int. Is there anything similar to a NAN() function in TSQL that I could
use, or can anyone think of another way to do this?

Below is some sample code I was using to play with this. Obviously the NAN()
function won't work, but that's the idea.

DECLARE @string varchar(20),  @year int
SET @string = '2004 BMW 330xi'
SELECT @year = CASE WHEN NAN(LEFT(@string, 4))
        THEN NULL
        ELSE  CONVERT(int, LEFT(@string, 4)) END
PRINT @year

Author
23 Mar 2006 8:19 AM
Mike Hodgson
You can use the ISNUMERIC() function to test a string to see if it will
cast to a valid int.  Like this:

    DECLARE @string varchar(20),  @year int
    SET @string = '2004 BMW 330xi'
    SELECT @year = CASE WHEN ISNUMERIC(LEFT(@string, 4)) = 0
            THEN NULL
            ELSE  CAST(LEFT(@string, 4) AS INT) END
    PRINT @year


NB/ I also changed the CONVERT() to a CAST() because CAST() is part of
the ANSI standard but CONVERT() is Microsoft proprietary.  The only time
I use CONVERT() is when manipulating datetime values as different string
formats but I've learnt a few tricks with DATEADD() and DATEDIFF()
recently that make most of the things I used to do with CONVERT() redundant.

--
*mike hodgson*
http://sqlnerd.blogspot.com



Dan wrote:

Show quote
>I need to be able to check if the first 4 characters in a varchar field are a
>valid int. Is there anything similar to a NAN() function in TSQL that I could
>use, or can anyone think of another way to do this?
>
>Below is some sample code I was using to play with this. Obviously the NAN()
>function won't work, but that's the idea.
>
>DECLARE @string varchar(20),  @year int
>SET @string = '2004 BMW 330xi'
>SELECT @year = CASE WHEN NAN(LEFT(@string, 4))
>        THEN NULL
>        ELSE  CONVERT(int, LEFT(@string, 4)) END
>PRINT @year

>
Author
23 Mar 2006 11:02 AM
Aaron Bertrand [SQL Server MVP]
You can use ISNUMERIC() but also see
http://www.aspfaq.com/2390





Show quote
"Dan" <D**@discussions.microsoft.com> wrote in message
news:DA35C149-7159-47C6-9170-1E480A1F74C6@microsoft.com...
>I need to be able to check if the first 4 characters in a varchar field are
>a
> valid int. Is there anything similar to a NAN() function in TSQL that I
> could
> use, or can anyone think of another way to do this?
>
> Below is some sample code I was using to play with this. Obviously the
> NAN()
> function won't work, but that's the idea.
>
> DECLARE @string varchar(20),  @year int
> SET @string = '2004 BMW 330xi'
> SELECT @year = CASE WHEN NAN(LEFT(@string, 4))
> THEN NULL
> ELSE  CONVERT(int, LEFT(@string, 4)) END
> PRINT @year

AddThis Social Bookmark Button