我使用简单的标准SQL查询从表中获取记录计数,我想将其存储在变量中,以便以后可以使用它。
原因是我的表格中包含大量数据,我不想再次使用以下查询。
select count(1) from mytable;
此外,我不想使用PL/SQL
,只需查找SQL
语句。
我尝试使用define关键字,但我无法在define变量中设置计数。
请建议如何将其存储在变量中。
示例:
DEFINE some_variable;
SELECT COUNT(1) into some_variable,sysdate as CLEANUP_START FROM TABLE_TEMP;
--offcourse this is not correct for simple sql statment.however i want to store it in variable.
DELETE from MY_TABLE where Primary_key in (select primary_key from TABLE_TEMP );
--around 10M records are deleting
SELECT sysdate as CLEANUP_END FROM dual;
---There are such 10 delete statments on different tables.
---Spool the deleted record in csv file.
spool output.csv
select 'RESULT' from dual;
---And at the last i want print the summary of the cleanup records.
select primary_key from TABLE_TEMP;
select some_variable||',Records is deleted from MY_TABLE' from DUAL;
spool off;
答案 0 :(得分:2)
不要使用替换变量;使用绑定变量。下面我将展示SQL * Plus的截图,以演示其工作原理。
我声明了cnt
类型的绑定变量number
。然后我使用匿名块(为了简洁和方便,我使用SQL * Plus exec
命令)来计算表中的行并将结果分配给:cnt
。 (我计算表all_objects
中的行,但我使用的表格无关紧要 - 从您需要计算的表中计算)。最后,我从dual
中选择此变量以显示其值,并显示如何在任何select
(以及任何其他SQL)语句中使用它。
SQL> variable cnt number
SQL> exec select count(*) into :cnt from all_objects
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.45
SQL> select :cnt from dual;
:CNT
----------
89814
1 row selected.
Elapsed: 00:00:00.00
SQL>