.net - 两个 SELECTS,一个查询

标签 .net sql

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

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

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

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

(为简单起见,我知道使用“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];
}

关于.net - 两个 SELECTS,一个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1075831/

相关文章:

.net - 用于构建服务器和测试环境的最佳虚拟机产品

.net - 通过 Razor 创建新节点(在 Umbraco 中)

c# - Npgsql 奇怪的异常

sql - Firebird 2.5 VS Interbase 9/XE - 哪个性能更快?

sql - 如何在 do 列中按日期划分分组数据

mysql - 在 MySQL 中的同一语句中使用 GROUP_CONCAT、GROUP 和 HAVING

.net - NSubstitute 是否支持 ref 参数?

php - echo 失败错误

mysql - SQLzoo JOIN 教程 #13

c# - HTTP POST 通过 C#