Sql server 使用mssql在一个有效的查询中插入到两个连接的表中

Sql server 使用mssql在一个有效的查询中插入到两个连接的表中,sql-server,join,sql-insert,Sql Server,Join,Sql Insert,我正在尝试将一些数据插入我的ms sql数据库(ms sql server 2012)中的两个不同表中 考虑以下两个表,其中包含有关投票及其选择的信息 +----------------+ | Polls | +----------------+ | pollID | The id of a poll (auto increment) | memberID | The id of the member, owning the poll | poll

我正在尝试将一些数据插入我的ms sql数据库(ms sql server 2012)中的两个不同表中

考虑以下两个表,其中包含有关投票及其选择的信息

+----------------+ 
|     Polls      |
+----------------+
| pollID         | The id of a poll (auto increment)
| memberID       | The id of the member, owning the poll
| pollTitle      | The title/question of the poll
| date           | The date of the poll
+----------------+

+----------------+ 
|  PollChoices   |
+----------------+
| pollChoiceID   | The id of a poll choice (auto increment)
| pollID         | The id of the poll, that include this choice
| pollChoice     | The name/title of the poll choice
+----------------+
如何进行查询,以最有效的方式插入数据? 我总是可以做两个查询,但我真的不知道如何用一个查询来完成

在本例中,我的主要问题之一是在插入pollchoices时获取投票id。。如何获取新插入的“pollID”(自动递增)并在同一查询中使用它

另外,是否有必要使用事务或存储过程(我在什么地方读过)


任何帮助都将不胜感激。

我认为你所做的是不可能的

我认为执行您描述的操作的最佳方法是将其包装到存储过程中。您可以使用获取先前添加的记录和事务的ID以及一个块,以确保执行两个insert查询或根本不执行任何查询

请尝试此查询

declare @npi int
INSERT INTO Polls (memberID, pollTitle, date)
 VALUES (@memberID, @pollTitle, @date)
set @npi=
(select top 1 PollId
from Polls
order by PollId desc)
INSERT INTO PollChoices(pollChoiceID, pollID, pollChoice )
   VALUES (@pollChoiceID, @npi, @pollChoice)

这太完美了!非常感谢你+1.虽然我不需要“创建过程”部分,但它的目的是什么?@user68621它的目的是创建一个存储过程(以防您需要这样的东西)。对于存储过程上的docu,请看一看我知道这可能是一个“noobish”问题,但是否可以在“提交事务”部分之后返回pollID作为结果集。是的,可以返回pollID的值:return@pollID应该有效。你不妨看看这里谢谢你的帮助。。但我似乎无法让它发挥作用。它没有归还任何东西。你能看出有什么问题吗
declare @npi int
INSERT INTO Polls (memberID, pollTitle, date)
 VALUES (@memberID, @pollTitle, @date)
set @npi=
(select top 1 PollId
from Polls
order by PollId desc)
INSERT INTO PollChoices(pollChoiceID, pollID, pollChoice )
   VALUES (@pollChoiceID, @npi, @pollChoice)