c #sql语句显示最后4条记录

时间:2013-07-23 07:49:10

标签: c# sql sql-server

我想在每张标签上显示员工ID的最后4条记录,我该怎么办?

String strSQL = @"SELECT * FROM staff";
SqlCommand myCommand = new SqlCommand(strSQL, myConn);
SqlDataReader myDataReader = myCommand.ExecuteReader();

while (myDataReader.Read())
{
    Label1.Text = myDataReader["staffID"].ToString();
    Label2.Text = myDataReader["staffID"].ToString();
    Label3.Text = myDataReader["staffID"].ToString();
    Label4.Text = myDataReader["staffID"].ToString();
}               

7 个答案:

答案 0 :(得分:2)

你必须使用这样的查询:

SELECT TOP 4 * 
FROM staff 
ORDER BY MyOrderColumn DESC

通过这样的查询,您将返回最后4条记录。

答案 1 :(得分:2)

首先,如果只想要它们,你必须只选择最后四个:

String strSQL = @"SELECT TOP 4 staffID FROM staff ORDER BY staffID DESC";
using(var myCommand = new SqlCommand(strSQL, myConn))
using(var dataAdapter = new SqlDataAdapter(myCommand))
{
    DataTable table = new DataTable();
    dataAdapter.Fill(table);
    Label1.Text = table.Rows[0]["staffID"].ToString();
    Label2.Text = table.Rows[1]["staffID"].ToString();  
    Label3.Text = table.Rows[2]["staffID"].ToString();
    Label4.Text = table.Rows[3]["staffID"].ToString();
} 

你必须处理少于4名员工的情况。

答案 2 :(得分:1)

如果这是winforms,你可以尝试这样做:

int i = 1;
while (myDataReader.Read())
{
  var label = this.Controls.Find("Label" + i, false) as Label;
  if (label != null)
  {
      label.Text = myDataReader["staffID"].ToString();
  }
  else
  {
       break;
  }

  i++;
}

答案 3 :(得分:0)

我会尝试以下:

  String strSQL = @"SELECT top 4 staffID FROM staff order by staffID desc";
  SqlCommand myCommand = new SqlCommand(strSQL, myConn);
  SqlDataReader myDataReader = myCommand.ExecuteReader();

  var labels = new Label[] { Label1, Label2, Label3, Label4 };
  foreach (var label in labels) {
    if (!myDataReader.Read()) {
      break;
    }
    label.Text = myDataReader["staffID"].ToString();
  }

同时,中继器和数据绑定可能是更好(更清洁)的选择。

答案 4 :(得分:0)

尝试修改仅返回最后4行的SQL查询

SELECT 
    *
FROM
(
    SELECT 
        ROW_NUMBER() OVER (PARTITION BY StaffID ORDER BY StaffID DESC) AS StaffID, *
FROM Staff
) as temporaryList
WHERE temporaryList.StaffID <= 4

答案 5 :(得分:0)

String strSQL = @"SELECT TOP 4 StaffID FROM staff ORDER BY StaffID DESC"; //
SqlCommand myCommand = new SqlCommand(strSQL, myConn);
SqlDataReader myDataReader = myCommand.ExecuteReader();
int i = 0;
while (myDataReader.Read() && i<4)
{
    Label lblToSet = new Label();
    switch (i) 
    {
       case 0: lblToSet = Label1; break;
       case 1: lblToSet = Label2; break;
       case 2: lblToSet = Label2; break;
       case 3: lblToSet = Label3; break;
    }
    lblToSet.Text = myDataReader["staffID"].ToString();
    i++;
 }

答案 6 :(得分:0)

With cte 
As 
(SELECT TOP 4 [StaffId]
   FROM [sample].[dbo].[Staff] 
  ORDER BY  [StaffId] desc) 

SELECT * 
  FROM cte 
 ORDER BY StaffId