【问题标题】:Multiple Selects In Query Not Giving All Result Sets查询中的多项选择未给出所有结果集
【发布时间】:2018-02-27 02:05:23
【问题描述】:

在我的代码中,有一个循环使用 SqlCommand 给出 SQL 查询的结果。 但是,对于我需要运行的某些查询,查询中有多个选择语句。例如,这可能是整个语句的样子:

Dim query as string = "
    Select * from people
    Select * from places
    Select * from items
    Select * from foods"

cmd = New SqlCommand(query, connect)
cmd.Connection.Open()
reader = cmd.ExecuteReader

While reader.HasRows()
//various logic
While reader.Read()
//Do Logic Here
End While
End While

当我的查询运行时,我得到了前 2 个的结果,但由于第 3 个没有结果,它会将应用程序踢出循环,我没有得到第 4 个选择的结果。我还需要第四次选择的结果。

编辑:联合不适用于这种情况,因为我需要能够区分我的逻辑中的结果集。

【问题讨论】:

  • 你有没有在每次查询之间尝试UNION ALL
  • 在外循环中使用reader.NextResult
  • 或者代替阅读器,填充 DataSet 并遍历 Tables 集合。
  • 根据this answer,一个好的方法可能是在同一连接上运行单独的查询。
  • @BryantFrankford 你不能在换行符上拆分字符串并遍历每个SELECT吗?

标签: sql-server vb.net


【解决方案1】:
    static void Main(string[] args)
    {
        cmd = new SqlCommand("zp_multiple_results", connect);
        cmd.Connection.Open();

        reader = cmd.ExecuteReader();

        do
        {
            if (reader.HasRows)
                while (reader.Read())
                {
                    Console.WriteLine(reader[0].ToString());
                }
        }
        while (reader.NextResult());

        cmd.Connection.Close();
        cmd.Connection.Dispose();
        cmd.Dispose();

        Console.ReadLine();
    }

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多