How can I convert string ‘1234-2345’ to integer?

How can I convert a string to integer?

DECLARE @string NVARCHAR(30)='1234-2345'

How can I convert @string to integer type? Is it possible?


Source: sql

1 Comment

  1. Digin Dominic

    If I understood you right, you need:

    DECLARE @Result INT
    DECLARE @string NVARCHAR(30)='1234-2345'
    SELECT @Result = CONVERT(INT, REPLACE(@string, '-', ''))

    SELECT @Result --Your desired result

    If you want the result of your expression:

    DECLARE @Result INT
    DECLARE @string NVARCHAR(30)='1234-2345'

    SELECT @Result = CAST(LEFT(@string, CHARINDEX('-', @string) - 1) AS INT) -
    CAST(RIGHT(@string, CHARINDEX('-', @string) - 1) AS INT)

    SELECT @Result --Your desired result

    Reply

Leave a Reply