使用execute Immediate删除查询

时间:2017-11-24 08:50:09

标签: sql oracle plsql oracle11g oracle-apex-5

我希望将varchar2转换为日期但是它出现错误给我解决方案

DECLARE
  ADATE VARCHAR2(100):='02/20/1981';
BEGIN
  EXECUTE IMMEDIATE 'DELETE FROM emp WHERE HIREDATE= '||to_char(to_date(ADATE,'mm/dd/yy'),'mm/dd/yy');
  DBMS_OUTPUT.PUT_LINE('DELETE');
END;

3 个答案:

答案 0 :(得分:1)

你可以用它。确保使用USING子句传递绑定变量以避免SQL注入。同样如@Kaushik所述,没有必要TO_CHAR

DECLARE
   ADATE   VARCHAR2 (100) := '02/20/1981';
BEGIN
   EXECUTE IMMEDIATE
         'DELETE FROM emp WHERE HIREDATE= TO_DATE(:ADATE, ''mm/dd/yyyy'')' using adate;

   DBMS_OUTPUT.PUT_LINE ('DELETE');
  COMMIT;
END;

答案 1 :(得分:1)

你也可以使用这个:

DECLARE
   ADATE   VARCHAR2 (100) := '02/20/1981';
BEGIN
   EXECUTE IMMEDIATE
         'DELETE FROM emp WHERE HIREDATE= :aDate' using TO_DATE(ADATE, 'mm/dd/yyyy');

   DBMS_OUTPUT.PUT_LINE ('DELETE');
  COMMIT;
END;

答案 2 :(得分:0)

您无需将其转换为TO_CHAR。引号必须正确并使用正确的日期格式。

DECLARE
  ADATE VARCHAR2(100):='02/20/1981';
BEGIN
  EXECUTE IMMEDIATE 'DELETE FROM emp WHERE HIREDATE=to_date('''||ADATE||''',''mm/dd/yyyy'')';
  DBMS_OUTPUT.PUT_LINE('DELETE');
END;

对于删除操作,您甚至不需要EXECUTE IMMEDIATE。像这样的一块就足够了。

DECLARE
  ADATE VARCHAR2(100):='02/20/1981';
BEGIN
  DELETE FROM emp WHERE HIREDATE=to_date(ADATE,'mm/dd/yyyy');
  DBMS_OUTPUT.PUT_LINE('DELETE');
END;