sql - Conversion failed when converting the nvarchar value to data type int -


do know wrong here?

all variables nvarchar. error occurs when @functionvalue contains int in string format.

if @targettype = 'int' begin     select @sqlstr = 'update ' + @targettable +                          ' set ' + @targetcolumn + ' = ' + coalesce(cast(@functionvalue int), cast(@value int)) +                           ' ' end 

the problem ambiguity of + operator. when argument numeric, assumes doing numeric addition, rather string concatenation.

if original data characters, can fix removing cast entirely:

if @targettype = 'int' begin     select @sqlstr = 'update ' + @targettable +                          ' set ' + @targetcolumn + ' = ' + coalesce(@functionvalue, @value) +                           ' ' end; 

if original data numeric, need explicitly convert them characters:

if @targettype = 'int' begin     select @sqlstr = 'update ' + @targettable +                          ' set ' + @targetcolumn + ' = ' + cast(cast(coalesce(@functionvalue, @value) int) varchar(255)) +                           ' ' end; 

i moved "cast int" outside coalesce().


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -