我想创建一个通用的Oracle PL / SQL过程,它将表名和列名作为参数,然后通过SQL再次创建表名。然后我的程序的基本结构是这样的:
CREATE OR REPLACE PROCEDURE P_GROUPBY (
P_Table_Name IN ,
P_Column_Name IN ,
)
BEGIN
/**********************Check Parameters ************************/
IF (P_Table_Name IS NULL OR P_Column_Name IS NULL)
THEN
Raise_Application_Error (-20001, 'Parameter cannot be NULL');
END IF;
/**********************Select statment ************************/
SELECT P_Column_Name, COUNT(*) AS CNT
FROM P_Table_Name
GROUP BY P_Column_Name
ORDER BY P_Column_Name;
EXCEPTION
WHEN OTHERS
THEN
ROLLBACK;
DBMS_OUTPUT.Put_Line ('Cannot run the statement');
Raise_Application_Error (-20004,
'Could not run the procedure: ' || SQLERRM);
END P_GROUPBY;
如何确定参数的数据类型?如何做到这一点?
答案 0 :(得分:0)
您无法像这样发出SQL语句:
SELECT P_Column_Name, COUNT(*) AS CNT
FROM P_Table_Name
GROUP BY P_Column_Name
ORDER BY P_Column_Name;
解决方案是使用动态sql:
v_sql := 'SELECT ' || P_Column_Name || ', COUNT(*) AS CNT' ||
'FROM ' || P_Table_Name ||
'GROUP BY ' || P_Column_Name ||
'ORDER BY ' || P_Column_Name;
EXECUTE IMMEDIATE v_sql;
关于How to determine the data type for the parameters?
我不确定你的意思。可能是您要确定表中特定列的类型?如果是,那么您可以查询USER_TAB_COLS
视图:
select data_type from user_tab_cols
where table_name = P_Table_Name
and column_name = P_Column_Name;
还有一个补充:只要您不修改过程中的任何数据,在异常处理部分就不需要ROLLBACK
。