Stored Procedure dynamic / generic where

依然范特西╮ 提交于 2019-12-12 02:52:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!