【问题标题】:Getting the sequenced id of a row to be the foreign key of a row in another table in one query在一个查询中将一行的有序 id 作为另一表中一行的外键
【发布时间】:2017-08-30 18:19:43
【问题描述】:

数据库是 SQL Server 2012。

我应该在 Excel 文件中的两个表上添加一堆行。

我有桌子Customers

id | firstname | lastname
1  | John      | Doe
etc.

Customers 表有一个序列customers_seq 用于新行的 id。因为在插入时行数是未知的。如下:

    insert into Customers (id,firstname,lastname)
    values
    (next value for customers_seq, '2016-001', 'John', 'Doe'),
    (next value for customers_seq, '2016-002', 'Jane', 'Doe'),
    (next value for customers_seq, '2016-003', 'Steve', 'Waters'); 
-- tons of more customers --

这按预期工作。

我也有桌子Services

id | name | fk_Customers
1  | lunch| 2
etc.

现在,问题来了:

我应该 - 在我添加 Customers 行的同一个查询中 - 在添加到表 Customers 的每一行之后在表 Services 上添加一行,这样,序列生成的 @ Customers 行的 987654331@ 将成为添加到 Services 表的行上的列 fk_Customers 的值。

我在想这可能通过使用 TSQL 局部变量来实现。

所以,类似:

DECLARE @sequenceCreatedId bigint;  
SET @sequenceCreatedId = next value for customers_seq; 

insert into Customers (id,firstname,lastname)
values(@sequenceCreatedId, '2016-001', 'John', 'Doe')

insert into Services (id,name,fk_Customers)
values(next value for services_seq, someName, @sequenceCreatedId);

--And just repeat that whole thing. Setting that variable again and again--

SET @sequenceCreatedId = next value for customers_seq; 

insert into Customers (id,firstname,lastname)
values(@sequenceCreatedId, '2016-002', 'Jane', 'Doe')

insert into Services (id,name,fk_Customers)
values(next value for services_seq, anotherName, @sequenceCreatedId);

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: sql-server local-variables tsql-sequence


    【解决方案1】:

    当然,使用output clauseinserted 部分一次性获取所有这些:

    declare @customers table (
        id int not null identity(0, 1)
      , firstname nvarchar(100) not null
      , lastname nvarchar(100) not null
    );
    
    insert into @customers (firstname, lastname)
    output inserted.*
    values ('John', 'Doe')
         , ('Jane', 'Doe')
         , ('Steve', 'Waters');
    

    我的示例没有使用序列,但它的工作方式相同。请注意,这也适用于updatedelete;甚至可以同时使用deletedinserted 一次性获取新旧值:

    update a
       set a.FirstName = Convert(nvarchar(100), NewId())
    output deleted.FirstName as OldFirstName
         , inserted.FirstName as NewFirstName
    from @customers as a;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 2014-11-08
      • 2018-09-22
      相关资源
      最近更新 更多