dynamic sql query filterin in csharp

To create a dynamic SQL query with filtering in C#, you can use StringBuilder to dynamically build the SQL query string, and SqlParameter to pass in the filter criteria.

Here is an example code snippet:

main.cs
string filter = "apple"; // example filter value
StringBuilder query = new StringBuilder();
query.Append("SELECT * FROM Fruits WHERE 1 = 1");

if (!string.IsNullOrWhiteSpace(filter))
{
    query.Append(" AND FruitName LIKE @Filter");
}

using (SqlConnection connection = new SqlConnection("connectionString"))
{
    using (SqlCommand command = new SqlCommand(query.ToString(), connection))
    {
        if (!string.IsNullOrWhiteSpace(filter))
        {
            command.Parameters.AddWithValue("@Filter", "%" + filter + "%");
        }

        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                // process the resultset
            }
        }
    }
}
762 chars
29 lines

In this example, the StringBuilder is used to dynamically create a SQL query string based on the presence of the filter value. The SqlParameter is used to pass in the filter value in a secure and parameterized way to avoid SQL injection attacks.

Finally, the SQL query is executed using the SqlCommand object, and the results are read using a SqlDataReader.

gistlibby LogSnag