sql - Inserting multiple records in database table using PK from another table -


i have db2 table "organization" holds organizations data including following columns

organization_id (pk), name, description 

some organizations deleted lot of "organization_id" (i.e. rows) doesn't exist anymore not continuous 1,2,3,4,5... more 1, 2, 5, 7, 11,12,21....

then there table "title" other data, , there organization_id organization table in fk.

now there data have insert organizations, title going shown of them in web app. in total there approximately 3000 records added.

if 1 one this:

insert title  (     name,      organization_id,      datetime_added,      added_by,      special_fl,      title_type_id )  values  (      'this new title',       xxxx,       current timestamp,       1,       1,       1 ); 

where xxxx represent "organization_id" should table "organization" insert existing organization_id. "organization_id" changing matching "organization_id" table "organization".

what best way it? checked several similar qustions none of them seems equal this? sql server 2008 insert while loop while loop answer interates on continuous ids, other answer assumes id autoincremented.

same here: how use sql loop insert rows database?

not sure 1 (as question not quite clear) inserting multiple records in table while loop

any advice on this? how should it?

if want row every organization record in title exact same data should work:

insert title  (     name,      organization_id,      datetime_added,      added_by,      special_fl,      title_type_id )  select      'this new title' name,      o.organization_id,     current timestamp datetime_added,      1 added_by,      1 special_fl,      1 title_type_id     organizations o ; 

you shouldn't need column aliases in select including readability , measure. https://www.ibm.com/support/knowledgecenter/ssw_i5_54/sqlp/rbafymultrow.htm

and measure in case process errors out or whatever... can insert record in title if organization_id , title not exist.

insert title  (     name,      organization_id,      datetime_added,      added_by,      special_fl,      title_type_id )  select      'this new title' name,      o.organization_id,     current timestamp datetime_added,      1 added_by,      1 special_fl,      1 title_type_id     organizations o     left join title t     on o.organization_id = t.organization_id     , t.name = 'this new title'     t.organization_id null ; 

Comments