Paul Riker
Paul Riker

Reputation: 797

How can I calculate a formula within a field returned by a query?

Select table1.column1, table2.column1, calcuate(table1.column2) as result
from table1, table2
where table1.id = table2.fkid

Say table1.column2 is a varchar and the value is "=table1.column1*table2.column1". I want my query to actually calculate that formula rather than return the text. Thoughts?

Upvotes: 2

Views: 2076

Answers (2)

S.Roeper
S.Roeper

Reputation: 359

As far as I know, there is nothing like the JavaScript evaluate in SQL. If you only have a few formulas you can try a CASE switch in your SQL. But in general you maybe should rethink your Architecure - SQL Statements like that are hard to maintain if you have changes. (And you should always expect changes...)

Example:

Select 
  a.column1, 
  b.column1, 
  CASE 
    WHEN b.column2 = 'Multiply' THEN a.column1 * b.column1
    WHEN b.column2 = 'Divide' THEN a.column1 / b.column1
    ELSE 0
  END
from table1 a, table2 b
where a.id = b.fkid

Upvotes: 2

FMaz008
FMaz008

Reputation: 11295

In MSSQL, you have the EXEC command, but in MySQL, you don't have it. You have 2 options:

Upvotes: 0

Related Questions