SQL Server Conditional where logic

4bbkushb  于 2023-11-16  发布在  其他
关注(0)|答案(2)|浏览(139)

I have a SQL Server stored procedure where I want to add a conditional clause based on a parameter ( @action ). So if a action is X or Y then I don't want to use the where clause (and want to fetch all records), but if the action is NOT X OR Y then I want to fetch only those records that match with other parameter ( @username ).

I am trying this:

AND CASE 
        WHEN (ISNULL(@action, '') = 'X' OR ISNULL(@action, '') = 'Y')
            THEN a.name 
            ELSE a.name 
    END = @username

This seems to work ok if the action is not X or Y, however it does not return any data if the action is X.

How can I return all records (basically ignore the Where clause) if the action is X or Y?

c7rzv4ha

c7rzv4ha1#

Just use plain conditions - essentially expressing your English description using SQL:

WHERE (@action NOT IN ('X', 'Y') OR a.name = @username)
-- plus any other conditions
1qczuiv0

1qczuiv02#

maybe this -

AND (CASE 
        WHEN (ISNULL(@action, '') = 'X' OR ISNULL(@action, '') = 'Y')  THEN 1
        WHEN ISNULL(@action, '') <> 'X' AND  ISNULL(@action, '') <> 'Y' AND a.name = @username THEN 1
            ELSE 0 
    END) = 1

相关问题