Conversion failed when converting the nvarchar value to data type int

  • ---Create Table

    create table tmp_dist

    ([District] nvarchar(140))

    --Insert Into Table

    insert into tmp_dist values ('1030');

    insert into tmp_dist values ('1080');

    insert into tmp_dist values ('9200.');

    insert into tmp_dist values ('9999MiriTest');

    insert into tmp_dist values ('9999MiriTest1545');

    insert into tmp_dist values ('Districts');

    insert into tmp_dist values ('ABC');

    -----------This is my SQL

    select [District],substring([District],0,charindex('.',[District],1)),

    case when ascii(substring([District],1,1)) between 48 and 57 then [District] else 0 end Dist

    from tmp_dist

    I want to show the result as like below....from my above sql.

    But my above sql giving me an error "Conversion failed when converting the nvarchar value '9200.' to data type int."

    So request you to please provide me solution how to handle this case.How would be my sql

    Expected Result

    -------------------

    District

    -----------

    1030

    1080

    9200

    9999

    9999

    0

    0

    Regards,

    KRaj

  • Just put the 0 in quotes...

    select [District],substring([District],0,charindex('.',[District],1)),

    case when ascii(substring([District],1,1)) between 48 and 57 then [District] else '0' end Dist

    from tmp_dist

  • thanks for your valuable reply,but whats about my other result....

  • Seems to be a problem with the BETWEEN part of the query; it can't do a comparison to those numbers because you're passing an nvarchar type to the BETWEEN, and it needs dates or numbers to work with. This should fix that up:

    select [District],substring([District],0,charindex('.',[District],1)),

    case when CAST(ascii(substring([District],1,1)) AS int) between 48 and 57 then [District] else '0' end Dist

    from tmp_dist

    However, this doesn't quite return the results you wanted; namely, the 4th and 5th rows have more than just the District number. Is this the expected output, or should it be trimmed further?

    - 😀

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply