Correct查询错误输出

本文关键字:输出 错误 查询 Correct | 更新日期: 2023-09-27 18:02:45

我有这个查询在我的项目

u_name = Application.Current.Properties["username"].ToString();
cmd = new SqlCommand("Select 'User ID' = u_id, 'USERNAME' = u_name, 'ROLE' = r_name from [User] as u, [Role] as r Where u_name != '@u_name' and u.r_id = r.r_id and r_name like '%" + txtBoxSearch.Text.Replace("'", "''").Trim() + "%' or u_name like '%" + txtBoxSearch.Text.Replace("'", "''").Trim() + "%'", conn);
cmd.Parameters.AddWithValue("@u_name", u_name);
da = new SqlDataAdapter(cmd);
dt = new DataTable("User");
da.Fill(dt);
dataGridUser.ItemsSource = dt.DefaultView;
dataGridUser.Columns[0].Visibility = System.Windows
                                  .Visibility
                                  .Hidden;

当我尝试在SQL Server中使用查询时,它显示了正确的输出,但当我在我的项目中使用它并使用搜索按钮在数据网格中显示它时。它仍然显示了由于我在查询中使用的u_name != @u_name语句而不应该显示的用户名。这有什么不对吗?

Correct查询错误输出

您的用户名没有用单引号括起来,因此显示为:

u_name != Administrator

代替

u_name != 'Administrator'

要解决这个问题,我建议您修改:

u_name != @u_name

u_name != '@u_name'

这是因为你的最后一个OR子句。在查询的末尾有这个:

    or u_name like '%" + txtBoxSearch.Text.Replace("'", "''").Trim() + "%'

使用(and)将WHERE子句的不同组括起来以获得正确的结果。您可能会在查询分析器中得到正确的输出,因为您用文字值替换了对txtBoxSearch控件的引用。