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
AreaSubscription
for specific area passed by @AreaId
AreaSubscription
does not have subscription entry then evaluate AreaId
in (SELECT [@Areas].AreaId FROM @Areas)
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.
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.
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.
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With