ssnkh
ssnkh

Reputation: 109

sql server dynamic calculated field

I need a calculated field based on each record in sql server 2000. for example there is a table like this:

col1 col2 calcfield
-------------------
1     2   col1+col2
3     5   col1*col2

I need a query to calculate the last field per record eg:

1     2     3
3     5     15

Actually This is a system that calculates a number for some persons.There are some parameters stored in fields of a table and there is another field that stores how to calculate the number from those parameters(that is the formula). for each person there are different parameters and a different formula. I want to design a query that can extract parameters and the calculated column directly from the table

Is there any way to do this and if there is what is the best and fastest way....

best regards

Upvotes: 1

Views: 2331

Answers (1)

Jim
Jim

Reputation: 3510

You just do the math and alias it. Por exemplo:

SELECT 
  field1,
  field2,
  field1 + field2 AS 'CalcField'
FROM table

If you need to do different calculations depending on the record, use a CASE statement:

SELECT 
  field1,
  field2,
  CASE 
    WHEN (some condition) THEN field1 + field2 
    WHEN (some other condition) THEN field1 * field2
    ELSE (some default value or calculation)
    END AS 'CalcField'
FROM table

Upvotes: 2

Related Questions