0

I am trying to insert some data into a table from a select statement. I know I can do it like this:

insert into new_logs (idLog, logEntry)
(select idLog, logEntry from old_logs)

But, I am running into a problem when trying to execute this type of query when I need to pass in a sequence value:

insert into new_logs (idLog, logEntry)
(select LOGSEQ.NEXTVAL, logEntry from old_logs) 

I think the problem is because the sequence comes from the dual table, but the query above implies that it comes from the old_logs table.

I also tried this,

insert into new_logs (idLog, logEntry)
select next_value for LOGSEQ, logEntry from old_logs

But I still can't get it to work. Could someone please tell me if what I am trying to do is possible? All I want to do is run an insert statement using a select query and a sequence on another schema.

3
  • It's always helpful to specify what error you are getting rather than hoping that we can guess correctly. Are you saying that logseq is a sequence that is owned by a user other than the one you are running the INSERT statement as? Does your user have permission to use the sequence? If so, you'd need a fully qualified object name unless you are creating synonyms for the sequence. Commented Oct 22, 2013 at 16:05
  • It should work. what error do you get. Sequence does not come from any table. It is an independent object. Commented Oct 22, 2013 at 16:05
  • The error said "sequence number not allowed here", but I rewrote the query from scratch and it worked. I guess what I typed here did not match what I was running, so I apologize Commented Oct 23, 2013 at 15:44

2 Answers 2

1

your query insert into new_logs (idLog, logEntry) (select LOGSEQ.NEXTVAL, logEntry from old_logs) might give error if u have duplicate logentry field in old_logs.

try this:-

    insert into new_logs (idLog, logEntry)
select LOGSEQ.NEXTVAL, logEntry from (select distinct logEntry  from old_logs);
Sign up to request clarification or add additional context in comments.

Comments

0

Your query is correct, as shown below:

SQL> CREATE TABLE old_logs AS
  2     SELECT ROWNUM idLog, 'a' logEntry FROM dual CONNECT BY LEVEL <= 10;

Table created

SQL> CREATE TABLE new_logs AS
  2     SELECT * FROM old_logs WHERE 1 = 2;

Table created

SQL> CREATE SEQUENCE logseq;

Sequence created

SQL> INSERT INTO new_logs (idLog, logEntry)
  2  (SELECT LOGSEQ.NEXTVAL, logEntry FROM old_logs);

10 rows inserted

What error message exactly do you get?

1 Comment

I rec'd the following error: "sequence number not allowed here", but I decided to rewrite the query from scratch and it worked. I guess my syntax did not match what I typed here, I apologize

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.