【问题标题】:SQL Server insert with row N referencing the identity of the N - 1 row. Possible?SQL Server 插入第 N 行引用第 N - 1 行的标识。可能的?
【发布时间】:2012-03-19 17:56:02
【问题描述】:

我有一个 SQL Server 2008 数据库,其中包含这样的表(表 1):

ID    ParentID    Name
--    --------    ---
11    NULL        Foo
12    11          Bar
13    12          etc 

ID 用IDENTITY 声明。

我将值 FooBaretc 作为另一个表(表 2)中的行,我必须将它们插入表 1。

插入的值必须在 Table1 中的父子关系中,第 N 行的ParentID 列指向第 N-1 行的ID

是否可以用一条语句插入具有它们之间关系的值?

【问题讨论】:

  • 值列表是什么意思?
  • @Hogan:我有另一个表(Table2),其中包含以下行:Foo、Bar 等。我想在 Table1 中插入(使用 insert...select),但在 Table1 中我必须为这些值创建 ID-ParentId 关系。
  • table2中的paren子关系逻辑是什么?插入时一个可以按 ASC 排序,另一个可以按 DESC 排序。 ???

标签: sql sql-server sql-server-2008 insert identity


【解决方案1】:
-- Insert all names in first table
insert  Table1
        (Name)
select  Name
from    Table2

-- For each row in Table1,
-- Search for the matching row in Table2,
-- Then look up the "parent" row in Table2,
-- And back to Table1 for the "parent" id
update  t1
set     ParentID = t1_parent.ID
from    Table1 t1
join    Table2 t2
on      t1.Name = t2.name
cross apply
        (
        select  top 1 *
        from    Table2 t2_parent
        where   t2_parent.ID < t2.ID
        order by
                t2_parent.ID desc
        ) t2_parent
join    Table1 t1_parent
on      t1_parent.Name = t2_parent.Name

【讨论】:

    【解决方案2】:

    既然你问是否可以在一个声明中做到这一点,这里有一个答案。我不禁觉得,如果您提供更多信息,我会告诉您,无论您为此做什么,都应该以另一种方式解决。我很难找到这样做的充分理由。不管怎样,这是一种方法:

    我假设 Table1 具有 Id、ParentId 和 Name,而 Table2 具有 Id 和 Name(您说您从 Table2 中获得了名称 Foo、Bar 等)。我还假设你可以强加一些命令。

    CREATE TABLE #T
    (
        Id INT IDENTITY(1, 1)
        , ParentId INT
        , Name VARCHAR(100)
    )
    
    CREATE TABLE #T2
    (
        Id INT IDENTITY(1, 1)
        , Name VARCHAR(100)
    )
    
    INSERT #T2
    (
        Name
    )
    VALUES ('Foo'), ('Bar')
    
    INSERT #T
    (
        ParentId
        , Name
    )
    SELECT
        NULLIF(IDENT_CURRENT('#T')
        + ROW_NUMBER() OVER(ORDER BY T2.Name)
        - 2, (SELECT ISNULL(MIN(Id), 1) - 1 FROM #T))
        , T2.Name
    FROM #T2 T2
    
    SELECT * FROM #T
    
    DROP TABLE #T
    DROP TABLE #T2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      • 2011-03-30
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多