You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Dapper、IDbAdapter从SQL存储过程的表变量获取OUTPUT值

使用Dapper和IDbAdapter获取存储过程表变量@inserted_values的值

首先明确核心前提:存储过程内部的表变量@inserted_values无法被外部直接访问,必须在存储过程末尾显式将其数据作为结果集返回,Dapper才能读取到。

步骤1:修改存储过程,输出表变量数据

在你的MERGE/INSERT逻辑之后,添加一段SELECT语句,把@inserted_values中的数据输出为结果集:

-- 原存储过程逻辑结束后添加
SELECT 
    Id, 
    DefinitionId, 
    PortfolioCode, 
    BenchmarkCode, 
    ExternalCode 
FROM @inserted_values;

步骤2:定义结果映射实体

创建一个C#类,属性名与存储过程返回的列名对应(若列名和属性名不一致,可使用[Column]特性映射):

public class InsertedRecord
{
    public int Id { get; set; }
    public int DefinitionId { get; set; }
    public string PortfolioCode { get; set; }
    public string BenchmarkCode { get; set; }
    public string ExternalCode { get; set; }
}

步骤3:用Dapper直接调用存储过程

通过Dapper扩展IDbConnection的Query方法,读取返回的结果集:

using (var conn = new SqlConnection("你的数据库连接字符串"))
{
    conn.Open();
    
    // 替换为你的存储过程名称,参数根据实际需求传递
    var insertedRecords = conn.Query<InsertedRecord>(
        "你的存储过程名",
        commandType: CommandType.StoredProcedure,
        parameters: new { /* 存储过程所需参数,如 ParamName = ParamValue */ }
    ).ToList();
    
    // insertedRecords即为@inserted_values中的数据
}

步骤4:结合IDbAdapter使用(自定义适配器场景)

如果项目封装了IDbAdapter统一数据库操作,只需在适配器内部调用Dapper方法即可:

// 示例IDbAdapter实现
public class SqlDbAdapter : IDbAdapter
{
    private readonly IDbConnection _connection;

    public SqlDbAdapter(IDbConnection connection)
    {
        _connection = connection;
    }

    public List<T> ExecuteStoredProcedure<T>(string procedureName, object parameters = null)
    {
        return _connection.Query<T>(
            procedureName, 
            parameters, 
            commandType: CommandType.StoredProcedure
        ).ToList();
    }
}

// 使用适配器
using (var conn = new SqlConnection("你的数据库连接字符串"))
{
    conn.Open();
    var adapter = new SqlDbAdapter(conn);
    var insertedRecords = adapter.ExecuteStoredProcedure<InsertedRecord>("你的存储过程名");
}

关键注意事项

  • 若存储过程返回多个结果集,需使用Dapper的QueryMultiple方法,再通过Read<InsertedRecord>()读取对应结果集。
  • 确保实体类属性类型与数据库列类型匹配,避免类型转换错误。

内容的提问来源于stack exchange,提问作者Auroops

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:42:52