SQL Server中WHERE子句中的大小写/存在

时间:2019-01-17 13:36:24

标签: sql sql-server case

我有一个查询,需要在WHERE子句中添加条件。条件是,如果companyID在特定列表内,则仅显示具有LocationTypeID的用户,否则显示所有用户。反正有实现这一目标的方法吗?

SELECT 
    UserID
FROM [Account].[User] AS [User]
INNER JOIN [Account].[Location] as [Location]
    ON [Location].[LocationID] = [User].[LocationID]

我正在尝试在where子句中添加条件,但不确定如何做。

WHERE
CASE WHEN Location.CompanyID IN (123, 344, 444, 565)
THEN 'AND Location.LocationTypeID IS NOT NULL'

3 个答案:

答案 0 :(得分:2)

使用下面的条件

SELECT 
    UserID
FROM [Account].[User] AS [User]
INNER JOIN [Account].[Location] as [Location]
    ON [Location].[LocationID] = [User].[LocationID] 
    where        
    (
     Location.CompanyID IN (123, 344, 444, 565)
     AND Location.LocationTypeID IS NOT NULL
    ) 
     OR 
     (
      Location.CompanyID not IN (123, 344, 444, 565)          
     )

答案 1 :(得分:2)

当简单的逻辑组合将起作用时,人们似乎总是想使用setTimeout

CASE

请注意,我已经颠倒了第一个条件,因此只要第一个条件为假,我们只需要第二个条件为真即可。当然,它们可能都是正确的,但这无关紧要。

答案 2 :(得分:0)

尝试以下查询-:

SELECT 
    UserID
FROM [Account].[User] AS [User]
INNER JOIN [Account].[Location] as [Location]
    ON [Location].[LocationID] = [User].[LocationID]
WHERE
Location.CompanyID IN (123, 344, 444, 565)
AND Location.LocationTypeID IS NOT NULL

SQL Server 2014