简体   繁体   English

SQL Server:多输出子句

[英]SQL Server: Multiple Output Clauses

I have two tables, Table_1 and Table_2 . 我有两个表, Table_1Table_2

Table_1 has columns PK (autoincrementing int ) and Value ( nchar(10) ). Table_1包含列PK (自动增量int )和Valuenchar(10) )。

Table_2 has FK ( int ), Key ( nchar(10) ) and Value ( nchar(10) ). Table_2FKint ), Keynchar(10) )和Valuenchar(10) )。

That is to say, Table_1 is a table of data and Table_2 is a key-value store where one row in Table_1 may correspond to 0, 1 or more keys and values in Table_2 . 也就是说, Table_1是数据的一个表,并Table_2是一个键值存储其中在一个行Table_1可以对应于0,1或更多个键和值在Table_2

I'd like to write code that programmatically builds up a query that inserts one row into Table_1 and a variable number of rows into Table_2 using the primary key from Table_1 . 我想编写代码,以编程方式构建一个查询,使用Table_2中的主键将一行插入Table_1 ,将可变数量的行插入Table_1

I can do it easy with one row: 我可以用一行轻松完成:

INSERT INTO Table_1 ([Value])
OUTPUT INSERTED.PK, 'Test1Key', 'Test1Val' INTO Table_2 (FK, [Key], [Value])
VALUES ('Test')

But SQL doesn't seem to like the idea of having multiple rows. 但SQL似乎不喜欢有多行的想法。 This fails: 这失败了:

INSERT INTO Table_1 ([Value])
OUTPUT INSERTED.PK, 'Test1Key', 'Test1Val' INTO Table_2 (FK, [Key], [Value])
OUTPUT INSERTED.PK, 'Test2Key', 'Test2Val' INTO Table_2 (FK, [Key], [Value])
OUTPUT INSERTED.PK, 'Test3Key', 'Test3Val' INTO Table_2 (FK, [Key], [Value])
VALUES ('Test')

Is there any way to make this work? 有没有办法让这项工作?

I had to put the code in answer, in comment it looks ugly... 我不得不把代码放在答案中,在评论中看起来很难看......

CREATE TABLE #Tmp(PK int, value nchar(10))

INSERT INTO Table_1 ([Value])
OUTPUT INSERTED.PK, inserted.[Value] INTO #Tmp
SELECT 'Test'

INSERT INTO Table_2 (FK, [Key], Value)
SELECT PK, 'Test1Key', 'Test1Val' FROM #Tmp
UNION ALL SELECT PK, 'Test2Key', 'Test2Val' FROM #Tmp
UNION ALL SELECT PK, 'Test3Key', 'Test3Val' FROM #Tmp

Btw, SQL Server won't let you do it all in one query without some ugly hack... 顺便说一句,SQL Server不会让你在一个查询中完成所有操作而没有一些丑陋的黑客...

尝试将INSERTED.PK值放入参数,然后使用3 INSERT..VALUES或1 INSERT..SELECT语句插入表2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM