dynamic sql query filtering in csharp

To create a dynamic SQL query with filtering in C#, you can use SQL parameters to avoid SQL injection attacks. You can build your SQL query dynamically based on user inputs, and use SqlParameters to safely pass user inputs to the SQL query.

Here is an example of how to implement dynamic SQL querying in C# with filtering:

main.cs
string query = "SELECT * FROM myTable WHERE 1=1 "; // Starting query

if (!string.IsNullOrEmpty(name))
{
    query += " AND name=@name"; // Append to query
    parameters.Add(new SqlParameter("@name", name)); // Add parameter
}
if (age.HasValue)
{
    query += " AND age=@age"; // Append to query
    parameters.Add(new SqlParameter("@age", age)); // Add parameter
}
// Add more if statements for additional filter parameters

// Execute query
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (SqlCommand command = new SqlCommand(query, connection))
    {
        foreach (SqlParameter parameter in parameters)
        {
            command.Parameters.Add(parameter);
        }
        using (SqlDataReader reader = command.ExecuteReader())
        {
            // Read results
        }
    }
}
854 chars
31 lines

In this example, we start with a base SQL query and build upon it with conditional statements based on user inputs for filtering criteria. We then add the SQL parameters to the SqlCommand object to safely pass user inputs to the SQL query. Finally, we execute the query and read the results.

gistlibby LogSnag