我有一个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语句,它使用“Systems”表中的潜在多条记录以及UsersSystemsAssoc
表中的一条特定记录来填充Users
表。在声明中,将为UsersID
提供一个变量。
例如,如果我想让Systems
表中的所有系统(但SysIndex
,而不是SysName
)与一个特定用户(JaneMDoe)一起填充 - 但是使用UsersIndex 125,而不是其他字段),那么我希望结果为:
表:UsersSystemsAssoc
UsersSystemsAssocID | UsersID | SysID
--------------------+---------+---------
5 | 125 | 178 <- New record
6 | 125 | 219 <- New record
7 | 125 | 226 <- New record
...
...
因此,UsersSystemsAssoc
表中的Systems
表中有一条新记录,表示SysIndex
表中的每条记录,但该记录会插入每条记录的UsersID
以及相同的UsersSystemsAssoc
每个记录中都有1}}。
从代码的角度来看,insert into UserSystemsAssoc (UsersID, SysID)
values ((select SysIndex from Systems), (select UsersIndex from Users where Username = 'JaneMDoe'))
表中永远不会存在与此插入冲突的现有记录,因此SQL语句不需要考虑这一点。
我尝试过以下几件事:
Insert into <table> (<field1>,<field2>)
select <field1>, <field2>
from <table2>
...但当然,这不起作用。
做类似
的事情User-Agent
...不起作用,因为插入不是全部来自同一个表.....
我不确定哪种语法适用于此。
感谢。