如何在数据集DataTable中显示数据列

时间:2013-02-08 21:31:31

标签: c# sql sql-server vb.net sql-server-2005

我有一个查询,我将数据集作为数据表放入。查询运行很好,但是在数据表中它没有列出数据列中的任何内容,因为我无法报告它...任何想法为什么这不起作用?我的查询如下。

SELECT * FROM (
    SELECT timeclock.dtTimeIn, timeclock.dtTimeOut, employees.sfirstname,
       RANK() OVER ( ORDER BY dtTimeIn) rk1, --earliest record gets 1
       RANK() OVER (ORDER BY dtTimeOut DESC) rk2 --latest record gets 1

    FROM   TimeClock INNER JOIN
                         Employees ON TimeClock.lEmployeeID = Employees.lEmployeeID
    WHERE (dtTimeIn > dateadd(day, datediff(day, 0, getdate())-1, 0)) AND (dtTimeOut < dateadd(day, datediff(day, 0, getdate()), 0)) AND 
      (sDept IN ('1', '2', '3'))
) A
WHERE rk2=1 

运行查询时的当前输出:

  dtTimeIn                    dtTimeOut       sfirstname    rk1      rk2
2/7/2013 2:36:00 PM 2/7/2013 7:52:33 PM        Brian        10        1

enter image description here

在wizzard中创建表适配器时...我收到一条错误消息:

The Wizard detected the following problems when configuring the TableAdapter:
"OpenTime":

Details:
Generated SELECT statement.
The OVER SQL construct or statement is not supported
To add these components to your dataset, click Finish.

我猜它不喜欢这个查询...但是我不知道除了使用“OVER”函数之外还有什么其他方法可以完成查询......

3 个答案:

答案 0 :(得分:8)

由于TableAdapter向导的限制,您必须使用代码创建DataTable

DataTable dataTable;

using (SqlConnection sqlConn = new SqlConnection())
{
    sqlConn.Open();

    using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
    using (sqlDataAdapter.SelectCommand = sqlConn.CreateCommand())
    {

        sqlDataAdapter.SelectCommand.CommandType = CommandType.Text;
        sqlDataAdapter.SelectCommand.CommandText = '
            SELECT * FROM (
                SELECT timeclock.dtTimeIn, timeclock.dtTimeOut, employees.sfirstname,
                    RANK() OVER ( ORDER BY dtTimeIn) rk1, --earliest record gets 1
                    RANK() OVER (ORDER BY dtTimeOut DESC) rk2 --latest record gets 1

                FROM TimeClock INNER JOIN
                    Employees ON TimeClock.lEmployeeID = Employees.lEmployeeID
                WHERE (dtTimeIn > dateadd(day, datediff(day, 0, getdate())-1, 0)) AND (dtTimeOut < dateadd(day, datediff(day, 0, getdate()), 0)) AND (sDept IN ('1', '2', '3'))
            ) A
            WHERE rk2=1';

        sqlDataAdapter.Fill(dataTable);
    }
}

在填充dataTable后,只需将其分配给ReportViewer的DataSource

ReportDataSource rds = new ReportDataSource(dataTable.TableName, dataTable);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);

请注意,这些代码段的很大一部分未经测试。

答案 1 :(得分:6)

我认为不是使用拖放界面来创建tableAdapter,因为您的查询包含OVER SQL结构(如错误所示),您必须创建tableAdapter并填充数据表在代码中。

答案 2 :(得分:3)

您可以从查询中创建一个视图,然后只需从视图中选择,这应该隐藏来自tableAdapter的OVER SQL。