sql - 插入时,输出未插入但在连接表中的列

标签 sql sql-server sql-insert

我目前正在研究某种数据映射。假设我有以下三个表:

临时表

RUNID | DocId | Amount
E       7       50
C       6       12

Table1

T1ID | DocID | Amount
1      5       10
2      6       20
3      6       50

Table2

T2ID | RUNID | T1Id
1      B       1
2      C       2
3      D       3

In table Table1 and Table2 the columns T1ID and T2ID are identity columns that are populated automatically. What I want to do now is to insert the values from TemporaryTable into Table1 and save the value in column RunID from TemporaryTable and the newly generated T1ID to Table2

The resulting table should look like this:

Table1

T1ID | DocID | Amount
1      5       10
2      6       20
3      6       50
4      7       50
5      6       12

Table2

T2ID | RUNID | T1Id
1      B       1
2      C       2
3      D       3
4      E       4
5      C       5

I would like to do so with the help of the output statement. Something like this:

CREATE TABLE #map(T1ID, RUNID)
INSERT INTO Table1(DocId, Amount)
OUTPUT inserted.T1ID, t.RunId INTO #map 
SELECT t.DocId, t.Amount
FROM TemporaryTable t

这显然不起作用,因为我无法访问输出语句中的 t.RunId 。这怎么能做到呢?

最佳答案

您可以使用MERGE命令与一些始终为假的条件来模拟您的插入与OUTPUT

中可用的所有列
MERGE Table1 t1
USING TemporaryTable t
  ON 1=2
WHEN NOT MATCHED THEN
  INSERT (DocId, Amount)
  VALUES (t.DocId, t.Amount)
  OUTPUT inserted.T1ID, t.RunId 
  INTO #map ;

关于sql - 插入时,输出未插入但在连接表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45187127/

相关文章:

sql - 防止基于序号位置删除 SQL 查询中的行

sql-server - 重新部署包含 CLR 存储过程的 .NET 程序集

mysql - 在coldfusion函数中使用sql查询的正确方法是什么

android - ORMLite 使用 SQL 插入日期

sql - 为什么 Redshift 不需要物化 View 或索引?

sql - 如何获取有关 SQL Select 语句的信息

Python - 类型错误 : expecting string or bytes object

java - 如何构建具有多列的 CriteriaQuery 谓词 IN 子句?

C# Hash SHA256Managed 不等于 TSQL SHA2_256

sql - INSERT [...] ON CONFLICT 可以用于外键违规吗?