首页 > 解决方案 > Avoid string concatenation for parameters when they are null

问题描述

In C# I have query like that:

string query = "SELECT * FROM product WHERE name = @name";
...
da.SelectCommand.Parameters.AddWithValue("@name", name);

if (price.HasValue)
{
    query += " AND price = @price";
    da.SelectCommand.Parameters.AddWithValue("@price", price.Value);
}
..

How to avoid if statements? In above example I have only one parameter but in my code I have several parameters what is mean that I have several if statements

标签: c#sqlparameters

解决方案


you can do it with SQL query without any IFs , something like :

string query = "SELECT * FROM product WHERE name = @name AND (@price IS NULL OR price = @price)";

推荐阅读