Domanda

We have a stored procedure that takes in a few parameters, but only one of these parameters has a value and that is used to filter the result set. The SELECT statement itself contains multiple joins and is somewhat long.

To avoid copy-pasting the query multiple times, I want to be able to use an IF or CASE statement in the WHERE clause. The problem is, we are using full-text index and the CONTAINS statement, and I'm not quite sure how to inject an IF or CASE statement inside/outside the CONTAINS clause, something like this:

SELECT * FROM [QUERY]
WHERE( 
   IF @Filter1 IS NOT NULL
   BEGIN
    CONTAINS(SomeColumn, @Filter1)
   END
   ELSE IF @Filter2 IS NOT NULL
   BEGIN
    CONTAINS(AnotherColumn, @Filter2)
   END)

which obviously doesn't work. I can't put the SELECT query in a view or function either because the result set currently doesn't specify a unique index key, i.e. cannot be full-text indexed (right now tables are full-text indexed individually to address this issue).

So is there a way to achieve this? I could potentially copy-pase the long SELECT query inside different IF statement for each filter, but that gets very ugly. Any help is appreciated.

È stato utile?

Soluzione

Maybe I'm overlooking something, but couldn't you structure the WHERE as follows...

WHERE ((@Filter1 IS NOT NULL) AND CONTAINS(..)) OR ((@Filter2 IS NOT NULL) AND CONTAINS(..))

That's how we do it for a similar scenario.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top