Search code examples
sqlsql-server-2014-express

SQL conditional 'WHERE' clause


I'm trying to do a conditional AND within a SQL WHERE clause. A pseudo code example is below.

SELECT
    *
FROM [Table]
WHERE
    [A] = [B]
AND
    IF EXISTS
    (
        SELECT TOP 1 1
        FROM [Table2]
        WHERE
            1 = 1
    )
        BEGIN
            --Do conditional filter
            (Table3.[C] = Table.[A])
        END

So, if the if condition is true, the rest of the filtering should be applied. Any help please?


Solution

  • This should cater for the chance of the conditional filter and without

    AND
    (
        NOT EXISTS
        (
            SELECT TOP 1 1
            FROM [Table2]
            WHERE
                1 = 1
        )
        OR
        (
            EXISTS
            (
                SELECT TOP 1 1
                FROM [Table2]
                WHERE
                    1 = 1
            )
            AND
            (
                --Do conditional filter
                (Table3.[C] = Table.[A])
            )
        )
    )