1

I have a company table with list of companies name and company id.

Now there is a Value table which hold information about the company with reference to company id.

I need to first get the list and size of the companies and for all the companies insert a particular feature information in the Value table.

This means I need to have all companies having those features in the Value table.

I tried to use the below SQL which gives a compilation error. But the for loop works well without the insert.

DECLARE
  x NUMBER(2) ;
BEGIN 
    FOR x IN (select distinct company_num from company where comp_IN_comp='T') LOOP
       INSERT INTO VALUE (PROPERTY_NUM, DATA_GROUP, NUM_UPDATES, 
        CREATED_DATE, CREATED_BY, LAST_UPDATED_DATE, LAST_UPDATED_BY, VALUE) VALUES 
        ('78', x ,'0', TO_DATE('2015-12-17 00:00:00', 'YYYY-MM-DD HH24:MI:SS'), 
        'ADMIN', TO_DATE('2015-12-17 00:00:00', 'YYYY-MM-DD HH24:MI:SS'), 'ADMIN', 'N');
    END LOOP;
END;
4
  • Could you post the compile error? Commented Jan 5, 2016 at 22:09
  • What RDBMS is this for? Please add a relevant tag - oracle, sql-server, mysql, postgresql - or whatever else you might be using Commented Jan 5, 2016 at 22:10
  • This Oracle 11g enterpise edition Commented Jan 5, 2016 at 22:11
  • Error:Error report - ORA-06550: line 5, column 174: PLS-00382: expression is of wrong type 06550. 00000 - "line %s, column %s:\n%s" *Cause: Usually a PL/SQL compilation error. *Action: Commented Jan 5, 2016 at 22:11

1 Answer 1

2

You don't need a loop for this - just use an insert-select statement:

INSERT INTO VALUE (PROPERTY_NUM, 
                   DATA_GROUP, 
                   NUM_UPDATES, 
                   CREATED_DATE, 
                   CREATED_BY, 
                   LAST_UPDATED_DATE,
                   LAST_UPDATED_BY,
                   VALUE)
SELECT             DISTINCT '78',
                   company_num,
                   '0',
                   TO_DATE('2015-12-17 00:00:00', 'YYYY-MM-DD HH24:MI:SS'),
                   'ADMIN',
                   TO_DATE('2015-12-17 00:00:00', 'YYYY-MM-DD HH24:MI:SS'),
                   'ADMIN',
                   'N'
FROM               company
WHERE              comp_in_comp='T'
Sign up to request clarification or add additional context in comments.

3 Comments

so , if there are 10 companies all the 10 companies will get the features added in the value table ?
This is the best way to do it but it's worth noting the original error was the the INSERT referenced x when it should have used x.company_num. The cursor column must be referenced even if there's only one column.
So, I case if some of the rows already exist how do we update these rows.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.