2

I'm trying to populate a database with certain values, based on a query stored within another table.

Table1:

ID      SQL                                         Title
1       select ID from userTable where ID = 1       Query 1
2       select ID from userTable where ID > 7       Query 2

I basically need to grab the 'SQL' field, and populate another table with information from the above, once the script has run it'll look something like:

ID      userID      Title
1       1           Query 1
2       8           Query 2
2       9           Query 2
2       10          Query 2

And so on.

I hope that makes sense, I have absolutely no clue if it's possible - I've tried creating it as a procedure but I can't find anyway whatsoever to run the 'SQL' code from table 1 in the procedure.

Alternatively I will do it in PHP, though it'd be preferable to get this into SQL as it's easier to automate.

Thank you

1 Answer 1

3

This is an odd thing to be doing (I would query why) but this code should do it:

declare
  rc sys_refcursor;
  l_id table1.id%type;
begin
  for r_sql in (select id, sql, title from table1) loop
    open rc for r_sql.sql;
    loop
      fetch rc into l_id;
      exit when rc%notfound;
      insert into table2 (id, userid, title) values (r_sql.id, l_id, r_sql.title);
    end loop;
    close rc;
  end loop;
end;
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, you're a star - thank you so much, will try to implement this now (as for why, we're trying to populate a reminders/notification section just for certain people)

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.