gpt4 book ai didi

c# - 从 SQL 插入查询中获取新记录主键 ID 以将相同的值插入另一个表?

转载 作者:太空狗 更新时间:2023-10-29 23:21:28 25 4
gpt4 key购买 nike

我有以下 C#

protected void add_button_Click(object sender, EventArgs e)
{
string teamname = team_name_tb.Text;
string teamstatus = "Not Started";
string teamnotes = team_notes_tb.Text;
string sprintid = sprint_select.SelectedValue;

string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(ConnectionString);

myConnection.Open();

String query = "INSERT INTO teams (team_name, status, notes)
VALUES (@team_name, @status, @notes);
INSERT INTO sprints_vs_teams (sprint_id, team_id)
VALUES (@sprint_id, @team_id)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@team_name", teamname);
myCommand.Parameters.AddWithValue("@status", teamstatus);
myCommand.Parameters.AddWithValue("@notes", teamnotes);
myCommand.Parameters.AddWithValue("@sprint_id", sprintid);
myCommand.Parameters.AddWithValue("@team_id", ????);

myCommand.ExecuteNonQuery();
myConnection.Close();
}

teams 表中,主键是 team_id 我希望能够提取它的值并将其插入到 team_id查找表中的字段我有 sprints_vs_teams。有没有一种方法可以做到这一点,如果可以,您能否为我提供一些指导,请注意我是 C# 的新手。任何帮助将不胜感激。

修改后的代码

protected void add_button_Click(object sender, EventArgs e)
{
String user = Session["user_id"].ToString();
string teamname = team_name_tb.Text;
string teamstatus = "Not Started";
string teamnotes = team_notes_tb.Text;
string sprintid = sprint_select.SelectedValue;

string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(ConnectionString);

myConnection.Open();

String query = "Declare @team_identity int INSERT INTO teams (team_name, status, notes) VALUES (@team_name, @status, @notes); set @team_identity = scope_identity() INSERT INTO sprints_vs_teams (sprint_id, team_id) VALUES (@sprint_id, @team_identity)";

SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@team_name", teamname);
myCommand.Parameters.AddWithValue("@status", teamstatus);
myCommand.Parameters.AddWithValue("@notes", teamnotes);
myCommand.Parameters.AddWithValue("@sprint_id", sprintid);

myCommand.ExecuteNonQuery();
myConnection.Close();
}

我用@Sick 的回答修改了我的代码,但它似乎没有用。如果有人可以就我可能出错的地方提出建议,将不胜感激。

最佳答案

使用SCOPE_IDENTITY

Declare @team_identity int

INSERT INTO teams (team_name, status, notes)
VALUES (@team_name, @status, @notes);

set @team_identity = scope_identity()

INSERT INTO sprints_vs_teams (sprint_id, team_id)
VALUES (@sprint_id, @team_identity)"

关于c# - 从 SQL 插入查询中获取新记录主键 ID 以将相同的值插入另一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com