SQL动态查询 - ' @ WhereClause'

时间:2015-11-20 07:58:00

标签: sql sql-server

//_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'。

附近的语法不正确

1 个答案:

答案 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