【问题标题】:Sql Server Insert query Into multiple tables from temporary tablesSql Server将查询插入临时表中的多个表
【发布时间】:2015-05-11 14:19:31
【问题描述】:

我有两张表,一张是主表,一张是明细表,明细表包含主表ID作为参考

这是我的桌子

**Table_Customer**  
CustomerId  CustomerName
1           A
2           B

**Table_CustomerRelatives**         
RelativesId  CustomerId     RelativesName   Address
1                  1                M        xyz
2                  1                N        mno
3                  2                L        pqr
4                  2                O        ghy

这里 CustomerId 和 RelativesId 是标识列,因此会自动生成列值

这里有两个临时表,例如

**TembreryTableCustomer**   
CustomerId  CustomerName
1               F
2               G
3               H

**TembreryTableDetails**        
CustomerId  RelativesName   Address
1              S             fgg
1              T             dfg
2              U             ghj
3              V             jkl
3              W             rty

如何将临时表数据插入到我的带有身份的表中。 在这里我想插入临时表客户的行并获取身份值,然后使用临时表客户身份插入临时表详细信息。

【问题讨论】:

  • 看看SQL中的SCOPE_IDENTITY

标签: sql-server


【解决方案1】:

您可以使用merge 语句的output 子句来构建临时客户ID 到新ID 的映射。

declare @Map table (Old int, New int);

;merge  Table_Customer dest
using   TembreryTableCustomer src
on      dest.CustomerName = src.CustomerName
when    not matched then
        insert (CustomerName) values (CustomerName)
output  inserted.CustomerID, src.CustomerID
into    @map;

insert  Table_CustomerRelatives
        (CustomerId, RelativesName, Address)
select  m.New
,       t.RelativesName
,       t.Address
from    TembreryTable2 t
join    @Map m
on      t.CustomerID = m.Old;

Example at SQL Fiddle.

【讨论】:

    【解决方案2】:

    根据 SQL 的版本和您对工作位置的偏好,有多种方法。

    我发现使用sequences 比使用标识列容易得多。您可以在临时表中使用与持久表中相同的序列,因此无需进行“修复”。

    除此之外,您可以使用 output 子句插入到持久表中以捕获新分配的 ID。从链接中,查看示例“E”。显着的特点是在临时表 ID 旁边输出持久 ID。

    【讨论】:

    • 您不能使用insert 语句的output 子句来获取临时表ID。试试看。
    • Aw crud - 这就是我随便回答的结果! @Andomar,你当然是对的。
    猜你喜欢
    • 2015-11-26
    • 2016-03-20
    • 2011-02-05
    • 2011-08-21
    • 1970-01-01
    • 2015-11-12
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多