Question: I have the following tables:

Table\_1

```
timestamp                  parameter     value
---------------------------------------------------
2015-09-04 18:48:00.000    par01          1
2015-09-04 18:48:00.000    par02          2
2015-09-04 18:48:00.000    par03          3
2015-09-04 18:48:00.000    par04          4
2015-09-04 18:48:00.000    par05          5
2015-09-04 18:48:00.000    par06          6

```

Table\_2

```
formulaID      formula                 
---------------------------------------------------
1              (par01*par02)
2              (par03*par04)
3              (par05*par06)

```

I want to replace the values of the table\_1 in the formulas of the table\_2. Finally, execute the formula. What's the fastest way?

I know how execute the formulas with the following code:

```
DECLARE @sql VARCHAR(50)
SET @sql = '(2*2)'

EXEC('select ' + @sql)

```

Answer: 
I already did this in the past, and it's a bit tricky:

* Make sure the formulas encloses the field names within square brackets, like `([par01]*[par02])`
* Create a dynamic query to pivot all those table\_1 values as columns
* Combine the pivoted dynamic query with the formula values and it will be "natural" for the SQL to execute

A glimpse on that result would be like this.

```
;WITH   Table_1 AS
(
        SELECT  *
        FROM
        (       VALUES
                ('2015-09-04 18:48:00.000', 'par01', 1),
                ('2015-09-04 18:48:00.000', 'par02', 2),
                ('2015-09-04 18:48:00.000', 'par03', 3),
                ('2015-09-04 18:48:00.000', 'par04', 4),
                ('2015-09-04 18:48:00.000', 'par05', 5),
                ('2015-09-04 18:48:00.000', 'par06', 6)
        )       Table_1([timestamp], [parameter], [value])
)
SELECT  *
FROM
(
        SELECT  ([par01]*[par02]) as [formulaId=1], --
                ([par03]*[par04]) as [formulaId=2], -- This area must be dynamic
                ([par05]*[par06]) as [formulaId=3]  --
        FROM    Table_1 
        PIVOT   (       SUM(value) FOR
                        [parameter] in
                        (
                            [par01], [par02], [par03], -- This area must
                            [par04], [par05], [par06]  -- be dynamic too
                        )
                )       pvt
)       p
UNPIVOT
(
        Value FOR FormulaId IN 
        (
            [formulaId=1],  -- 
            [formulaId=2],  -- Another dynamic area
            [formulaId=3]   -- 
        )
)       upvt

```

Please, notice the dynamic areas.
To retreive a value, you have to use `SELECT`
So your query can be :

```
DECLARE @sql VARCHAR(500)
SET @sql = '((select value from t where parameter = ''par01'') +
             (select value from t where parameter = ''par02'') +
             (select value from t where parameter = ''par03'')) / 3'

EXEC('select ' +  @sql)

```