简体   繁体   English

如何在小步骤中使用 C# 从 Sql 服务器长查询中检索数据

[英]How to retrieve data from Sql Server long query using C# in small steps

I want to get data from a long query like Sql Server Management Studio does.我想从像 Sql Server Management Studio 这样的长查询中获取数据。 I mean, it displays small amounts of data as soon as is received from the server (in this case, SQL Server 2008).我的意思是,一旦从服务器接收到少量数据(在本例中为 SQL Server 2008),它就会显示少量数据。

I am using C# and NET 3.5.我正在使用 C# 和 NET 3.5。 I have read documentation about BeginExecuteReader: this method starts the query asynchronously but the read operation is done synchronously.我已阅读有关 BeginExecuteReader 的文档:此方法异步启动查询,但读取操作是同步完成的。

Unfortunately, I haven't found any real life example while googling for this:-( Can you help me with this topic?不幸的是,我在谷歌搜索时没有找到任何现实生活中的例子:-(你能帮我解决这个话题吗?

My query is a simple one: SELECT [...] FROM [...] WHERE [...]我的查询很简单: SELECT [...] FROM [...] WHERE [...]

But there are many rows involved and I would like to show the user the firsts ones that match the query, without waiting for the whole operation to complete.但是涉及到很多行,我想向用户展示与查询匹配的第一个行,而不是等待整个操作完成。

Many thanks!非常感谢!

You don't need to execute the reader asynchronously for what you want to accomplish.您不需要异步执行阅读器来完成您想要完成的任务。 Here are a couple options for you:这里有几个选项供您选择:

Option 1: Display records as you read them (or batched) by using a SqlDataReader .选项 1:使用 SqlDataReader在读取(或批处理)记录时显示记录。 Depending on your application, you may need to execute the reader on a separate thread and notify the UI thread to update the view accordingly (using a BackgroundWorker for example).根据您的应用程序,您可能需要在单独的线程上执行阅读器并通知 UI 线程相应地更新视图(例如使用 BackgroundWorker)。

using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        //read record, diplay record
    }
}

Option 2 (best option): Page your query results and show only a "screen" of data at a time.选项 2(最佳选项):分页查询结果并一次仅显示“屏幕”数据。

You can try paginate the result set and get the chunk as soon as they were transfered from sql server database to the application.您可以尝试对结果集进行分页,并在它们从 sql 服务器数据库传输到应用程序后立即获取块。

  1. Count the result set.计算结果集。
  2. With the count number, paginate through the result set with a page size like 1000 (or more) (Use ROW_NUMBER on Sql Server)使用计数,对结果集进行分页,页面大小为 1000(或更多)(在 Sql 服务器上使用 ROW_NUMBER)
  3. Display the first result set (paginated), than append the rest as soon as they return.显示第一个结果集(分页),而不是 append 和 rest 一返回。

Hope it helps.希望能帮助到你。

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

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