Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come mostrare DataColumns in Dataset DataTable

A causa delle limitazioni del TableAdapter procedura guidata, devi creare la DataTable utilizzando il codice.

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);
    }
}

Dopo aver ottenuto la tua dataTable compilato, assegnalo semplicemente al DataSource di ReportViewer

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

Tieni presente che gran parte di questi frammenti di codice non sono stati testati.