当我在SSMS中执行以下命令时,我得到了我期望的结果 -
SELECT * FROM [Event] WHERE Active = 'True' AND [Name] LIKE '%P%'
即显示名称包含P的所有事件
但是,当我在用C#编写的WinForms应用程序中构建此命令时,我总是得到一个空的数据表.
我使用以下代码 -
string sqlText = "SELECT * " + "FROM Event " + "WHERE Active = @Active"; SqlCommand sqlCom = new SqlCommand(); sqlCom.Parameters.Add("@Active", SqlDbType.Bit).Value = active; if (txtSearchName.Text != null && txtSearchName.Text.Length > 0) { sqlText += " AND [Name] LIKE '@Name'"; string value = "%" + txtSearchName.Text + "%"; sqlCom.Parameters.Add("@Name", SqlDbType.VarChar).Value = value; } sqlText += " ORDER BY [Date] DESC;"; sqlCom.CommandText = sqlText; DataTable table = Express.GetTable(sqlCom); DataView view = new DataView(table); DataTable show = view.ToTable(true, "ID", "Date", "Name"); dataEventsFound.DataSource = show;
请注意Express.GetTable是一种简单地添加SQLConnection并使用DataReader填充和返回DataTable的方法.我不相信错误在于Method,因为它在我编写的这个和其他应用程序中被使用了数百次.
我认为错误与命令文本和@Name参数有关,但我无法确切地确定问题是什么,以及为什么我的DataTable总是为空.
从@Name
参数之间删除单引号.
sqlText += " AND [Name] LIKE @Name";