Hi
I have below sql query . I want if count of current query = 0 then it should check the condition where V.Isactive = 0 else with V.isactive = 1
Current query
SQL
(SELECT TOP 1 V.[LastSessionTentativeDate] FROM [View_StudentSubscription] V WHERE V.IsActive = 1 AND V.StudentID = t.StudentId AND V.SubscriptionStatus = 'Active' AND V.DummySubscription = '' ORDER BY V.LastSessionTentativeDate DESC) [LastSessionTentativeDate],SQL
(SELECT TOP 1 V.[LastSessionTentativeDate] FROM [View_StudentSubscription] V WHERE V.IsActive = 0 AND V.StudentID = t.StudentId AND V.SubscriptionStatus = 'Active' AND V.DummySubscription = '' ORDER BY V.LastSessionTentativeDate DESC) [LastSessionTentativeDate],Thanks

Mudzakkir TohaRank #3,303 · 435 reputationPosted May 31, 2023, 10:40 PM EDT
do you want do if else in the sql?
if count sql 1 have rows, do sql1.
else do sql2?
Vishal JoshiRank #377 · 6.7K reputationPosted Jun 1, 2023, 1:29 AM EDT
Hello Ramco
You can get expected results using different ways like you can write a stored procedure or you can write conditions in a programming language like C#.
CREATE PROCEDURE [dbo].[PROC001] AS BEGIN SET NOCOUNT ON DECLARE @Count int SELECT @Count = count(*) FROM [View_StudentSubscription] V WHERE V.IsActive = 1 IF @Count = 0 BEGIN SELECT @Count = count(*) FROM [View_StudentSubscription] V WHERE V.IsActive = 0 END ELSE BEGIN SELECT @Count = count(*) FROM [View_StudentSubscription] V WHERE V.IsActive = 1 END ENDThank you
Vishal
Amit MohantyRank #112 · 20K reputationPosted Jun 1, 2023, 1:57 AM EDT
Check this:
SELECT TOP 1 V.[LastSessionTentativeDate] FROM [View_StudentSubscription] V WHERE (CASE WHEN (SELECT COUNT(*) FROM [View_StudentSubscription] WHERE V.IsActive = 1 AND V.StudentID = t.StudentId AND V.SubscriptionStatus = 'Active' AND V.DummySubscription = '') = 0 THEN V.IsActive = 0 ELSE V.IsActive = 1 END) AND V.StudentID = t.StudentId AND V.SubscriptionStatus = 'Active' AND V.DummySubscription = '' ORDER BY V.LastSessionTentativeDate DESCRajkiran SwainRank #165 · 14.4K reputationPosted Jun 1, 2023, 2:27 PM EDT
SELECT CASE WHEN ( SELECT COUNT(*) FROM [View_StudentSubscription] V WHERE V.IsActive = 1 AND V.StudentID = t.StudentId AND V.SubscriptionStatus = 'Active' AND V.DummySubscription = '' ) = 0 THEN (SELECT TOP 1 V.[LastSessionTentativeDate] FROM [View_StudentSubscription] V WHERE V.IsActive = 0 AND V.StudentID = t.StudentId AND V.SubscriptionStatus = 'Active' AND V.DummySubscription = '' ORDER BY V.LastSessionTentativeDate DESC) ELSE (SELECT TOP 1 V.[LastSessionTentativeDate] FROM [View_StudentSubscription] V WHERE V.IsActive = 1 AND V.StudentID = t.StudentId AND V.SubscriptionStatus = 'Active' AND V.DummySubscription = '' ORDER BY V.LastSessionTentativeDate DESC) END AS [LastSessionTentativeDate] FROM YourTable t