0

I have a windows form where the user can input multiple values in multiple textboxes for faster search results. But when running, it takes only 1st parameter i.e., the fullname and ignores the other. Don't know the reason why is it so. Am getting the full table in the result which I don't want. I have created a stored procedure.

CREATE PROCEDURE USP_SELECT_CUSTOMERS (
    @fullName VARCHAR(100) = '',
    @Address VARCHAR(100) = '',
    @ContactNumber VARCHAR(15) = ''
)
AS BEGIN
    SELECT * FROM Customers 
        WHERE ((ContactName LIKE @fullName+'%') OR (@fullName = ''))
            OR ((Address LIKE @Address+'%') OR (@Address = ''))
            OR ((Phone LIKE @ContactNumber+'%') OR (@ContactNumber = ''))
END

Here's how am i calling the stored procedure in my program :=>

private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("USP_SELECT_CUSTOMERS", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@fullName", txtFullName.Text);
                cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
                cmd.Parameters.AddWithValue("@ContactNumber", txtContactNumber.Text);                
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    dataGridView1.Visible = true;
                    dataGridView1.DataSource = ds.Tables[0];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            finally
            {
                con.Close();
            }
        }

What I want is even if the 1 textbox if filled, the stored procedure should give the desired output. Kindly help me out in this.

Thanks.

6
  • 1
    Those ORs at the beginning of the 2nd two lines should probably be ANDs? Commented Mar 1, 2014 at 10:16
  • Can you add the code you are using to call the stored procedure? As it stands, the stored procedure you're using will return the full table unless you are passing all three parameters as values which are not '' to the stored procedure. Changing the ORs to ANDs would fix that. Commented Mar 1, 2014 at 10:17
  • @thudbutt i have edited the question, kindly look into it. Commented Mar 1, 2014 at 10:23
  • 1
    Raging Bull's answer below will fix your problem with the whole table being returned when only one textbox is filled. Do Address and ContactNumber still get ignored if you make the below changes? Commented Mar 1, 2014 at 10:27
  • @user3095539 - I have added an answer that in combination with Raging Bull's should give you the results you're after. Commented Mar 1, 2014 at 11:20

5 Answers 5

1

You should AND instead of OR. Try this:

CREATE PROCEDURE USP_SELECT_CUSTOMERS (
    @fullName VARCHAR(100),
    @Address VARCHAR(100),
    @ContactNumber VARCHAR(15)
)
AS BEGIN
    SELECT * FROM Customers 
        WHERE ((ContactName LIKE @fullName+'%') OR (@fullName = ''))
            AND ((Address LIKE @Address+'%') OR (@Address = ''))
            AND ((Phone LIKE @ContactNumber+'%') OR (@ContactNumber = ''))
END

It will give you the desired result.

See SQL Fiddle

EDIT: As per your requirement, use this query:

CREATE PROCEDURE USP_SELECT_CUSTOMERS 
(
        @fullName VARCHAR(100),
        @Address VARCHAR(100),
        @ContactNumber VARCHAR(15)
)
AS 
BEGIN
    IF LEN(@fullName)=0
        SET @fullName='$$$'
    IF LEN(@Address)=0
        SET @Address='$$$'
    IF LEN(@ContactNumber)=0
        SET @ContactNumber='$$$'

    SELECT * FROM Customers 
        WHERE ((ContactName LIKE @fullName+'%'))
           OR ((Address LIKE @Address+'%'))
           OR ((Phone LIKE @ContactNumber+'%'))
END

Added a simple trick. See SQL Fiddle.

Replace $$$ with anything which will not be included in ContactName,Address and Phone fields.

Sign up to request clarification or add additional context in comments.

6 Comments

Not a single result if I use AND instead of OR.. I want that even if a single textbox is filled, the result should come.
Ok. Nice. 1 more question, what if I want multiple rows to be fetched ? Like if there are 2 people with same name, how to show should i display it ?
Since you are using LIKE operator, it will select both of them who have same name. See this example
thanks bud. now what if user inputs name as maria and address as Åkergatan 24. the result is not being fetched. I want both the results from northwind database , hence in my question, i had used OR
Now I get your problem. See Edit in my answer.
|
0

I agree with what @Baljeet said ... it should fetch the desired results. Make Sure you have done the following 1) Intitilise the the parameter value as '' (blank) if varchar eg @fullName VARCHAR(100) = ''

and in where condition like given below, people tend to make mistake in the second condtion of OR. Make sure the condtion is Where ( 'Field Name' like '@parametername' OR @parametername ='')

 WHERE ((ContactName LIKE @fullName+'%') OR (@fullName = ''))

Comments

0

As well as carrying out the changes in Raging Bull's answer, try adding ISNULL to your second check for each parameter. So

@fullname = ''

becomes

ISNULL(@fullname, '') = ''

and do the same for the other two parameters.

From memory Sql Server will only use the default value you specify for the parameters, if you don't pass the parameter at all, if you do pass the parameter but the value is null then your query will only work with the change above.

Comments

0

My suggestion would be to define the stored procedure with default value of parameters as NULL. Database is good at handling NULL values and it would keep the stored procedure definition simple.

Then pass the parameters from C# conditionally:

if(!String.IsNullOrEmpty(txtFullName.Text)) 
    cmd.Parameters.AddWithValue("@fullName", txtFullName.Text);
//...add other parameters the same way

Stored procedure should be defined as below:

CREATE PROCEDURE USP_SELECT_CUSTOMERS (
    @fullName VARCHAR(100) = NULL,
    @Address VARCHAR(100) = NULL,
    @ContactNumber VARCHAR(15) = NULL
)
AS BEGIN
    SELECT * FROM Customers 
        WHERE ContactName LIKE @fullName+'%'
            OR Address LIKE @Address +'%'
            OR Phone LIKE @ContactNumber+'%'
            --in case you want to select all rows if all the parameters are NULL then add
            --this condition too 
            --OR 1 = CASE WHEN COALESCE(@fullName, @Address, @ContactNumber,'') = '' THEN 1 ELSE 0 END
END

Comments

0

IMO,

this should do

CREATE PROCEDURE USP_SELECT_CUSTOMERS (
    @fullName VARCHAR(100) = '',
    @Address VARCHAR(100) = '',
    @ContactNumber VARCHAR(15) = ''
)
AS BEGIN
    SELECT * FROM Customers 
        WHERE ((ContactName LIKE @fullName+'%') OR (@fullName = ''))
            AND ((Address LIKE @Address+'%') OR (@Address = ''))
            AND ((Phone LIKE @ContactNumber+'%') OR (@ContactNumber = ''))
END

using northwind i get following , command with EXEC USP_SELECT_CUSTOMERS 'maria','','' enter image description here

exec USP_SELECT_CUSTOMERS 'maria','Åkergatan 24','' --result row is displayed now check the next pic enter image description here

** exec USP_SELECT_CUSTOMERS 'maria','Åkergatan 24 ','' ** --because of extra space end of address parameter you could see no result enter image description here

5 Comments

It is giving, but the whole table is being fetched as result and not the desired result.
can you share what extact values were send ?
if you are having northwind database in sql management studio, you can do it coz i am also sending the values from my form like for name i am giving Maria and when i press the search button, not a single result is fetched..
same here. now what if user inputs name as maria and address as Åkergatan 24. the result is not being fetched. i want both the results , hence in my question, i had used OR
i tried again with name and address inputs i see the results !! there is no reason it shouldnt come for you except the address is not exact. see the updated picture in a while and i suggest you update sp with '%' + @Address+'%'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.