【问题标题】:Deal with the record returned from the stored procedure Web API处理存储过程 Web API 返回的记录
【发布时间】:2016-12-21 15:59:58
【问题描述】:

我有下面的存储过程,它插入/更新并从表中选择记录,看起来像

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

非常感谢任何帮助

【问题讨论】:

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


    【解决方案1】:

    首先,您需要使用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();
    

    【讨论】:

    猜你喜欢
    • 2012-10-11
    • 2019-04-20
    • 2017-05-06
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多