处理从存储过程Web API返回的记录

时间:2016-12-21 15:59:58

标签: c# sql-server asp.net-web-api

我有以下存储过程,插入/更新,并从表中选择看起来像

的记录
ALTER PROCEDURE [dbo].[usp_InserUpadte] 
    @account_TT AS account_TT READONLY
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRANSACTION;
        MERGE dbo.[clarity_Account] prj
        USING @account_TT tt ON prj.AccountID = tt.AccountID

        WHEN MATCHED THEN 
           UPDATE SET prj.CounterSeq = prj.CounterSeq+1

        WHEN NOT MATCHED THEN 
           INSERT (AccountID, CounterSeq)
           VALUES (tt.AccountID, 1);

        SELECT * 
        FROM dbo.[clarity_Account] ca 
        JOIN @account_TT TT ON ca.AccountID = TT.AccountID;

        COMMIT TRANSACTION;

我有调用存储过程的Web API代码,如下所示

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

这会更新/插入。但我不知道如何从API中的存储过程Select查询中获取记录。另外,我如何从返回的记录中提取AccountIDCounterSeq

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

首先,您需要使用command.ExecuteReader()而不是command.ExecuteNonQuery()ExecuteReader将返回SqlDataReader。然后使用GetOrdinal根据列名获取列的位置。最后,调用GetValue来检索值。您可以参考https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getvalue(v=vs.110).aspx

var reader = command.ExecuteReader();
while (reader.Read())
{
    var obj = dataReader.GetValue(dataReader.GetOrdinal("COLULMN_NAME"));
}
reader.Close();