sql server 2008 - Execute mathematical expression and set the value to variable in SQL -


i have mathematical expression expression created 3 variable @val1,@val2 , @operator. should need execute query string , need set value of variable inside query string, how can set?

i tried below

declare @val1 varchar=100; declare @val2 varchar=300; declare @oper varchar(20)='>';  declare @query varchar(max);  declare @flag int=0;  set @query='if(convert(int,'+@val1+')'+@oper+'convert(int,'+@val2+') set @flag=1';   exec (@query); print @flag; 

note: using inside function.

use parametrized query sp_executesql procedure:

declare @val1 varchar(20)= '500'; declare @val2 varchar(20)= '300'; declare @oper varchar(20)= '>';  declare @query nvarchar(max);  declare @flag int= 0;  set @query = 'if ' + @val1 + @oper + @val2 + ' set @flag=1';  declare @paramdefs nvarchar(max) = n'@flag int output'  exec sp_executesql @query, @paramdefs, @flag output  print @flag; 

also corrected mistakes:

  1. declare @val1 varchar=100; default size 1 , @val1 initialized * not 100. see why cast/convert int returns asterisk details.
  2. you don't need cast int inside dynamic query.

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -