Question

I'm trying to calculate string '5-22/5' without getting substrings and finding out operators and such in sql.

my algorythmic string = @Diam is a varchar with the value of '5-22/5'

Desired Result = 2 I am going to need this result evaluated into a variable

I have tried many different ways to get the result of

exec('select ' + @Diam) to return a value to a @result variable of type float defined above.

for example:

DECLARE @result float
DECLARE @Diam varchar(50)

@Diam = 'select @x = ' + @Diam 

declare @S nvarchar(max) = @Diam 
declare @xx int
set @xx = 0
exec sp_executesql @S, N'@x int out', @xx out
select @xx

However I'm getting all sorts of compile errors I can't figure out.

Thanks in advance for any hints / tips / answers.

Was it helpful?

Solution

Try something like this...

DECLARE @result float;
DECLARE @Diam NVARCHAR(50);
DECLARE @S NVARCHAR(max);


SET @Diam = '5-(22/5)';

SET @S = N'SELECT @result = (' + @Diam + ')';

PRINT @S
exec sp_executesql @S
                  , N'@result float OUTPUT'
                  , @result OUTPUT
select @result
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top