插入Via Output参数C#
本文关键字:参数 Output Via 插入 | 更新日期: 2023-09-27 17:58:46
我有一个表单,它会在单击时将数据发送到多个表,人,教育,经验,参考。
我如何将数据添加到多个表中,以便所有表中都有相同的个人ID,
我是新手,使用分层架构,所有数据库代码都在DAL中,)使用Asp 2.0
我想用一个插入Person的存储过程来完成这项工作,并为PersonID获取一个输出参数,但我不知道如何使用该输出参数来插入其他表。
我的样品COde就是这个
public virtual bool AddJobApplication(int JobID,string Name,string FatherName,string Phone,string Email,string Address,int AppID){
obj_db2.objCmd.CommandText = "AddApplication";
obj_db2.objCmd.CommandType = CommandType.StoredProcedure;
obj_db2.objCmd.Parameters.AddWithValue("JjobID", JobID);
obj_db2.objCmd.Parameters.AddWithValue("@Name", Name);
obj_db2.objCmd.Parameters.AddWithValue("@FName", FatherName);
obj_db2.objCmd.Parameters.AddWithValue("@Email", Email );
obj_db2.objCmd.Parameters.AddWithValue("@Address", Address);
obj_db2.objCmd.Parameters.AddWithValue("@Phone", Phone);
SqlParameter param = new SqlParameter("@AppID", AppID);
param.Direction = ParameterDirection.Output;
param.ParameterName = "@AppID";
param.DbType = DbType.Int32;
obj_db2.objCmd.Parameters.Add(param);
obj_db2.objCmd.ExecuteNonQuery();
}
我在DAL中有这个函数,我正在获取param作为输出参数,我知道我可以从代码后面访问这个AddJobApplication来输入表单信息,但不知道如何使用这个输出来插入,很抱歉,如果我的级别很低,但我需要帮助。
这实际上取决于已经建立的体系结构。
如果比较容易的话,您可能只需要返回新记录的标识,而不是使用输出参数:
INSERT INTO Person (
FirstName,
LastName
)
VALUES (
'James',
'Johnson'
)
SELECT @@IDENTITY --return the identifier of the new record
但是,如果要更新多个表,请确保所有这些都在单个事务的范围内完成。
存储过程是实现这一点的正确方法。有了存储过程,您就可以在insert方法中定义输出参数。
下面是一个示例,说明如何插入一篇博客文章,然后取回SQL创建的ID。
示例(插入博客文章):
public int InsertArticle(ArticleItem articleitem)
{
SqlParameter articleid = new SqlParameter(Parameters.ArticleID, SqlDbType.Int);
articleid.Direction = ParameterDirection.Output;
SqlHelper.ExecuteNonQuery(Conn, CommandType.StoredProcedure, INSERT_ARTICLE,
new SqlParameter(Parameters.Body, articleitem.Body),
new SqlParameter(Parameters.Category, articleitem.Category),
new SqlParameter(Parameters.ExpireDate, articleitem.ExpireDate),
new SqlParameter(Parameters.PublishDate, articleitem.PublishDate),
new SqlParameter(Parameters.Published, articleitem.Published),
new SqlParameter(Parameters.Section, articleitem.Section),
new SqlParameter(Parameters.Title, articleitem.Title),
articleid);
return (int)articleid.Value;
}
调用代码
public void InsertAllTheThings()
{
var articleId = InsertArticle(articleItem); //Insert an article, return the ID
//Once you have the id, use it as needed.
var data = new SomeAwesomeData();
data.ArticleID = articleId;
data.IsAwesome = true;
InsertSomeRelatedData(data);
}