Click here to Skip to main content
15,887,249 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a query, and it has subquery written with (IN statement) like this:

SQL
Select * From Student
Where IsActive=1 
AND stu_Id IN (Select stu_Id From Temp)


What I need is:
if (IN) gets nothing, then ignore or react like this line doesn't exist:
SQL
(AND stu_Id IN (Select stu_Id From Temp)


What I have tried:

I Googled for my problem and found nothing!
Posted
Updated 24-Oct-23 1:21am
v3

Try using a JOIN instead: SQL Joins[^]
 
Share this answer
 
To ignore the subquery if the IN clause doesn't retrieve any results, you can use an EXISTS clause. Here's an updated version of the query:
SQL
SELECT * 
FROM Student
WHERE IsActive = 1 
AND EXISTS (SELECT 1 FROM Temp WHERE Temp.stu_Id = Student.stu_Id);

if the subquery inside the EXISTS clause returns no results, the condition will be evaluated as false, and the row won't be included in the final result set.
Left join can also serve this purpose, If you want to ignore the subquery when the IN clause doesn't return any results, you can modify the query using a left join:
SQL
SELECT s.* 
FROM Student s
LEFT JOIN Temp t
ON s.stu_Id = t.stu_Id
WHERE s.IsActive = 1 
AND (t.stu_Id IS NOT NULL OR t.stu_Id IS NULL)
 
Share this answer
 
Comments
Ghost Ghost 22-Oct-23 12:31pm    
Note:
Sometimes I send many values to (IN clause) not just one, and Sometimes I send No values to it.

I want what?
if I send no values to (IN clause) so ignore it.

How can I do that?
M Imran Ansari 22-Oct-23 12:52pm    
If that is the case you can achieve through a dynamic query that handles the IN clause when values are provided and ignores it when no values are provided, you can use a combination of conditional logic and dynamic SQL.
M Imran Ansari 22-Oct-23 13:01pm    
DECLARE @Values NVARCHAR(MAX) = ''; -- Pass your values here

-- Checking if values are provided
IF @Values <> ''
BEGIN
DECLARE @Query NVARCHAR(MAX) = 'SELECT * FROM Student WHERE IsActive = 1 AND stu_Id IN (' + @Values + ')';
EXEC sp_executesql @Query;
END
ELSE
BEGIN
SELECT * FROM Student WHERE IsActive = 1;
END

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900