How do I create a stored procedure that will optionally search columns?

前端 未结 10 689
醉话见心
醉话见心 2020-12-08 08:30

I\'m working on an application for work that is going to query our employee database. The end users want the ability to search based on the standard name/department criteria

10条回答
  •  庸人自扰
    2020-12-08 09:34

    My first thought was to write a query something like this...

    SELECT EmpId, NameLast, NameMiddle, NameFirst, DepartmentName
      FROM dbo.Employee
           INNER JOIN dbo.Department ON dbo.Employee.DeptId = dbo.Department.Id
     WHERE IdCrq IS NOT NULL
           AND
           (
              @bitSearchFirstName = 0
              OR
              Employee.NameFirst = @vchFirstName
           )
           AND
           (
              @bitSearchMiddleName = 0
              OR
              Employee.NameMiddle = @vchMiddleName
           )
           AND
           (
              @bitSearchFirstName = 0
              OR
              Employee.NameLast = @vchLastName
           )
           AND
           (
              @bitSearchDepartment = 0
              OR
              Department.Id = @intDeptID
           )
    

    ...which would then have the caller provide a bit flag if they want to search a particular field and then supply the value if they are to search for it, but I don't know if this is creating a sloppy WHERE clause or if I can get away with a CASE statement in the WHERE clause.

    As you can see this particular code is in T-SQL, but I'll gladly look at some PL-SQL / MySQL code as well and adapt accordingly.

提交回复
热议问题