立即执行Oracle

时间:2013-12-22 16:23:29

标签: sql oracle plsql

我正在尝试执行EXECUTE IMMEDIATE语句。但我收到以下错误。我正在尝试这个新的,我读了现有的帖子。

在看到以下示例后,我正在尝试这个。 http://docs.oracle.com/cd/B13789_01/appdev.101/b10807/13_elems017.htm

它表示无效的表名,但表存在

Connecting to the database Local
ORA-00903: invalid table name
ORA-06512: at "MMM.Maxtable", line 26
ORA-06512: at line 9
CNTRYCNTRYID
SELECT MAX(:1) FROM  :2  WHERE :1  <= 99999
Process exited.
Disconnecting from the database oraclesrv.local.

我正在传递CNTRY AS TABLE NAME,CNTRYID作为列名

Create OR REPLACE PROCEDURE Maxtable
    (ITableName          VarChar2,
    IColumnName  VarChar2 )
AS
 Limit1 int;
 RESULT1 INT;
 Query1  varChar(255);
 TableName          VarChar(50);
    ColumnName VarChar(50);
BEGIN
Limit1 := 99999;
MaxTableId := 0;
Result1 := 0;

TableName := ltrim(rtrim(ITableName));
ColumnName := ltrim(rtrim(iColumnName));
DBMS_OUTPUT.PUT_LINE(TableName || ColumnName );

IF (TableName is not null and  ColumnName is not null) then
Query1 := 'SELECT MAX(:1) FROM  :2  WHERE :1  <= 99999' ;
DBMS_OUTPUT.PUT_LINE(Query1);

EXECUTE IMMEDIATE Query1 INTO Result1 USING ColumnName, TableName;                               
END IF;

DBMS_OUTPUT.PUT_LINE(Result1);

 MaxTableId := Result1;

 IF (MaxTableId = Limit1) THEN
    MaxTableId := -1;
 ELSE
    MaxTableId := MaxTableId + 1  ;
 END IF;

END adm_getMaxTableIdLimited;

我也试过这个选项,它不起作用..

连接数据库。 ORA-00905:缺少关键字 ORA-06512:在“mmm.Maxtable”,第19行 ORA-06512:第9行 SELECT max(CNTRYID)INTO Result1 FROM CNTRY WHERE CNTRYID&lt; = 99999 流程已退出。 断开与数据库oraclesrv.local的连接。

Create OR REPLACE PROCEDURE Maxtable
    (TableName          VarChar2,
    ColumnName  VarChar2,
    MaxTableId OUT  Int )
AS
 Limit1 int;
 RESULT1 INT;
 Query1  varChar(255);
BEGIN
Limit1 := 99999;
MaxTableId := 0;
Result1 := 0;

IF (TableName is not null and  ColumnName is not null) then
Query1 := 'SELECT max( ' || ColumnName || ')  INTO  Result1'  || ' FROM ' || TableName || ' WHERE ' || ColumnName || ' <= ' || 99999 ;

DBMS_OUTPUT.PUT_LINE(Query1);

EXECUTE IMMEDIATE Query1;
END IF;

DBMS_OUTPUT.PUT_LINE(Result1);

 MaxTableId := Result1;

 IF (MaxTableId = Limit1) THEN
    MaxTableId := -1;
 ELSE
    MaxTableId := MaxTableId + 1  ;
 END IF;

END Maxtable;

2 个答案:

答案 0 :(得分:2)

您添加的链接说明如下:

  

您不能使用绑定参数将架构对象的名称传递给   动态SQL语句。

很遗憾,您无法对表名和列名使用绑定变量。你必须对它们进行字符串连接:

Query1 := 'SELECT MAX(' || ColumnName || ') FROM  ' || TableName || '  WHERE ' || ColumnName || ' <= 99999' ;

以下列方式使用EXECUTE IMMEDIATE:

EXECUTE IMMEDIATE Query1 INTO Result1;

答案 1 :(得分:0)

EXECUTE IMMEDIATE 'drop table tbl_proc_cre_ins purge';--using "EXECUTE IMMEDIATE";
EXECUTE IMMEDIATE 'CREATE TABLE tbl_proc_cre_ins(rollno varchar2(100),name varchar2(100))';