简体   繁体   中英

C#: SQL “Select Top..” query does not return any rows?

I need to:

1) Filter Rows by "NodeParent" (which I provide)

2) Sort rows by "Time" and get the most recent entry

Here's what I wrote:

using (SqlConnection con = new SqlConnection(conString))
{
        SqlCommand cmd = new SqlCommand("SELECT TOP 1 NodeID FROM ActivityTable WHERE NodeParent='" + nodeid_previous + "'" + " ORDER BY Time DESC", con);

        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        if (rdr.HasRows)
        {
             while (rdr.Read())
             {
                     nodeid_previous = rdr["NodeID"].ToString();
                     break;
             }
             rdr.Close();
        }
        else
        {
             //so on and so forth..
        }
}

This however doesn't return any results even though I HAVE rows which abide by these conditions. Is the query correct folks? :)

Before

    SqlCommand cmd = new SqlCommand("SELECT TOP 1 NodeID FROM ActivityTable WHERE NodeParent='" + nodeid_previous + "'" + " ORDER BY Time DESC", con);

After - Limit is added to the end of your query, rather than in the beginning of you select list like MS SQL Server's Top command

    SqlCommand cmd = new SqlCommand("SELECT NodeID FROM ActivityTable WHERE NodeParent='" + nodeid_previous + "'" + " ORDER BY Time DESC Limit 1", con);

You have to use "Limit 1" in the end. There is no "TOP 1" in MYSQL. I guess it is SQLServer command.

Do:

SqlCommand cmd = new SqlCommand("SELECT NodeID FROM ActivityTable WHERE NodeParent='" + nodeid_previous + "'" + " ORDER BY Time DESC Limit 1", con);

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