简体   繁体   中英

Search with multiple parameters in SQL Server

This question is related to both c# and SQL Server.

I want to figure out how to do a custom search.

I have three tables

Customer

CusId, Name, Telephone

Employee

EmpId, Name, Job

Appointment

AppId, Date, EmpId, CusId

My C# form has three checkboxes. I want to find the data according to those checked values.

Ex: when customer,employee,app check boxes have selected, I want to find data on depending on all those three values.

When only two or one is selected I want to search depending on those selection. Here there will be total 6 combinations.

How to write a query to get correct result when I pass those values as parameters to a stored procedure.

Do I have to write 6 stored procedures to get the result?

Are there any methods to do this easily?

Please help me to fix this matter. Thanks in advance.

With a query such as the below (would suggest in a stored proc):

-- Parameters to a SQL sproc
DECLARE @CustID INT, @EmpID INT, @AppointmentID INT

-- Set Parameters here for testing

SELECT *
FROM Appointment as A
INNER JOIN Employee as E
  ON E.EmpID = A.EmpId
INNER JOIN Customer as C
  ON C.CusID = A.CusID
WHERE (@CustID IS NULL OR C.CUsID = @CustID)
AND (@EmpID IS NULL OR E.EmpID = @EmpID)
AND (@AppointmentID IS NULL OR A.AppID = @AppointmentID)

You then need to pass in the parameters appropriately, either an ID if selected, or null if not filtering on one item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM