使用立即执行删除查询

delete query using execute Immediate

我想将 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;

您不需要将其转换为 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;

你可以用这个。确保使用 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;

你也可以使用这个:

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;