【问题标题】:SqlDataAdapter - combine stored procedure and Select statement with parametersSqlDataAdapter - 将存储过程和 Select 语句与参数结合起来
【发布时间】:2017-02-08 15:49:53
【问题描述】:

使用SqlDataAdapter(或其他 ASP.NET 技术),是否可以对存储过程进行单个 SQL 调用并运行 select 语句?两者都有参数。

我知道你可以组合多个 select 语句...

DataSet ds = new DataSet();

using (SqlConnection connection = new SqlConnection(myConnectionString))
{
    connection.Open();

    SqlDataAdapter cmd = new SqlDataAdapter("SELECT id FROM Table1 WHERE id=@myid; SELECT id FROM Table2", connection);
    cmd.SelectCommand.Parameters.AddWithValue("@id",myid);
    cmd.Fill(ds);
}

你可以用类似的方式调用存储过程...

DataSet ds = new DataSet();

using (SqlConnection connection = new SqlConnection(myConnectionString))
{
    connection.Open();
    SqlDataAdapter cmd = new SqlDataAdapter("myStoredProcedure", connection);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.SelectCommand.Parameters.AddWithValue("@id",myid);
    cmd.Fill(ds);
}

但我想将两者合并为一个调用。

我需要将存储过程和选择语句分开。我不想将它们组合成一个存储过程。

感谢您的帮助!

【问题讨论】:

    标签: c# asp.net sql-server stored-procedures


    【解决方案1】:

    诀窍是exec 函数。

    来自文档

    它在 Transact-SQL 中执行命令字符串或字符串 批处理,或以下模块之一:系统存储过程, 用户定义的存储过程、CLR 存储过程、标量值 用户定义函数,或扩展存储过程。

    所以你可以这样做:

    DataSet ds = new DataSet();
    using (SqlConnection connection = new SqlConnection(myConnectionString))
    {
        connection.Open();
        SqlDataAdapter cmd = new SqlDataAdapter("SELECT id FROM Table1 WHERE id=@myid; Exec myStoredProcedure @myid", connection);
        cmd.SelectCommand.Parameters.AddWithValue("@myid",myid);
        cmd.Fill(ds);
    }
    

    【讨论】:

    • 谢谢胡安!因此,如果我想将两个参数传递给我的存储过程,它看起来像这样......“Exec myStoredProcedure @myid, @myid2” 另外,如果其中一个参数是用户定义的表类型怎么办?
    • 是的,你必须传递多语句命令所需的所有参数。
    猜你喜欢
    • 1970-01-01
    • 2013-02-17
    • 2014-04-05
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多