0

I am newbie to SQL.

I want to insert data into table using below for-loop query. But unable to identify the issue

declare
cursor mac is SELECT DISTINCT(MAC) FROM DEVICES;
cmd varchar2(200);
begin
for c in mac loop
cmd := 'INSERT INTO MAC VALUES(DEVICES_ID_SEQ.nextVal,'||c.MAC||',"ABC","123")';
execute immediate cmd;
end loop;
end;

For each MAC in existing table, I want to insert new record.

2
  • 1
    Don't use a cursor or PL/SQL if it's not needed, please! Look at Quassnoi's answer for something that is MUCH faster and MUCH less code. Learn to do things the set-based way using SQL. Commented Apr 29, 2013 at 9:42
  • 1
    And dynamic SQL is not needed for this case either. Commented Apr 29, 2013 at 9:45

1 Answer 1

7

You don't need a cursor for that.

Just run:

INSERT
INTO    mac
SELECT  DEVICES_ID_SEQ.nextval, mac, 'abc', 123
FROM    (
        SELECT  DISTINCT
                mac
        FROM    devices
        )
Sign up to request clarification or add additional context in comments.

1 Comment

Another great example of less is more. The OP 1) uses dynamic SQL (not needed); 2) probably has a bug with the MAC address being a string and therefore should be quoted in the dynamic SQL; 3) is somewhat susceptible to overflowing the string buffer of just 200 characters; 4) uses PL/SQL and a cursor where it's not needed anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.