贴出来比较一下,我写的比较烦琐一点,呵呵。
我在动态SQL中写DUAL表时,提示错误为:“ORA-00942: 表或视图不存在”
换成my_dual表就可以了:create table my_dual as select * from dual;不知道楼上的咋就好使捏。。。
--第一张表的列名必须是 以字母开头,且后面跟的全是不相等的数字
PROCEDURE xxx
IS
v_formula cal_formula_t.formula%TYPE;
n_value_new NUMBER(10,2);
v_sql_execute VARCHAR2(100);
TYPE record_value IS RECORD(
code cal_value_t.code%TYPE,
col_value cal_value_t.col_value%TYPE
);
TYPE type_value IS TABLE OF record_value INDEX BY BINARY_INTEGER;
t_value type_value;
BEGIN
-- 1。提取第一张表的值
FOR rec_val IN ( SELECT * FROM cal_value_t ) LOOP
t_value(to_number(substr(rec_val.code, 2))).code := rec_val.code;
t_value(to_number(substr(rec_val.code, 2))).col_value := rec_val.COL_VALUE;
END LOOP;
FOR rec_value IN (SELECT a.ROWID, a.* FROM cal_value_t a) LOOP
IF rec_value.flag = 'N' THEN GOTO continue; END IF;
-- 2。查询该字段的计算公式
BEGIN
SELECT FORMULA
INTO v_formula
FROM cal_formula_t
WHERE CODE = rec_value.CODE;
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('error1:表v_formula中无该code计算公式!code= '||rec_value.code);
RETURN;
WHEN OTHERS THEN
dbms_output.put_line('error2:'||SQLERRM);
RETURN;
END;
-- 3。替换公式中的字符串
FOR i IN 1..t_value.COUNT LOOP
v_formula := REPLACE(v_formula, t_value(i).code, t_value(i).col_value);
END LOOP;
-- 4。获取该行计算后的值
BEGIN
v_sql_execute := 'SELECT '||v_formula||' FROM my_dual';
EXECUTE IMMEDIATE v_sql_execute INTO n_value_new;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('error3:执行动态SQL失败!错误原因:'||SQLERRM);
RETURN;
END;
--dbms_output.put_line(n_value_new);
-- 5。更新第一张表的列
BEGIN
UPDATE cal_value_t
SET col_value = n_value_new
WHERE ROWID = rec_value.ROWID;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('error4:更新code = '||rec_value.code||' 的值失败!错误原因:'||SQLERRM);
rollback;
RETURN;
END;
<>
NULL;
END LOOP;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line('error4:执行失败!错误原因:'||SQLERRM);
ROLLBACK;
END;