Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHERE CASE WHEN statement with Exists

I am creating a SQL query having WHERE CASE WHEN statement. I am doing something wrong and getting error.

My SQL statement is like

DECLARE @AreaId INT = 2
DECLARE @Areas Table(AreaId int)

INSERT INTO @Areas SELECT AreaId
FROM AreaMaster
WHERE CityZoneId IN (SELECT CityZoneId FROM AreaMaster WHERE AreaId = @AreaID)

SELECT * 
FROM dbo.CompanyMaster
WHERE AreaId IN
     (CASE WHEN EXISTS (SELECT BusinessId
                        FROM dbo.AreaSubscription
                        WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId) 
             THEN @AreaId 
             ELSE (SELECT [@Areas].AreaId FROM @Areas)
      END)

I am getting error as

Msg 512, Level 16, State 1, Line 11
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Please help to successfully run query. My logic is to checking for conditional AreaId in (statement) for each row.

I want to select the row only when

  1. company has subscription entry into AreaSubscription for specific area passed by @AreaId
  2. table AreaSubscription does not have subscription entry then evaluate AreaId in (SELECT [@Areas].AreaId FROM @Areas)
like image 284
Haresh Ambaliya Avatar asked Aug 07 '13 09:08

Haresh Ambaliya


People also ask

Can you use exists in a case statement?

Using EXISTS clause in the CASE statement to check the existence of a record. Using EXISTS clause in the WHERE clause to check the existence of a record. EXISTS clause having subquery joining multiple tables to check the record existence in multiple tables.

Can we use exists in case statement in SQL Server?

Yes, just do: SELECT CASE WHEN EXISTS(subquery) THEN... There are some situations you can't use it (e.g. in a group by clause IIRC), but SQL should tell you quite clearly in that situation.

Can case when be used in WHERE clause?

CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.


1 Answers

This may help you.

SELECT * FROM dbo.CompanyMaster
WHERE AreaId=
(CASE WHEN EXISTS (SELECT BusinessId
                   FROM dbo.AreaSubscription
                   WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId) 
      THEN @AreaId ELSE AreaId END)
AND  AreaId IN (SELECT [@Areas].AreaId FROM @Areas)

One more solution is

SELECT * FROM dbo.CompanyMaster A 
LEFT JOIN @Areas B ON A.AreaId=B.AreaID
WHERE A.AreaId=
(CASE WHEN EXISTS (SELECT BusinessId
                   FROM dbo.AreaSubscription
                   WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId) 
      THEN @AreaId ELSE B.AreaId END)
)
like image 56
Nithesh Narayanan Avatar answered Nov 07 '22 18:11

Nithesh Narayanan