[英]Inserting a C# record into a table with multiple foreign keys in SQL Server
我有一个Players
表,一个Teams
表和一个TeamPlayers
表。 我想将不在TeamPlayers
表中的玩家分配给已经存在的团队。 我有一个下拉列表,显示在TeamPlayers
表中的球队,以及一个下拉列表,显示不在TeamPlayers
表中的TeamPlayers
。
这是TeamPlayers
表的结构:
CREATE TABLE TTeamPlayers
(
intTeamPlayerID INTEGER NOT NULL,
intTeamID INTEGER NOT NULL,
intPlayerID INTEGER NOT NULL,
CONSTRAINT TTeamPlayers_PK PRIMARY KEY (intTeamPlayerID)
)
在我的“提交”按钮中,我将包含将未分配的Player
并将其添加到TeamPlayers
表中的代码。 我不太确定该怎么做。我是一名学生,试图在全班学习,但不确定我是否使用C#来做到这一点。 任何人都可以帮忙。 以下是下拉列表的代码
private void PopulateDropDowns()
{
SqlConnection con = new SqlConnection("Data Source=itd2");
// Select Query.
string cmdText = "SELECT * FROM vPlayersThatsUnassigned";
// Providing information to SQL command object about which query to
// execute and from where to get database connection information.
SqlCommand cmd = new SqlCommand(cmdText, con);
//To check current state of the connection object. If it is closed open the connection
if (con.State == ConnectionState.Closed)
{
con.Open();
}
//ddlAgeGroup.DataSource = cmd.ExecuteReader();
ddlPlayers.DataTextField = "Players";
ddlPlayers.DataValueField = "intPlayerID";
ddlPlayers.DataBind();
con.Close();
ddlPlayers.Items.Insert(0, new ListItem("--Select an A Player--", "0"))
}
private void PopulateTeams()
{
SqlConnection con = new SqlConnection("Data Source=itd2");
// Select Query.
string cmdText = "SELECT * FROM vTeamsAssigned";
// Providing information to SQL command object about which query to
// execute and from where to get database connection information.
SqlCommand cmd = new SqlCommand(cmdText, con);
//To check current state of the connection object. If it is closed open the connection
if (con.State == ConnectionState.Closed)
{
con.Open();
}
ddlTeams.DataTextField = "strTeam";
ddlTeams.DataValueField = "intTeamID";
ddlTeams.DataBind();
con.Close();
ddlTeams.Items.Insert(0, new ListItem("--Select A Team --", "0"));
}
目前尚不清楚,如果您要查找执行此操作的确切sql或只是如何执行此操作的说明。
在这些类型的情况下,当您需要分配的列表/未分配的列表时,我将有2个sql方法将采用TeamID并返回这些人员。
我假设您有3张牌桌...玩家,球队,玩家团队(很多)。 PlayerTeam只会有一个玩家ID和一个TeamID。 您将需要通过@teamid将teamid作为参数传递给每个调用。
因此,对于那些已分配的典型sql看起来像这样...
Select * from Players p inner join PlayerTeams pt on pt.playerid = p.playerid where pt.teamid = @teamid
现在,要吸引不在团队中的球员要多得多。
Select * from Players where playerid not in (select playerid from playerteams where teamid = @teamid)
然后添加某人,只需将其插入到playerteam表中
Insert into playerteams (playerid, teamid) values (@playerid, @teamid)
如果您需要更多有关如何更好地执行SQL调用的代码,可以在这里轻松找到它,那么我就不用再赘述了。
要选择不在PlayerTeams中的玩家:
select p.*
from Players p
left join TeamPlayers tp on p.intPlayerID = tp.intPlayerID
Where tp.intPlayerID is null /*there is no record in TeamPlayers */
要选择TeamPlayers表中的球队:
select t.*
from Teams t
left join TeamPlayers tp on p.intTeamID = tp.intTeamID
当您处理Submit事件时,您将获得intPlayerID和intTeamID并插入值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.