【问题标题】:While Loop insert from select statement从 select 语句插入 while 循环
【发布时间】:2013-07-02 07:49:43
【问题描述】:

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

子表

--------------- 孩子ID | ChildNm --------------- 1 |一个 2 |乙 3 |C

父表

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

查询

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

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

这是最好的方法吗?

【问题讨论】:

  • 如果每个父母有多个孩子怎么办?父表只允许每个父级有一个 ChildNm。此外,您可以通过视图和 JOIN 使其 look 相同
  • 是的,该表允许多个子表,但目前的要求是为每个子表插入一个父表,因为父表是新表~

标签: sql sql-server sql-server-2008 tsql


【解决方案1】:

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

不妨试试这样的:

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

select * from parent

我不确定你想要什么样的父母名字

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

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

【讨论】:

    【解决方案2】:

    从架构上讲,这个表关系不好,完全违法。

    我不知道你想用这个实现解决什么目的。

    根据好的方法和实践,您需要在子表中添加一列“ParentId”。

    您可以针对每个孩子设置父 ID。我不确定你将如何决定这个 clild 属于哪个父级。

    我建议先重新考虑您的方法。

    顺便说一句,您可以使用批量插入查询在父表中插入值,例如:

       insert into parents (childnm) select  ChildNm from Child group by ChildNm
    

    【讨论】:

      猜你喜欢
      • 2012-12-16
      • 2017-05-02
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      相关资源
      最近更新 更多