简体   繁体   English

将SELECT查询的结果保存到另一个表

[英]Saving results from SELECT query to another table

I have a SQL query generates the results found below it using Visual Studio query window: 我有一个SQL查询使用Visual Studio查询窗口生成在其下找到的结果:

SELECT SUM(TaskLength) AS TaskLength 
FROM myTable 
WHERE EventStartTime BETWEEN '2019/8/17' AND '2019/8/19' 
GROUP BY TaskName 
ORDER BY TaskLength

The query results window produces the following: 查询结果窗口将产生以下内容:

TaskName        TaskLength
--------------------------
Idle Time        20
Start Shift      31
Downtime         85
Engineering     120
Part Prep       141
Maintenance     172
Production      417 

My C# code below only returns one string representing one column from one row. 我下面的C#代码仅返回一个字符串,表示一行中的一列。

using (SqlConnection con = new SqlConnection(_connectionString))
{
     string query = @"SELECT SUM(TaskLength) AS TaskLength 
                      FROM myTable 
                      WHERE EventStartTime BETWEEN '2019/8/17' AND '2019/8/19' 
                      GROUP BY TaskName 
                      ORDER BY TaskLength";

     using (SqlCommand cmd = new SqlCommand(query, con))
     {
          con.Open();
          object result = cmd.ExecuteScalar();
          string totalMinutes = Convert.ToString(result);
     }
}

Does the returned cmd.ExecuteScalar object represent the entire resulting table? 返回的cmd.ExecuteScalar对象是否表示整个结果表?

If not, is there another way to do this. 如果没有,还有另一种方法可以做到这一点。 My thoughts are to save the results to an intermediate table (if it does not already do this) and save that to a .csv file there unless there is a better way. 我的想法是将结果保存到中间表(如果尚未执行此操作),然后将其保存到.csv文件中,除非有更好的方法。

ExecuteScalar returns only the first column from the first row. ExecuteScalar仅返回第一行的第一列。
If you have many rows to read then you need to call ExecuteReader and loop on the using the value returned by the SqlDataReader.Read until it returns false. 如果要读取的行很多,则需要调用ExecuteReader并使用SqlDataReader.Read返回的值循环使用,直到返回false。
While looping you store the results of your query in some kind of List creating objects matching the info returned by the reader. 循环时,您将查询结果存储在某种类型的List中,这些对象创建与读取器返回的信息匹配的对象。

Then, this list can be easily used as DataSource for some kind of User Interface object like a DataGridView or similar or used to write your data into a file or other storage. 然后,此列表可以很容易地用作某种类型的用户界面对象(如DataGridView或类似对象)的数据源,或用于将数据写入文件或其他存储中。

// The model that describes the data returned by the query
public class TaskData
{
    public string Name {get;set;}
    public int Length {get;set;}
} 

..... 
// Where you store each record retrieved by the query
List<TaskData> results = new List<TaskData>();

using (SqlConnection con = new SqlConnection(_connectionString))
{
   // Added the taskname to the query
   string query = @"SELECT TaskName, SUM(TaskLength) as TaskLength 
                  FROM myTable 
                  WHERE EventStartTime 
                  BETWEEN '2019/8/17' AND '2019/8/19' 
                  GROUP BY TaskName ORDER BY TaskLength";

   using (SqlCommand cmd = new SqlCommand(query, con))
   {
      con.Open();

      // Get a reader to loop over the results
      using(SqlDataReader reader = cmd.ExecuteReader())
      {
          // Start reading data (until there are no more records to read)
          while(reader.Read())
          {
               // From the current record build the TaskData info
               TaskData data = new TaskData
               {
                   Name = reader["TaskName"].ToString(),
                   Length = Convert.ToInt32(reader["TaskLength"]);
               }

               // Add this info the the collection of your results
               results.Add(data);
          }
      }
   }
}

And now, if you want to store the result to a CSV file, the code is simply 现在,如果您要将结果存储到CSV文件中,则代码很简单

File.WriteAllLines("yourFile.csv", 
      string.Join(Environment.NewLine, 
             results.Select(x => x.Name +","+x.Length))

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

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