Conversion failed...!!!

  • create table #temp

    (

    id int,

    strg varchar (5),

    [index] tinyint

    )

    insert into #temp

    values (1, 'abc', 1)

    declare @strg varchar (5)

    select @strg = case when ID = 1 and [INDEX] = 1

    then strg

    else 0

    end

    from #temp

    select @strg

    Msg 245, Level 16, State 1, Line 12

    Conversion failed when converting the varchar value 'abc' to data type int.

    what is wrong here??

    Thanks..

  • Since you have an integer in the else part of your case statement, it tries to implicitly convert anything else that comes out of the case to an int. So when 'abc' comes out of the first part, it tries to make that an int, which it can't. Try putting single quotes around the 0 in your else so it is a character string rather than an integer.

  • Try this:

    create table #temp

    (

    id int,

    strg varchar (5),

    [index] tinyint

    )

    insert into #temp

    values (1, 'abc', 1)

    declare @strg varchar (5)

    select @strg = case when ID = 1 and [INDEX] = 1

    then strg

    else '0'

    end

    from #temp

    select @strg

  • This worked for me... (FWIW)

    insert into temp (id, strg, [index])

    values (1, 'abc', 1);

    declare @strg varchar (5)

    select @strg = case when ID = 1 and [INDEX] = 1

    then strg

    else cast(0 AS varchar(5))

    end

    from temp;

    select @strg

  • This is working thanks.....!!!

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

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