简体   繁体   中英

Best practice to build dynamic SQL queries

I am looking for some tips and tricks how to build dynamic queries. I am having an application which lets the user search 10 fields in the database table. Depending on which fields in the UI are filled with a value the query should search in an additional field in the DB.

Currently I am trying to build the query using StringBuilder and adding the where clause but I really don't like this and I am wondering if there is a better way to do this, for example with LINQ if possible.

Maybe someone can bring up ideas or better some example code. Thanks and have a nice day!

With LINQ it is pretty trivial:

IQueryable<User> users = db.Users;

if(name != null) users = users.Where(u => u.Name == name);
if(dept != null) users = users.Where(u => u.Dept == dept);
...

var page = users.OrderBy(u => u.Name).Take(100).ToList();

Each successive Where composes the query with more filters; exactly what you want.

With raw TSQL, StringBuilder isn't unreasonable; just make sure that you fully parameterize it. This might mean adding parameters in each term; for example:

...
if(name != null) {
    sql.Append(" and u.Name = @name");
    cmd.Parameters.AddWithValue("name", name);
}
if(dept != null) {
    sql.Append(" and u.Dept = @dept");
    cmd.Parameters.AddWithValue("dept", dept);
}
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM