在 Node 应用程序中查询表名时出现"SQL command not properly ended"错误消息



在使用节点oracledb执行以下查询时,我收到以下错误:

SELECT OBJECT_NAME
FROM ALL_OBJECTS || '@' || :db
WHERE OWNER = :schema
    AND (
        OBJECT_TYPE = ''TABLE''
        OR OBJECT_TYPE = ''VIEW''
        OR OBJECT_TYPE = ''SYNONYM''
    )
ORDER BY OBJECT_NAME

如果我在Oracle控制台中执行这个查询(当然,用占位符代替实际值),它执行得很好。然而,当我在Node应用程序中执行此操作时,我会得到以下错误:

"ORA-00933: SQL command not properly ended"

有人能帮助我解释为什么会出现这个错误吗?我可以确认,我的占位符肯定是用我想要填充的值填充的。

谢谢!

编辑:

即使我尝试这样做:

SELECT OBJECT_NAME
FROM ALL_OBJECTS || @ || :db

我仍然会犯同样的错误。

SELECT OBJECT_NAME
FROM ALL_OBJECTS || '@' || :db
WHERE OWNER = :schema
    AND (
        OBJECT_TYPE = 'TABLE'
        OR OBJECT TYPE = 'VIEW'
        OR OBJECT_TYPE = 'SYNONYM'
    )
ORDER BY OBJECT_NAME
  • 首先,您的查询中存在拼写错误。对象类型OR OBJECT TYPE = 'VIEW'中缺少下划线

  • 不能使用动态对象名称执行SQL。SQL必须具有静态对象名称DATABASE LINK是数据库对象,必须在运行时提供静态名称。只能提供占位符作为文本的绑定变量

如果要使其动态,则需要(ab)在PL/SQL中使用EXECUTE IMMEDIATE。你需要动态地准备字符串,然后执行它

例如,在SQL*Plus:中

var db varchar2(30);
var schema varchar2(30);
exec :db := 'database_name'
exec :schema := 'OWNER'
SET serveroutput ON
DECLARE
  v_sql         VARCHAR2(2000);
  v_object_name VARCHAR2(30);
BEGIN
  v_sql:= 'SELECT OBJECT_NAME
FROM ALL_OBJECTS@'||:db||' WHERE OWNER = :schema     
AND (        
OBJECT_TYPE = ''TABLE''
OR OBJECT_TYPE = ''VIEW''        
OR OBJECT_TYPE = ''SYNONYM''
)
ORDER BY OBJECT_NAME';
  dbms_output.put_line(v_sql);
  execute immediate v_sql into v_object_name using :db, :schema;
END;
/

或者,您可以将DATABASE LINK作为静态名称:

首先我创建数据库链接:

SQL> CREATE DATABASE LINK TEST
  2    CONNECT TO SCOTT IDENTIFIED BY tiger USING 'pdborcl';
Database link created.

tnsnames.ora文件中添加了以下条目:

test =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL=TCP)(HOST=ocalhost)(PORT=1521))
    (CONNECT_DATA = 
      (SERVER=DEDICATED)
      (SERVICE_NAME=pdborcl.in.oracle.com)
    )
  )

让我们在SQL*Plus:中执行

SQL> var schema varchar2(30);
SQL> exec :schema := 'SCOTT'
PL/SQL procedure successfully completed.
SQL> SELECT OBJECT_NAME
  2  FROM ALL_OBJECTS@test
  3  WHERE OWNER = :schema
  4      AND (
  5          OBJECT_TYPE = 'TABLE'
  6          OR OBJECT_TYPE = 'VIEW'
  7          OR OBJECT_TYPE = 'SYNONYM'
  8      )
  9  ORDER BY OBJECT_NAME
 10  /
OBJECT_NAME
------------------------------------------------------------
BONUS
DEPT
EMP
EMP_VIEW
SALGRADE

设法解决了这个问题。事实证明,这只是我对变量绑定工作方式的误解。我想我可以在查询中绑定任何我想绑定的内容。事实证明你不能:P

我修改了我的查询如下:

SELECT OBJECT_NAME
FROM ALL_OBJECTS@<HARDCODED DB NAME HERE>
WHERE OWNER = :schema
AND (
    OBJECT_TYPE = 'TABLE'
    OR OBJECT_TYPE = 'VIEW'
    OR OBJECT_TYPE = 'SYNONYM'
)
ORDER BY OBJECT_NAME;

一切都很完美!

相关内容

  • 没有找到相关文章

最新更新