我的查询很简单,但PL/SQL
代码块需要'INTO'
语句。
这是我的问题:
DECLARE
yesterdays_date DATE := SYSDATE-1;
start_date DATE :='01/JAN/2013';
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE P2P_DATA';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
--if table not found DO NOTHING AND MOVE ON
--dbms_output.put_line('HELLO');
NULL;
END IF;
---------------------------create new table here-------------------
CREATE TABLE P2P_DATA AS
SELECT
GM_NAME,
NEW_SKILL,
WEEK_DATE,
TOR_MWF
FROM TEST_TABLE
WHERE WEEK_DATE BETWEEN start_date AND yesterdays_date;
END;
它给出了COMPILE时间错误:
FOUND CREATE: EXPECTING END SELECT or (BEGIN CASE CLOSE CONTINUE DECLARE ... ETC)
我只是在声明块中设置日期,然后根据select
语句创建一个新表。任何想法如何完成这项任务?
答案 0 :(得分:3)
这可以做同样的事情,但避免了创建和删除表的执行立即和开销。
DECLARE
yesterdays_date DATE := SYSDATE-1;
start_date DATE :='01/JAN/2013';
BEGIN
--clear out old data------
DELETE from P2P_DATA;
---------------------------insert new data here-----------------
INSERT INTO P2P_DATA
SELECT
GM_NAME,
CASE WHEN SUBSTR(CST_NAME,0,5) = 'A'
THEN 'BVG1' ELSE SUBSTR(CST_NAME,0,5) END AS CST_NAME,
NEW_SKILL,
WEEK_DATE,
TOR_MWF,
TOR_MA,
TOR_DL
FROM TEST_TABLE
WHERE WEEK_DATE BETWEEN start_date AND yesterdays_date;
END;
- 在事务之外进行提交,以防万一
更好的方法是创建一个视图,并在你想要的只是一个子集时避免使用整个表格。
CREATE VIEW VW_P2P_DATA
AS
SELECT
GM_NAME,
CASE WHEN SUBSTR(CST_NAME,0,5) = 'A'
THEN 'BVG1' ELSE SUBSTR(CST_NAME,0,5) END AS CST_NAME,
NEW_SKILL,
WEEK_DATE,
TOR_MWF,
TOR_MA,
TOR_DL
FROM TEST_TABLE
WHERE WEEK_DATE BETWEEN TO_DATE('01/JAN/2013','DD/MON/YYYY') AND SYSDATE-1;
答案 1 :(得分:1)
您无法在PL / SQL块中执行DDL查询;如果你需要这样做,你必须使用dinamic SQL;例如,您可以使用:
execute immediate '
CREATE TABLE P2P_DATA AS
SELECT
GM_NAME,
NEW_SKILL,
WEEK_DATE,
TOR_MWF
FROM TEST_TABLE
WHERE WEEK_DATE BETWEEN start_date AND yesterdays_date;
';
但是,如果可以,请考虑与动态创建/删除表不同的解决方案
答案 2 :(得分:1)
实际上,我会把它作为答案而不是评论......
我建议完全避免使用PL / SQL ...只需执行以下操作:
truncate table P2P_DATA;
insert into P2P_DATA
SELECT
GM_NAME,
NEW_SKILL,
WEEK_DATE,
TOR_MWF
FROM TEST_TABLE
WHERE WEEK_DATE BETWEEN to_date('01/JAN/2013','dd/MON/yyyy') AND SYSDATE-1;
更简单,更清洁,更快捷。 ;)