Search code examples
sqlsql-servert-sqlsql-server-2014

Convert a varchar(10) into an int in SQL Server 2014


Is it possible to convert a varchar(10) into an int in SQL Server 2014?

I tried the following code, but I get a conversion error

Declare @Random varchar(10)
set @Random = CONVERT(varchar, right(newid(),10))
Declare @rand int = cast(@Random as int)
select @rand 

Solution

  • Is it possible to convert a varchar(10) into an int under SQL Server 2012?

    Yes, if the varchar(10) string is all numeric characters and the string is within the bound of an int:

    -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)
    

    In other words, this will work:

    select cast('2147483647' as int)
    

    This will not:

    select cast('2147483648' as int)
    

    I tried the following code, but I get a conversion error

    The code in your question isn't testing whether you can convert a string to an integer, it is testing whether any random string can be converted. Your random strings contain alpha characters that cannot convert to an integer so you are getting conversion errors. But even if you limit the random string to numbers, you will still only be able to convert numeric strings up to 2147483647 before you overflow your int. I don't think that generating (not-so) random strings that meet this criteria will prove much. The simple answer to your question is yes, you can convert a string to an int, as long as the string meets the requirements of an int.