我有以下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
1}}。有没有这样做的方法,如果可以的话,你可以提供一些指导,请注意我对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的答案修改了我的代码,但它似乎没有用。如果有人可以就我可能出错的地方提出建议,我们将不胜感激。
答案 0 :(得分:4)
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)"
答案 1 :(得分:0)
如果我没弄错,你必须将team_identity声明为cmd.parameter。当然没有传递进入它的参数c#仍然期待一个
cmd.paramater.addwithvalue("@team_identity", paramaterDirection.out);
或类似的东西
答案 2 :(得分:0)
在teams
表中插入一行后,编写以下代码以获取身份的当前值,并在插入sprints_vs_teams
表时使用它。
SqlCommand cmd=new SqlCommand("select Ident_current('teams')",Cn);
Cn.Open();
int teamid=int.Parse(Cmd.ExecuteScalar().ToString());
希望有所帮助