Search code examples
sql-serverstored-procedurescasewhere-clauseprocedure

An expression of non-boolean type specified in a context where a condition is expected, near 'and'. In SQL Server at CASE


SELECT 
    d.district_id, d.district_name, d1.district_id, d1.district_name
FROM 
    tbl_district d, tbl_district d1 
WHERE
     CASE
        WHEN (d.district_id % 2) != 0 
           THEN d.district_id 
     END
     AND d1.district_id = d.district_id+1;

Solution

  • I guess you are trying to filter the odd numbers

    SELECT 
        d.district_id, d.district_name, d1.district_id, d1.district_name
    FROM 
        tbl_district d 
    INNER JOIN tbl_district d1 
            ON d1.district_id = d.district_id+1
    WHERE (d.district_id % 2) != 0 
    

    Also start using INNER JOIN instead of old style comma separated join

    If you are using SQL SERVER 2012+ then you can use LEAD window function

    SELECT *
    FROM   (SELECT *,
                   Lead(district_id)OVER(ORDER BY district_id) AS next_dst,
                   Lead(district_name)OVER(ORDER BY district_id) AS next_name
            FROM   tbl_district ) a
    WHERE  a.district_id + 1 = a.next_dst
           AND ( district_id % 2 ) != 0