concatenate int and varchar error

  • hello every body ;

    i am trying to run this T code but it return error

    Conversion failed when converting the varchar value '0\0\0' to data type int

    this is my code

    declare @code varchar(10)='119537';

    declare @counted int=(select count(unitid) from UnitsFactors where ItemCode=@code);

    Declare @Stock int = (select QtyUnit from PHMainStore where ItemCode=@code);

    declare @base int =(select unitfactor from UnitsFactors where ItemCode=@code and UnitFactor=1);

    declare @small int= (select max(unitfactor) as f from UnitsFactors where ItemCode=@code group by ItemCode);

    declare @med int = (select unitfactor from UnitsFactors where ItemCode=@code and UnitFactor >@base and UnitFactor <@small);

    declare @second int=@stock%@small;

    declare @first int=(@stock-@second)/@small;

    declare @medvalue int=(@small/@med) ;

    declare @third1 int=(@stock%@medvalue);

    declare @second1 int=((@stock-@third1)/@medvalue)%@med;

    declare @first1 int=(@stock-(@stock%@small))/@small;

    declare @stockstring varchar(20) = case when (@counted = 1) then @Stock when @counted=2 then cast (@first as varchar(20)) + '\'+ cast(@second as varchar(20)) when @counted=3 then cast (@first1 as varchar(20)) + '\'+ cast(@second1 as varchar(20)) +'\' + cast (@third1 as varchar(20)) end ;

    select @stockstring

    variable @stockstring declared as varchar but why return conversion error ?

  • Without looking in great detail, I suspect it might be something to do with this bit:

    CASE WHEN ( @counted = 1 ) THEN @Stock

    You've declare @Stock as an int; maybe the CASE statement is therefore expecting the rest of the values returned to be of type INT, which they aren't - they're all varchars of varying lengths.

    Perhaps change the section indicated above to:

    CASE WHEN ( @counted = 1 ) THEN CAST ( @Stock AS varchar(20))

    Thomas Rushton
    blog: https://thelonedba.wordpress.com

  • ThomasRushton (7/5/2016)


    Without looking in great detail, I suspect it might be something to do with this bit:

    CASE WHEN ( @counted = 1 ) THEN @Stock

    You've declare @Stock as an int; maybe the CASE statement is therefore expecting the rest of the values returned to be of type INT, which they aren't - they're all varchars of varying lengths.

    Perhaps change the section indicated above to:

    CASE WHEN ( @counted = 1 ) THEN CAST ( @Stock AS varchar(20))

    yes ,you are right, thank you very much

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

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