Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While Loop insert from select statement

I need to create parent child table in my DB. My child table is already existed for a long time, so it contained a long list of records. What i want to do it copy child name to my parents table.

Child Table

---------------
ChildID | ChildNm
---------------
1        |A
2        |B
3        |C

Parent Table

----------------
ParentID|ParentNm|ChildNm
----------------

Query

WHILE (
        SELECT Min(ChildID)
        FROM ChildTable
        ) <
    SELECT Max(ChildID)
    FROM ChildTable

BEGIN
    --INSERT every child NAME TO my parents TABLE
END

Is this the best possible way to do this?

like image 536
Low Chee Mun Avatar asked Jan 30 '26 16:01

Low Chee Mun


2 Answers

I don't see a need for loops, I rarely do.

Try something like this perhaps:

insert parent(ChildNm)
select distinct ChildNm from child c
where not exists (select 1 from parent where c.childNm = childNm)

select * from parent

I am not sure what you want as parent names

*I am assuming your parent table looks something like this:

create table parent(ParentID int identity(1,1), ParentNm char(1), ChildNm char(1))
like image 71
t-clausen.dk Avatar answered Feb 02 '26 11:02

t-clausen.dk


Architecture wise this table relationship is not good and completely against the law.

I don't know what purpose you want to solve using this implementation.

According to good approach and practice you need to Add a column "ParentId" in Child table.

And against the every child you can set the parent ID. I am not sure how you will decide that this clild blongs to which parent.

I would suggest to rethink about your approach first.

By the way you can use bulk insert query to insert value in parent table like:

   insert into parents (childnm) select  ChildNm from Child group by ChildNm
like image 24
Sandeep Kumar Avatar answered Feb 02 '26 11:02

Sandeep Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!