Ho il seguente C#Ottieni il nuovo ID della chiave primaria del record dalla query di inserimento SQL per inserire lo stesso valore in un'altra tabella?
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();
}
Nella tabella teams
la chiave primaria è team_id
voglio essere in grado di tirare il valore di questo e di inserirlo nel campo team_id
nella tabella di ricerca che ho sprints_vs_teams
. Esiste un metodo per farlo, in tal caso potresti eventualmente fornirmi alcune indicazioni, per favore sappi che sono molto nuovo a C#. Qualsiasi aiuto sarebbe molto apprezzato.
codice Modificato
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();
}
ho modificato il mio codice con la risposta s' @Sick, tuttavia non sembra funzionare. Se qualcuno potesse consigliarmi su dove potrei aver sbagliato, sarebbe molto apprezzato.
Si prega di elaborare su "non mi sembrava a lavorare". Un errore? Nessun dato inserito? I dati errati inseriti? – AakashM