用于调用存储过程以插入/更新数据库

时间:2016-12-21 11:25:13

标签: c# asp.net asp.net-mvc rest asp.net-web-api

我一直致力于创建接受输入参数的Web API,并调用存储过程传递我们收到的插入/更新数据库中的帐户表的输入参数。现在这很完美,但我的API还需要选择已更新/插入的记录并将其作为响应返回

   public class ProjectNameCreationController : ApiController
   {
    [HttpGet]
    public HttpResponseMessage Get(string Account)
    {
        if (string.IsNullOrEmpty(Account))
        {
            return Request.CreateResponse(new { error = "Input parameters cannot be Empty or NULL" });
        }
       string strcon = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
       SqlConnection DbConnection = new SqlConnection(strcon);
       DbConnection.Open();

       SqlCommand command = new SqlCommand("[dbo].[usp_InserUpadte]", DbConnection);
       command.CommandType = CommandType.StoredProcedure;

       //create type table
       DataTable table = new DataTable();
       table.Columns.Add("AccountID", typeof(string));
       table.Rows.Add(Account);

       SqlParameter parameter = command.Parameters.AddWithValue("@account_TT", table);
       parameter.SqlDbType = SqlDbType.Structured;
       parameter.TypeName = "account_TT";
       command.ExecuteNonQuery();

现在我不确定我们是否能够选择现在作为存储过程的一部分插入/更新的记录,或者我是否必须单独创建一个查询,如下所示

       string strQuery = "select AccountID,CounterSeq from Account where AccountID = @accountID ";
       var cmd = new SqlCommand(strQuery);
       cmd.Parameters.AddWithValue("@accountID",Account);

因为我必须在调用API时将响应作为AccountID-CounterSeq(例如:IT-1)返回,如http://localhost/api/ProjectNameCreation?Account=IT。我怎么处理这个。非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

您必须更改您的程序,如下所示,它将返回上次插入或更新的记录。

 **--for insert** 
    IF @StatementType = 'Insert'
    BEGIN
    insert into Account (first_name,last_name,salary,city) values( @first_name,  @last_name,  @salary, @city) 
    --below line to return last inserted record
    select * from Account where accountid= SCOPE_IDENTITY()
    END
    **--for Update** 
    IF @StatementType = 'Update'
    BEGIN
    UPDATE Account SET
                First_name =  @first_name, last_name = @last_name, salary = @salary,
                city = @city
          WHERE accountid= @accountid
    --below line to return last Updated record
    select * from account where accountid = @accountid