[英]Get the new record primary key ID from SQL insert query to insert same value into another table?
我有以下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
我希望能夠獲取this的值並將其插入到查找表中的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的答案修改了我的代碼,但它似乎沒有用。 如果有人可以就我可能出錯的地方提出建議,我們將不勝感激。
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)"
如果我沒弄錯,你必須將team_identity聲明為cmd.parameter。 當然沒有傳遞進入它的參數c#仍然期待一個
cmd.paramater.addwithvalue("@team_identity", paramaterDirection.out);
或類似的東西
插入一個行后, teams
表中,填寫下列代碼來獲得認同的當前值和使用它插入到時sprints_vs_teams
表。
SqlCommand cmd=new SqlCommand("select Ident_current('teams')",Cn);
Cn.Open();
int teamid=int.Parse(Cmd.ExecuteScalar().ToString());
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.