繁体   English   中英

两个SELECTS,一个查询

[英]Two SELECTS, One query

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

我想使用两个select语句使它成为单个存储的proc,而不必对数据库进行两次调用。

我知道几种从单个选择中提取信息的方法...但是不记得如何从多个选择中获取数据。 谷歌搜索已被证明很困难,因为我在想出名词/动词来描述无法描述一百万种其他事物的情况时遇到了麻烦。

有人可以指出我正确的方向吗?

(为简单起见,我知道使用“ using”语句,等等……我只需要该方法的基本思想即可)。

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

如果您习惯使用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];
}
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()。

您需要使用MARS ,它允许您从多个选择中加载DataTable作为一个DataTableCollection。

也许我误会了您要做什么,但是您不能使用联接和数据读取器来获取此信息吗?

大致(在命令的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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM