NAGARAJA H I
NAGARAJA H I

Reputation: 149

Select query only when a value is not null in sql

I have the following query

SELECT 
    @EnrollmentTime = T1.EnrollmentTime 
FROM 
    T1 
INNER JOIN 
    T2 ON T1.DeviceMacAddress = T2.DeviceMacAddress 
WHERE 
    T1.ID = @LocationID

I want to select this query only when this scenario exists else select something.

How to achieve this with minimal lines of code

Upvotes: 0

Views: 153

Answers (2)

Shushil Bohara
Shushil Bohara

Reputation: 5656

Simply you can use ISNULL as below

SELECT @EnrollmentTime=ISNULL(@EnrollmentTime, T1.EnrollmentTime) 
FROM T1 
INNER JOIN T2  ON T1.DeviceMacAddress=T2.DeviceMacAddress 
WHERE T1.ID=@LocationID

Upvotes: 1

Akash Vishwakarma
Akash Vishwakarma

Reputation: 177

This may help you

  IF (@EnrollmentTime IS NOT NULL) OR (LEN(@EnrollmentTime) > 0)
            SELECT @EnrollmentTime=T1.EnrollmentTime 
            FROM T1 INNER JOIN T2  ON T1.DeviceMacAddress=T2.DeviceMacAddress WHERE 
            T1.ID=@LocationID
    ELSE
            PRINT 'else';

Upvotes: 0

Related Questions