1

I am using asp .net web form search in c#, for example with fields: - name - fruit

I want to write a sproc that can search name or fruit. If I knew that both would have values, I would pass two parameters into the sproc and would write:

Select * from myTable where name =@name and fruit = @fruit

However sometimes, either name or fruit could be empty. Without writing a separate search for fruit and name. How would I achieve this?

I would prefer not to create a dynamic query if possible, but if this is the only way how would I write it?

4 Answers 4

4

You'll need to make sure that empty strings aren't passed as arguments instead of null, but the following should work. I'm pretty sure, though, that if the user doesn't input anything the form value will be null.

 select * from myTable
 where (@name is null or name = @name) and (@fruit is null or fruit = @fruit)
Sign up to request clarification or add additional context in comments.

1 Comment

when user passes null, null this solution will return all records in the table
1

maybe:

SELECT * FROM myTable WHERE name Like '%' + @name AND fruit LIKE '%' + @fruit

Comments

0
select * from myTable 
where 
   (name = @name and fruit = @fruit)
   or (name = @name and @fruit is null)
   or (fruit = @fruit and @name = is null )

Comments

0
select * from myTable where name = isnull(@name, name) and fruit = isnull(@fruit, fruit)

Will return the entire table if both @name and @fruit is null. If that is a problem, you better add some additional logic to the SP.

Comments

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.