我有一个查询ReportStartDate和ReportEndDate的查询,所以我想我会在PLSQL中使用变量。不知道我在这里缺少什么,但是我收到了一个错误:
CLEAR;
DECLARE
varReportStartDate Date := to_date('05/01/2010', 'mm/dd/yyyy');
varReportEndDate Date := to_date('05/31/2010', 'mm/dd/yyyy');
BEGIN
SELECT
'Value TYPE',
1 AS CountType1,
2 AS CountType2,
3 AS CountType3
FROM DUAL;
SELECT COUNT (*)
FROM CDR.MSRS_E_INADVCH
WHERE 1=1
AND ReportStartDate = varReportStartDate
AND ReportEndDate = varReportEndDate
;
END;
/
错误是:
Error starting at line 2 in command:
Error report:
ORA-06550: line 6, column 5:
PLS-00428: an INTO clause is expected in this SELECT statement
ORA-06550: line 8, column 5:
PLS-00428: an INTO clause is expected in this SELECT statement
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
*Action:
这在Toad以及SQL Developer中都会发生。
在WHERE子句中使用变量的正确方法是什么?
答案 0 :(得分:7)
您不能直接在PL / SQL块中使用SQL语句(除非您使用EXECUTE IMMEDIATE
)。需要将列提取到变量中(这是PL / SQL告诉您的PLS-00428: an INTO clause is expected in this SELECT statement
错误)。所以你必须重写你的陈述,如下所示。
SELECT
'Value TYPE',
1 AS CountType1,
2 AS CountType2,
3 AS CountType3
INTO
V_VALUE_TYPE,
V_CountType1,
V_CountType2,
V_CountType3
FROM DUAL;
SELECT COUNT(*)
INTO V_COUNT
FROM CDR.MSRS_E_INADVCH
WHERE 1=1
AND ReportStartDate = varReportStartDate
AND ReportEndDate = varReportEndDate
确保添加异常处理程序,因为PL / SQL只需要返回1行。如果该语句没有返回任何行,则会遇到NO_DATA_FOUND
异常 - 如果该语句获取的行数过多,则会遇到TOO_MANY_ROWS
异常。
答案 1 :(得分:4)
您必须回答的问题是,您希望做所选择的数据是什么?
Sathya为您提供了一种方法 - 在PL / SQL块中声明变量并选择列INTO
这些变量。请注意,这要求SELECT语句只返回一行 - 任何更多或更少的行都将引发错误。另一种方法是使用BULK COLLECT选项声明集合类型:http://oracletoday.blogspot.com/2005/11/bulk-collect_15.html
另一个选择是让程序返回游标。这在调用代码期望能够获取过程所选数据的情况下非常有用:
PROCEDURE GET_MY_REPORT( varReportStartDate in date, varReportEndDate in date, cur out sys_refcursor) is
begin
OPEN cur FOR SELECT *
FROM CDR.MSRS_E_INADVCH
WHERE 1=1
AND ReportStartDate = varReportStartDate
AND ReportEndDate = varReportEndDate;
END GET_MY_REPORT;