Conditional where clause

  • Hi ,

    I wrote a stored proc where I need to evaluate a bit flag and if true append "NOT IN" clause. I don't want to use prepared statement.

    I tried following but it failed. Can I use Case or anyother statement to make it work ?

     

    table Test (id int, name varchar(10);

    table data

    ID-Name

    1  -A

    2 -B

    3 -C

    declare @myFlag bit;

    begin

    set @myFlag=1;

    select * from test

    where 1=1

    AND (@myFlag=1 and name not in ('A','C')) -- not in should only work when @myFlag=1

    end

     

     

  • DROP TABLE IF EXISTS #Test;

    CREATE TABLE #Test
    (
    id INT
    ,name VARCHAR(10)
    );

    INSERT #Test
    (
    id
    ,name
    )
    VALUES
    (1, 'A')
    ,(2, 'B')
    ,(3, 'C');

    DECLARE @myFlag BIT = 1;

    --SET @myFlag = 0;

    SELECT *
    FROM #Test
    WHERE (@myFlag <> 1)
    OR
    (
    @myFlag = 1
    AND name NOT IN ( 'A', 'C' )
    );

    If you haven't even tried to resolve your issue, please don't expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.

  • Thank you Phil.

    but why the addition of "@myFlag <> 1)" make it work ?

    (@myFlag <> 1)

    OR

    (

    @myFlag = 1

    AND name NOT IN ( 'A', 'C' )

    );

     

    Phil Parkin wrote:

    DROP TABLE IF EXISTS #Test;

    CREATE TABLE #Test
    (
    id INT
    ,name VARCHAR(10)
    );

    INSERT #Test
    (
    id
    ,name
    )
    VALUES
    (1, 'A')
    ,(2, 'B')
    ,(3, 'C');

    DECLARE @myFlag BIT = 1;

    --SET @myFlag = 0;

    SELECT *
    FROM #Test
    WHERE (@myFlag <> 1)
    OR
    (
    @myFlag = 1
    AND name NOT IN ( 'A', 'C' )
    );

  • but why the addition of "@myFlag <> 1)" make it work ?

    It's straight logic.

    You had two scenarios:

    1. SELECT all rows if myFlag not 1
    2. SELECT some rows if myFlag = 1

    I handled each of those scenarios with the OR in the WHERE clause.

     

    If you haven't even tried to resolve your issue, please don't expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.

  • You don't need the extra check on the flag:

    WHERE @myFlag <> 1 OR name NOT IN ('A', 'C')

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply