I am making a table that contains the earnings for each month.
To do that I am using a for loop with an insert statement inside.
What I am having trouble with is converting the number into a month then into a char.
This is what my code looks like:
BEGIN
FOR i IN 1..12
LOOP
INSERT INTO REVENUE ( TO_CHAR(TO_DATE(i, 'MM'), 'MON') || '2009'
, select sum(transaction_amount)
but when I run this I get an error saying:
INSERT INTO REVENUE ( TO_CHAR(TO_DATE(i, 'MM'), 'MON') || '2009'
*
ERROR at line 4:
ORA-06550: line 4, column 31:
PL/SQL: ORA-00917: missing comma
What am I doing wrong here?
go-oleg is right, it isn't the concatenation that's the problem, it's that your syntax for the insert statement
is wrong. You are missing the values
keyword from the values clause:
BEGIN
FOR i IN 1..12
LOOP
INSERT INTO REVENUE VALUES ( TO_CHAR(TO_DATE(i, 'MM'), 'MON') || '2009'
, select sum(transaction_amount)
...
or ideally specify the column names you're inserting into:
BEGIN
FOR i IN 1..12
LOOP
INSERT INTO REVENUE ( <column1>, <column2> )
VALUES ( TO_CHAR(TO_DATE(i, 'MM'), 'MON') || '2009'
, select sum(transaction_amount)
...
Because you don't have the values
keyword the parser thinks that the parentheses are enclosing a column list, and it's therefore confused when it sees the next opening bracket from the to_char
- the error is against the bracket, which is char 31 if it starts with ma tab, which would also poibably explain why the asterisk marking the error position appears in slightly the wrong place. It's expecting a comma there as a delimiter in the column list. It apparently hasn't got as far as ecaluating whether 'to_char
' is a valid column name.
Actually the select you're using for the second value suggests you might be trying to,use the subquery version; depending on what else you're doing in the rest of that statement, you might want:
BEGIN
FOR i IN 1..12
LOOP
INSERT INTO REVENUE ( <column1>, <column2> )
SELECT TO_CHAR(TO_DATE(i, 'MM'), 'MON') || '2009'
, sum(transaction_amount)
FROM <some other table>
...
I suspect you could probably do that with a single insertnrather than a loop, but hard to be sure without seeing the whole thing.