将选定的多个记录从现有表中插入到具有其他值的表中

时间:2014-12-02 10:50:21

标签: sql sql-server insert bulkinsert

我的第一张桌子是这样的

选民

userID  | lgDiv 
--------------------
   1     |   3
   2     |   4
   3     |   6
   4     |   3
   5     |   3

在我的第二个表格中,userIDelecID都是主键

VoterElection

voterID | elecID | voterType| votingStatus
--------------
   1      |  1   | Normal  | Active
   2      |  1   | Normal  | Active
   3      |  3   | Normal  | Active

我想将一些选定的Voter表行插入VoterElection表,其中包含electID,voterTypevotingStatuselectionID, voterTypevotingStatus与Votertable中所有选定项的值相同。

Voter表的

userID将是VoterElection表的voterID。

此外假设我选择lgDiv为3的所有用户

        SELECT userID FROM Voter WHERE lgDiv=3 ;

根据我在这里提供的数据,它将选择3条记录。

我想用elecID,voterType和votingStatus将我从Voter选择的所有三条记录插入到VoterElection中。对于所有记录elecID,voterType和投票状态将是相同的。

假设我选择了elecID = 3 voterType ='正常'和votingStatus =' Active'所有三个记录。 插入后应该看起来像这样。

VoterElection

voterID | elecID | voterType | votingStatus
--------------------------------------------
   1    |  1     | Normal    | Active
   4    |  1     | Normal    | Active
   5    |  1     | Normal    | Active

这是我可以通过搜索获取​​的内容

INSERT INTO VoterElection (voterID)
   SELECT userID  
   FROM Voter 
   WHERE lgDiv = 3;

如何添加elecId, voterTypevotingStatus

1 个答案:

答案 0 :(得分:2)

您只需在SELECT INTO中添加值:

INSERT INTO VoterElection (voterID, elecID, voterType, votingStatus)
     SELECT userID, 1, 'Normal', 'Active' FROM Voter WHERE lgDiv=3;

您可以将值1,'正常','有效'更改为您想要的任何内容。