How to execute mathematical expression stored in a varchar variable

前端 未结 4 1883
清歌不尽
清歌不尽 2021-01-13 13:03

I have a variable in my database function:

@LocalVariable = \'2*3*100\'

I want to get the result by executing the expression in another var

相关标签:
4条回答
  • 2021-01-13 13:34

    You could use sp_executesql:

    declare @expression nvarchar(max)
    set @expression = '2*3*100'
    
    declare @sql nvarchar(max)
    set @sql = 'select @result = ' + @expression
    
    declare @result int
    exec sp_executesql @sql, N'@result int output', @result = @result out
    
    select @result
    

    Example at SE Data.

    0 讨论(0)
  • 2021-01-13 13:40

    I got a better solution, I though of sharing with you all

    DECLARE @x xml
    DECLARE @v FLOAT
    SET @x = ''
    SET @v = @x.value('(1 + 4) div 3', 'FLOAT')
    SELECT @v
    

    This will work in function too.

    0 讨论(0)
  • 2021-01-13 13:41
    DECLARE @LocalVariable VARCHAR(32);
    SET @LocalVariable = '2*3*100';
    EXEC('SELECT ' + @LocalVariable);
    

    To get it into a variable:

    DECLARE @LocalVariable VARCHAR(32);
    SET @LocalVariable = '2*3*100';
    
    DECLARE @out INT, @sql NVARCHAR(4000);
    SET @sql = N'SELECT @out = ' + @LocalVariable;
    
    EXEC sp_executesql @sql, N'@out INT OUTPUT', @out OUTPUT;
    
    PRINT @out;
    

    However you can't do this in a function, because you can't use EXEC, sp_executesql etc. in a function, sorry.

    0 讨论(0)
  • 2021-01-13 13:46
    DECLARE @LocalVariable NVARCHAR(100)
    SET @LocalVariable = '2*3*100'
    EXEC ('SELECT ' + @LocalVariable)
    
    0 讨论(0)
提交回复
热议问题