问题
I know there a several Answers to this question but it i thing non of them fit my needs so here comes my question
based on this SQL Fiddle i will explain you what i'm trying to achieve.
How you can see it's just a simple table of persons so now i want to get a person by his id so i have to write a simple query SELECT * FROM Persons WHERE PersonID =@PersonID;
to get him i can do this now for any possible combination and i will get tons of stored procedures just for this Table
So here is my question how do i create a stored procedure that combines all this functionality in one. So that i will be able to just give here the LastName 'Schmidt' and get all Schmidt's. than ask her for all Paul's in NewYork
to make it easyer:
- it's enough if this Stored Procedure is only able to handle "AND"
- also it's enough if it select all columns
回答1:
Try something like this:
SELECT * FROM Persons
WHERE PersonID = ifnull(@PersonID,personID)
AND LastName = ifnull(@LastName,LastName)
AND FirstName = ifnull(@FirstName, FirstName)
AND Address = ifnull(@Address,Address)
AND City = ifnull(@City,City)
and see it on SQL Fiddle.
来源:https://stackoverflow.com/questions/18469186/stored-procedure-dynamic-generic-where