仅在sql中的值不为null时选择查询

时间:2019-01-18 04:24:48

标签: sql sql-server stored-procedures

我有以下查询

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

我只想在这种情况下选择此查询,否则选择 东西。

如何以最少的代码行实现这一目标

2 个答案:

答案 0 :(得分:1)

您可以按以下方式使用ISNULL

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

答案 1 :(得分:0)

这可能对您有帮助

  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';