从c#方法可选参数构建的SQL查询

时间:2015-07-20 16:14:55

标签: c# sql sql-server

我有一个应用程序,我需要允许用户选择月/年/用户,然后使用这些结果进行SQL查询。困扰我的部分是我希望每个参数都是可选的。

因此,如果我选择一个用户,但没有日期信息,我希望始终能够看到所有该用户的结果。如果我只选择一个月,我想显示该月的当前年份,等等。我使用此代码与月/用户合作:

    protected void btnView_Click(object sender, EventArgs e)
    {
        gvbind(Convert.ToInt32(ddlMonth.SelectedValue), ddlWebmasters.SelectedValue.ToString(), Convert.ToInt32(ddlYear.SelectedValue));
    }

    protected void gvbind(int month = 0, string user = "")
    {
        string query = "Select * from WebLogs w inner join(select max(ID) as id, username from WebLogs group by Username) w2 on w.id = w2.id and w.Username = w2.username where Year(LogEntryDate) = year(getDate())";

        if (user.Length > 0 && month > 0)
        {
            query = "SELECT * FROM [WebLogs] WHERE ([Username] = '" + user + "') AND month(LogEntryDate) =" + month + " AND year(LogEntryDate) = year(getdate()) ORDER BY [ID]";
        }
        else if (user.Length > 0 && month == 0)
        {
            query = "SELECT * FROM [WebLogs] WHERE ([Username] = '" + user + "') AND year(LogEntryDate) = year(getdate()) ORDER BY [ID]";
        }
        else if (user.Length == 0 && month > 0)
        {
            query = "SELECT * FROM [WebLogs] WHERE month(LogEntryDate) =" + month + "AND year(LogEntryDate) = year(getdate())  ORDER BY [ID]";
        }

然后将查询传递给SqlCommand,但是现在我已经添加了一年,这实在是效率低下,而且我知道必须有一种简单的方法来解决这个问题。

1 个答案:

答案 0 :(得分:0)

protected void gvbind(int month = 0, string user = "")
    {
        //string query = "Select * from WebLogs w inner join(select max(ID) as id, username from WebLogs group by Username) w2 on w.id = w2.id and w.Username = w2.username where Year(LogEntryDate) = year(getDate())";

        string query = string.Empty;
        query = "SELECT * FROM [WebLogs] WHERE "+((user.Length>0)?"([Username] = '" + user + "') AND ":"") +   ((month>0)?" month(LogEntryDate) =" + month+ "AND ":"") + " year(LogEntryDate) = year(getdate()) ORDER BY [ID]";

    }