C# 代码优化:如何确保从 SQL 查询中获取的 'dep' 值唯一性

在 C# 代码中,经常需要从数据库中读取数据并填充到界面元素中。当查询结果中存在重复的 'dep' 值时,会导致数据显示混乱。为了解决这个问题,可以使用 DISTINCT 关键字来筛选重复值。

原始代码:

private void readDept ()
{
    //读取ERP生产部门的值
    // 执行SQL查询语句,让cbx_p_cat显示已有的类别
    DateTime selectedDate = dtpKanBan.Value.Date; // 只获取日期部分
    using (SqlConnection connection = new SqlConnection(erpConnString))
    {
        connection.Open();
        string query = "SELECT dep, (select name from dept where dep=mf_mo.dep) as name FROM mf_mo WHERE sta_dd = @selectedDate groud by dep";
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            command.Parameters.AddWithValue("@selectedDate", selectedDate);
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataTable dataTable = new DataTable();
            //// 填充DataTable对象
            adapter.Fill(dataTable);
            // 添加默认显示值
            DataRow defaultRow = dataTable.NewRow();
            defaultRow["dep"] = "";
            defaultRow["name"] = "选生产部门";
            dataTable.Rows.InsertAt(defaultRow, 0);
            // 设置cboDept的显示值和对应的数据值
            cboDept.DataSource = dataTable;
            cboDept.DisplayMember = "name";
            cboDept.ValueMember = "dep";
            // 设置label1显示对应的dep
            lblDept.DataBindings.Add("Text", dataTable, "dep");
        }
    }
}

优化后的代码:

private void readDept ()
{
    //读取ERP生产部门的值
    // 执行SQL查询语句,让cbx_p_cat显示已有的类别
    DateTime selectedDate = dtpKanBan.Value.Date; // 只获取日期部分
    using (SqlConnection connection = new SqlConnection(erpConnString))
    {
        connection.Open();
        string query = "SELECT DISTINCT dep, (select name from dept where dep=mf_mo.dep) as name FROM mf_mo WHERE sta_dd = @selectedDate";
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            command.Parameters.AddWithValue("@selectedDate", selectedDate);
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataTable dataTable = new DataTable();
            //// 填充DataTable对象
            adapter.Fill(dataTable);
            // 添加默认显示值
            DataRow defaultRow = dataTable.NewRow();
            defaultRow["dep"] = "";
            defaultRow["name"] = "选生产部门";
            dataTable.Rows.InsertAt(defaultRow, 0);
            // 设置cboDept的显示值和对应的数据值
            cboDept.DataSource = dataTable;
            cboDept.DisplayMember = "name";
            cboDept.ValueMember = "dep";
            // 设置label1显示对应的dep
            lblDept.DataBindings.Add("Text", dataTable, "dep");
        }
    }
}

通过在 SQL 查询语句中添加 DISTINCT 关键字,可以确保查询结果中 'dep' 值的唯一性,避免重复值出现,从而提高数据显示的准确性。

C# 代码优化:如何确保从 SQL 查询中获取的 'dep' 值唯一性

原文地址: https://www.cveoy.top/t/topic/qupM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录