0

I have a SQL statement with parameters eg.

SELECT * 
FROM persons 
WHERE id = @id 
  AND firstName = @firstname
   OR surname = @surname

I would like to use c# to rewrite the statement based on the parameters supplied at run-time.

Example if at runtime, @firstname is not provided, then my SQL should be re-written to

SELECT * 
FROM persons 
WHERE id = @id OR surname = @surname

This is what I have so far.

public class SqlRewriter
{
    public string RewriteSql(List<string> passedRuntimeParameter )
    {
        var sql = @"SELECT * FROM persons 
                 WHERE id=@id AND firstName=@firstname
                 or surname=@surname";
        /**
         * todo parse the sql and compare with passedRuntimeParameter.
         * todo reconstruct the sql based on parsed parameters
         */

        return sql;
    }
}
4

4 回答 4

3
IF @firstname = Null {
    SELECT * FROM persons WHERE id=@id or surname=@surname
} else {
    SELECT * FROM persons WHERE id=@id AND firstName=@firstname or surname=@surname
}
于 2013-04-04T12:14:19.773 回答
2

好吧,您可以改写:

SELECT * FROM persons WHERE
    (id=@id OR @id is null) AND
    (
        (firstName=@firstname OR @firstname is null) OR
        (surname=@surname OR @surname is null)
    )

并在您没有​​指定值时发送空值

或者如果你真的想省略参数,你可以像 mikey 或 Patrick 回答的那样做。

但请记住,如果您真的想根据您拥有的参数进行查询(id 和 surname,或者只是firstname,或者firstname + surname),如果您愿意自定义,您最终会遇到很多 ifs您的查询字符串。

于 2013-04-04T12:20:07.043 回答
0
if FirstName==NULL
{
 sqlQuery="ConstructYourQueryfor This condition";
}
else
{
 sqlQuery="Another Construction for else Query";
}

使用 SQL 命令参数

using(var connection = new SqlConnection("your connectionstring goes here"))
{
    using(var command = new SqlCommand(sqlQuery,                                                                          connection))
    {
        command.Parameters.AddWithValue("@id ", yourIDvalue);
        command.Parameters.AddWithValue("@firstname ", FirstName);    
        command.Parameters.AddWithValue("@surname", surname);    
        var reader = command.ExecuteReader();
    }
}
于 2013-04-04T12:14:36.807 回答
0

您正在使用很好的参数化查询。您可以使用 if 块来执行您想要的操作,甚至可以使用内联 if。

string query = "SELECT * FROM persons WHERE id=@id" + ((firstname!=null&&firstname!=string.Empty) ? " AND firstname=@firstname OR surname=@surname" : " AND surname=@surname");
// setup command with query
// setup parameters (remember to check if you need to provide a firstname parameter or not)

祝你好运

于 2013-04-04T12:14:47.103 回答