Search code examples
c#mysqlparameterized-query

Parameterized query with dynamic where clasue


So I have this query:

var comm = @"SELECT * FROM `TABLE` ";

bool hasWhere = false;

if ( model.Serial > 0 ) {
    comm += " WHERE `SERIAL` LIKE '%" + model.Serial + "%' ";
    hasWhere = true;
}

if ( model.Id.HasValue && model.Id.Value > 0 ) {
    if ( !hasWhere ) {
        comm += " WHERE `NUIP` LIKE '%" + model.Id.Value + "%' ";
        hasWhere = true;
    } else
        comm += " AND `NUIP` LIKE '%" + model.Id.Value + "%' ";
}

if ( model.Date.HasValue ) {
    if ( !hasWhere ) {
        comm += " WHERE `DATE` = '" + model.Date.Value + "' ";
        hasWhere = true;
    } else
        comm += " AND `DATE` = '" + model.Date.Value + "' ";
}
....
....
....

I've read about parameterized queries against SQL Injection and so on. The thing is, given that I'll have a dynamic number of WHERE clauses (based on the search model),how can I parameterize the query? I can't put WHERE a = @A AND b=@B... because the user must not need to search based on all the columns.

Any idea? thanks in advance.

P.S: Can't use LINQ or something similar to that (-business rules-).


Solution

  • You can still use SQL parameterized query with where close (WHERE will be sort of dynamic). For example I have paramater @SerialNum that is NULL and I have a parameter @Code that equals to 455.

    SELECT
         Column1
        ,Column2
    FROM 
         YourTable
    WHERE
        (
            @SerialNum IS NULL
            OR
            Column3 LIKE '%' + @SerialNum + '%'
        )
        AND
        (
            @Code IS NULL
            OR
            Column4 LIKE '%' + @Code + '%'
        )