gpt4 book ai didi

sql - While 循环从 select 语句插入

转载 作者:行者123 更新时间:2023-12-02 02:00:40 25 4
gpt4 key购买 nike

我需要在我的数据库中创建父子表。我的子表已经存在很长时间了,所以它包含一长串记录。我想做的是将 child 的名字复制到我的 parent 表中。

子表

---------------ChildID | ChildNm---------------1        |A2        |B3        |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

这是最好的方法吗?

最佳答案

我认为不需要循环,我很少这样做。

也许可以尝试这样的事情:

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

select * from parent

我不确定你想要什么作为 parent 的名字

*我假设您的父表看起来像这样:

create table parent(ParentID int identity(1,1), ParentNm char(1), ChildNm char(1))

关于sql - While 循环从 select 语句插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17420210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com