SQL IF else select子句

时间:2013-06-13 15:57:01

标签: sql-server

我需要能够在select语句的having子句中执行IF ELSE。以下是我要做的事情的摘录:

HAVING  
IF      @Vendor IS NOT NULL 
THEN    (COUNT(Iron_1.SN) > 0) AND [User].UserIdentifier = @Vendor AND Location_1.LocationName = @LocationName
ELSE

(COUNT(Iron_1.SN) > 0) AND Location_1.LocationName = @LocationName

我希望根据用户是否为查询参数提供值来确定某些过滤器。

1 个答案:

答案 0 :(得分:3)

试试这个

HAVING COUNT(Iron_1.SN) > 0 AND Location_1.LocationName = @LocationName AND
        (@Vendor IS NULL OR (@Vendor IS NOT NULL AND [User].UserIdentifier = @Vendor))

或稍微简化的版本

HAVING COUNT(Iron_1.SN) > 0 AND Location_1.LocationName = @LocationName AND
        (@Vendor IS NULL OR [User].UserIdentifier = @Vendor)

尝试这两个并选择你最喜欢的那个并且工作