if/else in where clause

  • Hi all,

    Would like to ask how following T-SQL to be simplify it (without using if/else, join both the where clause into one statement). Thanks in advance.

    if @DateType = 1

    select a,b,c

    from abc

    where (

    (len(@P1) > 0 and DocNo like @P1 + '%') or

    (len(@P1) <= 0 and ADate between @FromDate and @ToDate)[/color]
    )

    else
    select a,b,c
    from abc
    where (
    [color=#red] (len(@P1) > 0 and DocNo like @P1 + '%') or

    (len(@P1) is null and BDate between @FromDate and @ToDate)

    )

    end

  • Try something like this.

    select a,b,c

    from abc

    where (

    ((len(@P1) > 0 and DocNo like @P1 + '%') or

    (len(@P1) 0 and DocNo like @P1 + '%') or

    (len(@P1) is null and BDate between @FromDate and @ToDate))

    AND @DateType 1

    )

    I don't have anything to test with, but here is an example using a system table.

    DECLARE @DateType int

    SET @DateType = 1

    SELECT sysdatabases.dbid FROM sysdatabases

    WHERE

    (sysdatabases.dbid < 4 AND @DateType =1)

    OR

    (sysdatabases.dbid < 20 AND @DateType 1)

Viewing 2 posts - 1 through 1 (of 1 total)

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