'Remove hardcoded WHERE (true) from sql statement in order to append AND dynamically

We are using quite a lot kind of pattern for SQL server table lookups like this one bellow:

using (SqlCommand cmd = new SqlCommand())
    {
        StringBuilder stringBuilder = new StringBuilder($"SELECT * FROM {tableName} WHERE 1=1");
        if (!String.IsNullOrEmpty(queryObj?.StudentName))
        {
            stringBuilder.Append(" AND StudentName=@StudentName");
            cmd.Parameters.AddWithValue("@StudentName", queryObj.StudentName);
            if (queryObj?.StudentTeacher != null)
            {
                stringBuilder.Append(" AND StudentTeacher=@StudentTeacher");
                cmd.Parameters.AddWithValue("@StudentTeacher", queryObj.StudentTeacher);
            }
            else
            {
                stringBuilder.Append(" AND StudentTeacher IS NULL");
            }
        }
        cmd.CommandText = stringBuilder.ToString();
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = connection;
        connection.Open();

    ========== code ommited for brevity ===========
        
    }

It is obvious that we have condition WHERE 1=1 (and it is really nasty IMHO and moreover you can imagine what could happen if for some reason AND(s) don't exist and table has billion of records) in order to narrow filters depending on other conditions.

Is there some better approach for appending additional AND filters and how to avoid WHERE 1=1 and still be able to construct appropriate queries with additional filters?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source