【问题标题】:Two SELECTS, One query两个选择,一个查询
【发布时间】:2009-07-02 18:02:44
【问题描述】:

我想从数据库的两个表中提取信息。 A 中的一行,B 中带有 FK 的行到我从 A 中拉出的行。

我想用两个 select 语句使它成为一个存储过程,而不是对 DB 进行两次调用。

我知道几种从单个选择中提取信息的方法...但不记得如何从多个选择中获取数据。事实证明,谷歌搜索很困难,因为我很难用名词/动词来描述无法描述其他一百万件事的情况。

有人能指出正确的方向吗?

(为了简单起见,我知道使用“使用”语句等......我只需要该方法的基本概念。

using (SqlConnection conn = new SqlConnection(connectionString))
{
    using (SqlCommand com = new SqlCommand(commandString, conn))
    {
        <somehow get multiple select's of data here in one call>
    }
}

【问题讨论】:

    标签: .net sql


    【解决方案1】:

    如果您习惯使用 SqlDataReader,那么您只需要让您的存储过程或 sql 语句执行多个选择并调用 NextResult() 即可移动到下一个结果集:

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(commandString, conn);
        // Add parameters here
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            // This will read the first result set
            while(reader.Read())
            { 
                // Read data
            }
    
            // This will read the second result set
            if (!reader.NextResult())
            {
                throw new ApplicationException("Only one result set returned");
            }
    
            while (reader.Read())
            {
                // Read data
            }
        }
    }
    

    如果您习惯使用数据适配器返回数据表,那么您需要做的就是让数据适配器填充数据集并从 Tables 属性中提取结果集:

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
    
        SqlDataAdapter da = new SqlDataAdapter(commandString, conn);
        DataSet ds = new DataSet();
        da.Fill(ds);
    
        DataTable firstResult = ds.Tables[0];
        DataTable secondResult = ds.Tables[1];
    }
    

    【讨论】:

    • 很棒,而且很完整。第二个答案是我以前见过的,但都很高兴知道。非常感谢。
    【解决方案2】:
    var reader = com.ExecuteReader();
    
    while(reader.Read())
    {
      //do operations for the first select here
    }
    
    reader.NextResult();
    
    while(reader.Read())
    {
      //do operations for the second select here
    }
    

    注意:可能有语法错误,未检查。但重点是,使用 SqlDataReader.NextResult()。

    【讨论】:

    • 这看起来正是我需要的......但我似乎没有看到 .ReadNext() 方法......我错过了拉入我需要的库吗?
    【解决方案3】:

    您需要使用M.A.R.S,它允许您从多个选择中加载DataTable 作为一个DataTableCollection。

    【讨论】:

    • 原帖中没有任何内容表明需要同时处理多个结果集。
    【解决方案4】:

    也许我误解了您要执行的操作,但您不能使用联接和数据读取器来获取此信息吗?

    大致(在你的命令的 using 语句中)

    select a.foo, b.bar from a, b where a.id = 2 and b.foo = a.foo;
    
    using( DbDataReader reader = com.executeReader() )
    {
        while( reader.read() )
        {
            myA.foo = reader[0].toString();
            myB.bar = reader[1].toString();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-19
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      相关资源
      最近更新 更多