简体   繁体   中英

Complicated Report Requires SQL Temp File C# Returns No Rows

Here is the problem. I have to write a long, hella complicated report. I don't think I can do it using only C# so I thought the best thing was a temporary SQL table. So I wrote this code and I always get no rows and I know there is data in the table.

        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand();
        SqlDataReader reader;

        cmd.CommandText = "SELECT * INTO ##temp FROM Customers";
        cmd.Connection = connection;
        connection.Open();

        reader = cmd.ExecuteReader();

        if (reader.HasRows)
        { MessageBox.Show("ROWS"); }
        else
        { MessageBox.Show("NO ROWS"); }

        connection.Close();

So I thought, maybe I need another reader to SELECT * FROM ##TEMP but it always crashes telling me that my reader is already open (I used reader = cmd.ExecuteReader();). Please help.

I found the answer:

        cmd.Connection = connection;
        connection.Open();
        cmd.ExecuteNonQuery();
        cmd.CommandText = "SELECT * from ##temp";
        reader = cmd.ExecuteReader();

First run ExecuteNonQuery, then change the command then run ExecuteReader

Your question fails to justify the use of a temporary table. There really is no reason for you not to simply read the data directly from the actual table (unless your question omitted important and relevant details).

Also, it's a good idea to get in the habit of disposing the db objects with using blocks to clean up properly even in the event of exceptions.

Here is what the code could look like:

using (var connection = new SqlConnection(connectionString))
{
    using (var cmd = new SqlCommand("SELECT * FROM Customers", connection))
    {
        connection.Open();

        using (var reader = cmd.ExecuteReader())
        {
            if (reader.HasRows)
            {
                MessageBox.Show("ROWS");
            }
            else
            {
                MessageBox.Show("NO ROWS");
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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