0

我想在每个Label中显示员工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();
}               
4

7 回答 7

2

你必须使用这样的查询:

SELECT TOP 4 * 
FROM staff 
ORDER BY MyOrderColumn DESC

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

于 2013-07-23T07:56:05.333 回答
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名员工的情况。

于 2013-07-23T07:57:54.047 回答
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++;
}
于 2013-07-23T07:54:09.877 回答
0
With cte 
As 
(SELECT TOP 4 [StaffId]
   FROM [sample].[dbo].[Staff] 
  ORDER BY  [StaffId] desc) 

SELECT * 
  FROM cte 
 ORDER BY StaffId 
于 2013-07-23T08:01:38.450 回答
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();
  }

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

于 2013-07-23T07:57:02.490 回答
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
于 2013-07-23T07:57:04.117 回答
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++;
 }
于 2013-07-23T07:57:22.473 回答