动态sql / query:SELECT中的撇号

时间:2014-09-04 09:44:10

标签: sql oracle plsql

所以我有问题,有一个变量,可能包含不同的列名  然后在SELECT中我想将列与特定单词进行比较。 但后来似乎撇号会产生问题:

query := 'SELECT value FROM table WHERE ' || variable || ' like ''word''';
EXECUTE IMMEDIATE query INTO rec;
  EXCEPTION WHEN OTHERS THEN htp.p(dbms_utility.format_error_stack);

2 个答案:

答案 0 :(得分:1)

SQL> set serveroutput on;
SQL> DECLARE
  2    VAR   VARCHAR2(20);
  3    REC   NUMBER;
  4    query VARCHAR2(1000);
  5  BEGIN
  6    var   := 'TABLE_NAME';
  7    QUERY := 'SELECT count(*) FROM USER_TABLES WHERE ' || VAR || ' like ''%EMP%''';
  8    dbms_output.put_line(query);
  9    EXECUTE IMMEDIATE QUERY INTO REC;
 10    dbms_output.put_line(rec);
 11  END;
 12  /
SELECT count(*) FROM USER_TABLES WHERE TABLE_NAME like '%EMP%'
1

PL/SQL procedure successfully completed.

使用REC作为集合类型:

SQL> DECLARE
  2      var   VARCHAR2(20);
  3      TYPE rec_typ
  4        IS TABLE OF user_tables%ROWTYPE;
  5      rec   REC_TYP;
  6      query VARCHAR2(1000);
  7  BEGIN
  8      var := 'TABLE_NAME';
  9
 10      query := 'SELECT * FROM USER_TABLES WHERE '
 11               || var
 12               || ' like ''%EMP%''';
 13
 14      dbms_output.Put_line(query);
 15
 16      EXECUTE IMMEDIATE query bulk collect INTO rec;
 17
 18      FOR i IN 1..rec.count LOOP
 19          dbms_output.Put_line(Rec(i).table_name);
 20      END LOOP;
 21  END;
 22  /
SELECT * FROM USER_TABLES WHERE TABLE_NAME like '%EMP%'
EMP

PL/SQL procedure successfully completed.

答案 1 :(得分:0)

如果您要在相等word的列中搜索值,请将like更改为=
如果您要在包含 word的列中搜索值,请将like ''word''更改为like ''%word%''(不要忘记第三个撇号& #39;关闭动态查询)。