//_whereclause is: where (lastName like '%Davis%')
public static MyList GetAll(string _whereclause)
{
using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
string selectSQL = "";
selectSQL += "SELECT @RecordCount = COUNT(*) FROM [PersonnelTable]";
if (_whereclause != string.Empty)
{
selectSQL += " @WhereClause";
}
using (SqlCommand myCommand = new SqlCommand(selectSQL, myConnection))
{
myCommand.CommandType = CommandType.Text;
SqlParameter whereClauseParam = new SqlParameter("@WhereClause", SqlDbType.NVarChar, 4000);
whereClauseParam.Value = _whereclause;
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{..............
如果我使用@WhereClause
运行它,我会收到错误:
' @ WhereClause'。
附近的语法不正确
答案 0 :(得分:1)
您的选择查询应该像
selectSQL += "SELECT @RecordCount = COUNT(*) FROM [PersonnelTable] where (lastName like '%" + @WhereClause + "%')";
假设:
SqlParameter whereClauseParam = new SqlParameter("@WhereClause", SqlDbType.NVarChar, 4000);
whereClauseParam.Value = _whereclause; //Here you are getting the value as 'Davis'
但是如果您将其中的值设为where (lastName like '%Davis%')
,则只需在
selectSQL += "SELECT @RecordCount = COUNT(*) FROM [PersonnelTable] ";
^^ here