Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to fetch data from a SQL Server database using values from a dropdown list.

My query is

select  Age,City,State,Caste,IncomeMin,IncomeMax from Ruser
where (Age between '" + drplistagemin.SelectedItem + "' and '" + drplistagemax.SelectedItem + "') 
and (Religion= '" + drplistreligion.SelectedItem + "')  ");

What I need to understand is how to build this query if the value of the Religion dropdown is optional rather than compulsory?

share|improve this question
1  
SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection –  marc_s May 19 '13 at 8:30

3 Answers 3

In the notation of @Pratik:

SELECT Age,City,State,Caste,IncomeMin,IncomeMax
FROM Ruser
WHERE age BETWEEN @minAge AND @maxAge
AND religion = coalesce(@religion, religion);
share|improve this answer

I never recommend using direct command methods but you can give try to below query:

SELECT Age,City,State,Caste,IncomeMin,IncomeMax
FROM Ruser
WHERE age BETWEEN @minAge AND @maxAge
AND religion LIKE CASE WHEN @religonVal IS NULL THEN '%' ELSE @religonVal END;

Please note : You can used appropriate values to the variables from stored procedure. Let me know if it works as you want.

share|improve this answer
    
IF i just select age from age dropdownlist , then it doesnt work , –  Kapil Dev May 19 '13 at 8:18
    
it works only when i select both drop down list age and religion –  Kapil Dev May 19 '13 at 8:19
    
you need to adjust parameter selection in front end c#,asp.net where using if else conditions over selection. Pass NULL as default value for religion in your case. –  Pratik May 19 '13 at 15:29

One way to do it would be to use a NULL value for the religion, and translate that into a % for a LIKE comparison in SQL Server.

Also - I would always separate the UI code (event handler etc.) from the actual database access code - so do something like this in a separate DataAccess class (and not stick this directly into the page code-behind) :

public List<RuserResults> GetRuserResults(int minAge, int maxAge, string religion)
{
    string selectStmt = "SELECT Age, City, State, Caste, IncomeMin, IncomeMax FROM Ruser " +
                        "WHERE Age BETWEEN @MinAge AND @MaxAge " + 
                        "AND Religion LIKE @religion";

    // set up your connection and command objects
    using(SqlConnection conn = new SqlConnection("--your-connection-string-here--"))
    using(SqlCommand cmd = new SqlCommand(selectStmt, conn))
    {
        // define the parameters
        cmd.Parameters.Add("@MinAge", SqlDbType.Int).Value = minAge;
        cmd.Parameters.Add("@MaxAge", SqlDbType.Int).Value = maxAge;
        cmd.Parameters.Add("@Religion", SqlDbType.VarChar, 100);

        // if you passed a value for the method parameter - use that value
        if(!string.IsNullOrEmpty(religion))
        {
           cmd.Parameters["@Religion"].Value = religion + "%";
        }
        else  // if no value was passed - just search for all religions
        {
           cmd.Parameters["@Religion"].Value = "%";
        }

        List<RuserResult> results = new List<RuserResult>();

        // open connection, run query, close connection
        conn.Open();

        using(SqlDataReader reader = cmd.ExecuteReader())
        {
           while(reader.Read())
           {
               // read the values, convert to a "RuserResults", and pass it back
               results.Add(ConvertReaderToRuserResult(reader));
           }
        }

        conn.Close();

        // return the results
        return results;
    }
}

And then from your ASP.NET page, you can call this

int minAge = Convert.ToInt32(drplistagemin.SelectedItem);
int maxAge = Convert.ToInt32(drplistagemax.SelectedItem);
string religion = drplistreligion.SelectedItem;

List<RuserResult> results = GetRuserResults(minAge, maxAge, religion);

// do something with the results returned here....
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.