以下是与您的要求相对应的 UPDATE、INSERT 和 DELETE 命令:
update studentsubject
set mark = @mark
insert into [subject] (name)
values (@name);
insert into studentsubject (student_id, subject_id, mark)
values (1, @@identity, @mark)
declare @subject_id int;
select @subject_id = subject_id
from studentsubject
where id = @id;
delete from studentsubject
where id = @id;
delete from [subject]
where id = @subject_id
我建议您使用SqlDataAdapter执行更新,因为它可以根据 DataRow 的状态自动决定执行哪个操作。您只需要执行SqlDataAdapter.Update方法。当然,必须分配SqlDataAdapter.DeleteCommand、SqlDataAdapter.InsertCommand和SqlDataAdapter.UpdateCommand属性。
这是一个代码片段:
adapter.InsertCommand = connection.CreateCommand();
adapter.InsertCommand.CommandText = "insert into [subject] (name) values (@name); insert into studentsubject (student_id, subject_id, mark) values (1, @@identity, @mark)";
adapter.InsertCommand.Parameters.AddRange(new SqlParameter[] {
new SqlParameter("@name", SqlDbType.Char, 10, "name"),
new SqlParameter("@mark", SqlDbType.Int, 1, "mark")
});
adapter.UpdateCommand = connection.CreateCommand();
adapter.UpdateCommand.CommandText = "update studentsubject set mark = @mark";
adapter.UpdateCommand.Parameters.Add("@mark", SqlDbType.Int, 1, "mark");
adapter.DeleteCommand = connection.CreateCommand();
adapter.DeleteCommand.CommandText = "declare @subject_id int; select @subject_id = subject_id from studentsubject where id = @id; delete from studentsubject where id = @id; delete from [subject] where id = @subject_id";
adapter.DeleteCommand.Parameters.Add("@id", SqlDbType.Int, int.MaxValue, "id");