我想請問一下我有一段SQL
for result in(
select * from tableA
where Dt <= '2021/10/18' AND Dt >'2021/10/17'
)loop
假設今天是10/18我想取這10天的區間會產生這樣的語法
for result in(
select * from tableA
where Dt <= '2021/10/18' AND Dt >'2021/10/17'
)loop
for result in(
select * from tableA
where Dt <= '2021/10/16' AND Dt >'2021/10/15'
)loop
for result in(
select * from tableA
where Dt <= '2021/10/14' AND Dt >'2021/10/13'
)loop
for result in(
select * from tableA
where Dt <= '2021/10/12' AND Dt >'2021/10/11'
)loop
for result in(
select * from tableA
where Dt <= '2021/10/10' AND Dt >'2021/10/09'
)loop
for result in(
select * from tableA
where Dt <= '2021/10/08' AND Dt >'2021/10/07'
)loop
類似迴圈的寫法
只是我不清楚怎麼寫,所以想請問各位該如何調整呢?
DECLARE
CURSOR c_tableA IS
SELECT *
FROM tableA
WHERE Dt <= TO_DATE('2021/10/18', 'yyyy/mm/dd') AND Dt > TO_DATE('2021/10/07', 'yyyy/mm/dd');
r_tableA tableA%ROWTYPE;
BEGIN
OPEN c_tableA;
LOOP
FETCH c_tableA INTO r_tableA;
EXIT WHEN c_tableA%NOTFOUND;
-- 處理資料
END LOOP;
CLOSE c_tableA;
END;
https://blogs.oracle.com/connect/post/working-with-cursors
你又改了? Oracle 的 SQL 與 PL/SQL 是分開的,不像SQL Server 是一起叫T-SQL.
你先用個 for in () , 後面又變成N個 for in.
其實取日期區間資料,不難,但你要能夠說清楚目的,table的結構,範例資料,想要的結果.
而不是問語法. SQL 思考方式與程序語言不同. Oracle 有 start with connect by
語法,就可以產生序列了,也可以用遞回 CTE方式.
如果是要用日期分,可以用 trunc()函數
https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/TRUNC-date.html#GUID-BC82227A-2698-4EC8-8C1A-ABECC64B0E79