两个SELECTS,一个查询

时间:2009-07-02 18:02:45

标签: .net sql

我想从数据库的两个表中提取信息。 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>
    }
}

4 个答案:

答案 0 :(得分:4)

如果你习惯使用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];
}

答案 1 :(得分:3)

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()。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

也许我误解了你想要做的事情,但是你不能用连接和数据加载器来获取这些信息吗?

粗略地(在你的命令中使用声明)

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();
    }
}
相关问题