handle special characters in PL/SQL procedures.?

岁酱吖の 提交于 2019-12-25 18:28:05

问题


I'm using oracle 10g plsql procedures for inserting and listing, but if we have any special characters like ' (single quote ) and & etc. query fails. How to handle special characters in plsql?

before:

    lquery := 'select count(id) into lCount
                        From
                            dual
                        where
                            name = '||iName||'
                         and Id= '||iId

after:

     select into lCount
                        From
                            dual
                        where
                            Id= iId
                         and name = iName;

after changing the query its working fine. Problem is if we keep variable like name value inside single quotes some times query wont execute for special characters like ' , " etc after changing query its working fine.


回答1:


First how to handle a quote ' and an ampersand &:

SQL@xe> set define off
SQL@xe> select q'(foo's & bar's)' from dual;

Q'(FOO'S&BAR'
-------------
foo's & bar's

SQL@xe>

See also How do I ignore ampersands in a SQL script running from SQL Plus? and Text Literals for details of alternative quoting mechanism q''.

Second don't create SQL statements as strings but instead use PL/SQL Static SQL. Static SQL will handle the quoting automatically for you (and is also SQL injection safe). Like:

declare
  lCount number;
  iName varchar2(20) := q'(foo's & bar's)';
  iId number := 42;
begin
  select count(*) into lCount From dual where name = iName and Id= iId;
end;


来源:https://stackoverflow.com/questions/22808328/handle-special-characters-in-pl-sql-procedures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!