Skip to content
Advertisement

Issue with SQL Server select statement

I need help with a select statement that I’m currently struggling with. The scenario is this:

select * from mytable WHERE isActive=1

  1. and if only id is provided, select everything where the id=@id
  2. if firstname and lastname is provided, then select everything where firstname=@firstname and lastname=@lastname regardless of the ID
  3. if either firstname or lastname is provided, select everything where firstname=@firstname or lastname=@lastname regardless of the ID again
  4. if id, firstname and lastname provided, just select where firstname=@firstname and lastname=@lastname regardless of the ID again

Here’s my query:

somehow I’m not getting the results expected, for example when I provide both firstname and lastname, it shows everyone with the firstname regardless of their lastname 🙁

Please help

Advertisement

Answer

Not sure if you need a union, especially UNION ALL, but you have two choices. First one is pretty, it works with small data sets. The second option looks ugly, but gives you almost guaranteed best performance.


That is with no difference between #2 & #4, unless you can describe it.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement