Getting second value of the column c# sql

I am working on a grade submission module. How do I get the second second row of the column in my table and put it into the label1, the third row I put it into label2, and so on?

Example:

studentID | Subjects
 12345    | Mathematics 
 12345    | Science
 12345    | History

I only want to get the second row of the column subject which is "Science" and "History" and put it into the label and save it to new table. because I always get the first row of the column.

This is my code

string sql = "Select * from tbl_Subject where studentID like '" + studID.Text + "'";
cm = new SqlCommand(sql, cn);
dr = cm.ExecuteReader();
while (dr.Read())
{
    Subject.Text = dr["Subjects"].ToString();
}
dr.Close();

Thank you in advance!

Upvotes: 0

Views: 654

Answers (1)

Er Mayank
Er Mayank

Reputation: 1073

ROW_NUMBER() can be used to skip the entire row as :

string sql = "select * from (Select  ROW_NUMBER() OVER(ORDER BY Subjects) AS RoNum ,* from tbl_Subject) std where std.studentID like @Search  and std.RoNum > 1 ";
cm = new SqlCommand(sql, cn);
 cm .Parameters.AddWithValue("@Search", "%" + studID.Text + "%"); 
dr = cm.ExecuteReader();
while (dr.Read())
{
    Subject.Text = dr["Subjects"].ToString();
}
dr.Close();

You can skip as many as rows using std.RoNum > 1 , with the ordering of row OVER(ORDER BY Subjects)

Upvotes: 1

Related Questions