使用存储过程从SQLCommand填充WPF数据网格

时间:2012-08-11 12:01:46

标签: c# .net datagrid ado.net

我目前正在尝试使用使用SQLCommand执行存储过程并返回结果的类的成员来填充数据网格。

我的班级成员(以及我认为问题所在的地方)是:

public DataView DisplayHealthIndicator(DateTime startDate, DateTime endDate)
{
    string queryString =
        "DECLARE @RC int"
        + "DECLARE @date_from datetime = dateadd(day, 0, datediff(day, 0, getdate()))"
        + "DECLARE @date_to datetime = dateadd(day, 0, datediff(day, 0, getdate()))"

        + "EXECUTE @RC = [Testing].[marlin].[support_retrieve_workflow_history] "
            + "@date_from "
            + ",@date_to"
        + "GO";

    using (SqlConnection connection = new SqlConnection(GetConnectionString()))
    {
        using (var cmd = new SqlCommand(queryString, connection))
        {
            connection.Open();

            var reader = cmd.ExecuteReader();

            var dt = new DataTable();
            dt.Load(reader);

            return dt.DefaultView;
        }
    }

}

我正在使用以下方式调用此成员:

var db = new DatabaseHandle();
        dataGridWorkflow.ItemsSource = db.DisplayHealthIndicator(DateTime.Now, DateTime.Now);

然而!我目前收到错误:

Incorrect syntax near @date_from

Must declare the scalar variable @RC

在某种程度上我理解错误 - 我相信我不能在我的sqlQuery字符串中声明变量......但是,我该怎么做?

我很确定它对此没有任何影响,但如果确实如此,这就是存储过程的内容:

create procedure marlin.support_retrieve_workflow_history
(
    @date_from datetime,
    @date_to datetime
)
as
select  dateadd(day, 0, datediff(day, 0, e.event_date)) as 'Date',
        c.setting_secondary 'Workflow Category' ,
        d.setting_main as 'Error Type' ,
        sum(e.event_count) as 'Total'
from    marlin.support_events e
        inner join marlin.support_config c
            on e.event_category = c.setting_code
            and c.config_code = 60
        inner join marlin.support_config d
            on e.event_type = d.setting_code
            and d.config_code = 70
where   e.event_date between @date_from and @date_to
group by 
        e.event_date,
        c.setting_secondary ,
        d.setting_main

2 个答案:

答案 0 :(得分:1)

cmd.Parameters["@ReturnValue"]包含返回值 - 您不需要在动态SQL中添加参数

将参数添加到cmd

cmd.Parameters.AddWithValue("ParamName", Value);

同时更改cmd.CommandType(可能不会调用它,检查cmd的成员)到StoredProcedure

e.g。

using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
    using (var cmd = new SqlCommand(queryString, connection))
    {
        connection.Open();

        cmd.CommandType = ??.StoredProcedure; // Can't remember what enum name is prob SqlCommandType or something
        cmd.Parameters.AddWithValue("date_from", DateTime.blah.blah);
        cmd.Parameters.AddWithValue("date_to", DateTime.blah.blah);
        var reader = cmd.ExecuteReader();

        var dt = new DataTable();
        dt.Load(reader);

        return dt.DefaultView;
    }
}

免责声明:其中一些道具名称,返回值参数的名称可能不正确,因此请查看文档:)

答案 1 :(得分:0)

这篇文章有点陈旧......但是,我想分享一下我如何动态填充WPF DataGrid

private void Fill_DataGrid_ServiceName()
    {
        this.Cursor = Cursors.Wait;

        // create an instance
        DatabaseClass objDatabaseClass = new DatabaseClass(_connectionString);

        // if we are able to open and close the SQL Connection then proceed
        if (objDatabaseClass.CheckSQLConnection())
        {
            try
            {
                // create an instance. variable 'con' will hold the instance
                SqlConnection con = new SqlConnection(_connectionString);

                con.Open();

                // Query to populate the Grid
                string Query = @"SELECT 
                                cm_mktdata_mdsservice_fits_to_finance_id_unique AS [Id Unique]
                                ,cm_mktdata_mdsservice_fits_to_finance_MDSService_fits AS [FITS MDSService]
                                ,cm_mktdata_mdsservice_fits_to_finance_MDSService_finance AS [Finance MDSService]
                                ,'[ ' + CONVERT(varchar, user_detail_user_info_id_user) + ' ] ' + user_detail_user_info_nm_login AS [Last Modified By]
                                ,cm_mktdata_mdsservice_fits_to_finance_record_version AS [Record Version]
                                ,cm_mktdata_mdsservice_fits_to_finance_dt_modified AS [Dt Modified]
                                ,cm_mktdata_mdsservice_fits_to_finance_ind_active AS [Ind Active]
                            FROM 
                                dbo.v_mktdata_ui_mdsservice_fits_to_finance_detail
                            WHERE
                                cm_mktdata_mdsservice_fits_to_finance_ind_operational = 1
                            ORDER BY
                                cm_mktdata_mdsservice_fits_to_finance_MDSService_fits";


                SqlCommand createCommand = new SqlCommand(Query, con);
                createCommand.ExecuteNonQuery();

                // transfer the results of createCommand to the dataGrid
                SqlDataAdapter dataAdapter = new SqlDataAdapter(createCommand);
                DataTable dt = new DataTable("vcm_mktdata_mdsservice_fits_to_finance");
                dataAdapter.Fill(dt);
                dataGrid_ServiceName.ItemsSource = dt.DefaultView;
                dataAdapter.Update(dt);

                con.Close();

                // Enable the Refresh Grid Button
                btn_RefreshGrid_ServiceName.IsEnabled = true;


                // get DataGrid row count                    
                lbl_dataGrid_RowCount_ServiceName.Content = dataGrid_ServiceName.Items.Count.ToString() + " rows";

                //return true;
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
                //return false;
            }
        }
        else
        {
            MessageBox.Show("Connection not established to the SQL Server. " + Environment.NewLine + "The SQL Server may be offline or valid credentials are not yet granted.", "SQL Server Connection Error", MessageBoxButton.OK, MessageBoxImage.Error);

            this.Close();
        }

        this.Cursor = Cursors.Arrow;
    }

DatabaseClass如下

   class DatabaseClass
{
    // Variables
    private string _connectionString = "";


    public DatabaseClass(string connectionString)
    {
        _connectionString = connectionString;  
    }

    /// Check to see if Connection can be opened
    /// 
    /// Returns True if the connection can be open else it returns False
    ///
    public bool CheckSQLConnection()
    {
        SqlConnection con = new SqlConnection(_connectionString);

        try 
        {           
            con.Open();
            con.Close();

            return true;
        }
        catch (SqlException ex)
        {       
           return false;
        }
    }

}

对于连接字符串,它将如下所示

public static string SQLDataSourceStr = "Data Source=MySQL-DB-DV;Initial Catalog=My_Data;Integrated Security=True";