Getting the last record in SQL in WHERE condition

后端 未结 9 2261
借酒劲吻你
借酒劲吻你 2021-02-15 04:24

i have loanTable that contain two field loan_id and status

loan_id status
==============
1       0
2       9
1       6
         


        
9条回答
  •  甜味超标
    2021-02-15 04:51

    Use a data reader. When it exits the while loop it will be on the last row. As the other posters stated unless you put a sort on the query, the row order could change. Even if there is a clustered index on the table it might not return the rows in that order (without a sort on the clustered index).

        SqlDataReader rdr = SQLcmd.ExecuteReader();
        while (rdr.Read())
        {
        }
        string lastVal = rdr[0].ToString()
        rdr.Close();
    

    You could also use a ROW_NUMBER() but that requires a sort and you cannot use ROW_NUMBER() directly in the Where. But you can fool it by creating a derived table. The rdr solution above is faster.

提交回复
热议问题