表A
主题 | 标记 |
---|---|
A | 100 |
B | 200 |
C | 400 |
D | 500 |
表B
主题 | 公式 |
---|---|
A | A/B |
B | 早/晚 |
C | D/A-B |
D | A+B/C-D |
输出
主题 | 结果 |
---|---|
A | 0.5 |
B | 0.4 |
C | 5 |
D | 3 |
您发布的某些结果(C 和 D)无效;首先你必须乘/除,然后加/减。对于您想要的结果,您需要使用括号。
无论如何:应该使用动态SQL。这是一种选择:
table_a
获取所有变量
table_b
SQL> set serveroutput on;
SQL> declare
2 l_val_a table_a.marks%type;
3 l_val_b table_a.marks%type;
4 l_val_c table_a.marks%type;
5 l_val_d table_a.marks%type;
6 --
7 l_str varchar2(200);
8 l_result number;
9 begin
10 select max(case when subject = 'A' then marks end),
11 max(case when subject = 'B' then marks end),
12 max(case when subject = 'C' then marks end),
13 max(case when subject = 'D' then marks end)
14 into l_val_a, l_val_b, l_val_c, l_val_d
15 from table_a;
16
17 for cur_r in (select subject, formula
18 from table_b
19 )
20 loop
21 l_str := replace(replace(replace(replace(
22 cur_r.formula, 'A', l_val_a),
23 'B', l_val_b),
24 'C', l_val_c),
25 'D', l_val_d);
26 l_str := 'select ' || l_str || ' from dual';
27 execute immediate l_str into l_result;
28 dbms_output.put_line(cur_r.subject ||': '|| l_str ||' = '|| l_result);
29 end loop;
30 end;
31 /
输出:
A: select 100/200 from dual = .5
B: select 200/500 from dual = .4
C: select 500/100+200 from dual = 205
D: select 100+200/400-500 from dual = -399.5
PL/SQL procedure successfully completed.
SQL>