簡體   English   中英

SQL Server插入多個記錄,其中包括來自另一個表的多個記錄的一個字段和一個靜態值

[英]SQL Server insert of multiple records, of which consists of one field of multiple records from another table, and one static value

我有一個ASP.net站點連接到SQL Server數據庫。 在數據庫中,我有3個表(除其他外)需要完成某些工作。

有2個內容表和1個記錄關聯的表。 這是表的示例:

表:用戶

UsersIndex | Username     | FirstName | MiddleInitial | LastName
-----------+--------------+-----------+---------------+-----------
92         | MilliVAnilli | Milli     | V             | Anilli
96         | BobLSmith    | Bob       | L             | Smith
...
...

表:系統

SysIndex | SysName   | .... | ....
---------+-----------+------+------
178      | Computer1 | .... | ....
219      | Computer2 | .... | ....
226      | Computer3 | .... | ....
...
...

表:UsersSystemsAssoc

UsersSystemsAssocID | UsersID | SysID
--------------------+---------+--------
1                   | 92      | 178
2                   | 92      | 226
3                   | 96      | 178
4                   | 96      | 219
...
...

我需要的是一條多條SQL語句,該語句使用“系統”表中的多個記錄以及Users表中的一個特定記錄來填充UsersSystemsAssoc表。 在該語句中,將為UsersID提供一個變量。

例如,如果我要與一個特定用戶(JaneMDoe-但使用UsersIndex 125,而不是其他字段)一起填充Systems表中的所有Systems (但SysIndex ,而不是SysName ),那么我想要結果是這樣的:

表:UsersSystemsAssoc

UsersSystemsAssocID | UsersID | SysID
--------------------+---------+---------
5                   | 125     | 178       <- New record
6                   | 125     | 219       <- New record
7                   | 125     | 226       <- New record
...
...

因此,這里在UsersSystemsAssoc表中有一個針對Systems表中每個記錄的新記錄,但是該記錄將每個記錄的SysIndex以及相同的UsersID每個記錄中。

從代碼角度來看, UsersSystemsAssoc表中永遠不應存在與該插入沖突的記錄,因此SQL語句不需要考慮這一點。

我已經嘗試過一些方法,例如:

insert into UserSystemsAssoc (UsersID, SysID) 
values ((select SysIndex from Systems), (select UsersIndex from Users where Username = 'JaneMDoe')) 

...但是當然,這不起作用。

做類似的事情

Insert into <table> (<field1>,<field2>) 
    select <field1>, <field2> 
    from <table2>

...也不起作用,因為插入內容並非全部來自同一張表.....

我不確定哪種語法適合於此。

謝謝。

這仍然不是很清楚您要嘗試執行的操作,這是黑暗中的一槍。 我猜您想要這樣的東西。

declare @UserID int = ? --TheValueFromTheFrontEnd


insert UsersSystemAssoc
(
    UsersID
    , SysID
)
select @UserID
    , SysIndex
from Systems

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM