1

I need to write a store procedure for SQL Server. And it need to be something like:

Select * from tblSomething
Where param in (If param1 like 'string' select * from tblTable where condition1
            Else select * from tblTable where condition2)

The problem all the if else examples print something and don't return select query. Can you help???

Jean-Rémy Revy
  • 5,607
  • 3
  • 39
  • 65
GLev
  • 29
  • 1
  • 4
  • 2
    Is it just me or does this question get more confusing due to the example posted? Provide sample data, expected results, etc. – JonH May 31 '11 at 19:23
  • It's just you. This is not a plain SQL SELECT statement. – DOK May 31 '11 at 19:27

2 Answers2

1
IF param1 LIKE 'string'
    SELECT *
        FROM tblSomething
        WHERE param IN (SELECT * FROM tblTable WHERE condition1)
ELSE
    SELECT *
        FROM tblSomething
        WHERE param IN (SELECT * FROM tblTable WHERE condition2)
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
  • this works but you could also make this a boolean type expression using an OR. Ya it might be slower but its also smaller in size. +1 either way. – JonH May 31 '11 at 19:25
1

I'm not sure if that's what you're looking for.

IF EXISTS (SELECT * FROM tblSomething WHERE param1 like 'string')
  SELECT * FROM tblSomething WHERE param IN (SELECT * FROM tblTable WHERE condition1)
ELSE
  SELECT * FROM tblSomething WHERE param IN (SELECT * FROM tblTable WHERE condition2)

I'm new to TSQL so any comments to improve will be appreciated.

  • 1
    FYI about IF EXISTS (SELECT *...) ... http://stackoverflow.com/questions/3994040/sql-server-if-exists/3994059#3994059 or http://stackoverflow.com/questions/6137433/where-does-the-practice-exists-select-1-from-come-from/6137474#6137474 – gbn Jun 09 '11 at 21:03
  • Well I see; Thanks for the hint. I'll update it to `EXISTS (SELECT * ...`. And what about `TOP 1` in the query. Will `EXISTS (SELECT TOP 1 * FROM` be faster than `EXISTS (SELECT * FROM` ? –  Jun 09 '11 at 21:22
  • 2
    Exactly the same. The TOP and select list are ignored (as per ANSI links) – gbn Jun 09 '11 at 21:23
  • 1
    I'm using this very often and I thought the `TOP 1 0` is faster but now I see it's even slower because it take some additional time to parse the `TOP 1` statement. Thanks man. –  Jun 09 '11 at 21:28