Web API调用存储过程并返回Result

时间:2016-12-21 06:52:15

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

我正在创建一个Web API,它接受两个名为ACC的输入参数。创建一个存储过程以在SQL Server中插入或更新Account表。帐户表只有两个字段AccountID nvarchar(50)(primaryKey)和Cnt int

 CREATE PROCEDURE [dbo].[usp_InserUpadte] 
 @Account_TT AS Account_TT READONLY

 AS
 BEGIN
 SET NOCOUNT ON;

 BEGIN TRANSACTION;

 MERGE dbo.[Account] prj
 USING @Account_TT tt
 ON prj.AccountID = tt.AccountID
 WHEN MATCHED THEN UPDATE SET prj.Cnt = prj.Cnt+1
 WHEN NOT MATCHED THEN INSERT (AccountID,Cnt)
 VALUES (tt.AccountID, 1);

 COMMIT TRANSACTION;

现在我尝试连接到SQL服务器,不知道如何将存储过程调用到ASP.NET Web API应用程序中,并在其中传递帐户ID以创建或更新表格

namespace WebService.Controllers
{
public class CreationController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get(string ACC)
    {
        string strcon =  System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        SqlConnection DbConnection = new SqlConnection(strcon);

我知道我们可以像

一样直接调用查询
var strQuery = "SELECT * from ACCOUNT where ACC = :ACC"

但是不知道如何调用上面的存储过程并传递帐户值。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

这是完整的工作示例。 请看一下。

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(ACC);

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

答案 1 :(得分:1)

要调用存储过程,您需要使用SqlCommand这样的内容:

string strcon =  System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
using (var connection = new SqlConnection(strcon)) {
    using (var command = new SqlCommand("usp_InserUpadte", connection)) {
      command.CommandType = CommandType.StoredProcedure;
      command.Parameters.Add("@Account_TT ", SqlDbType.NVarChar).Value = ACC;
      command.Open();
      var reader = command.ExecuteReader();

      // Handle return data here
    }
  }