SQL Server WHERE为空或多行(值)

时间:2018-01-25 12:11:39

标签: sql sql-server tsql

int arr[]={12,13,14,44};  
for(int i:arr){
    System.out.println(i);  
}

- 子查询时

--Main Query
SELECT * FROM tblUser u
WHERE
--Search Criteria 1
-- Sub Query 
((SELECT se.SearchEntityId FROM tblSearchEntity se WHERE se.SearchEntityTitle 
like 'MaritalStatus')
IS NULL
OR 
u.MaritalStatus IN 
-- Sub Query 
(SELECT se.SearchEntityId FROM tblSearchEntity se WHERE se.SearchEntityTitle 
like 'MaritalStatus'))

AND
--Search Criteria 2
-- Sub Query 
((SELECT se.SearchEntityId FROM tblSearchEntity se WHERE se.SearchEntityTitle 
like 'CountryOfResidence')
IS NULL
OR 
u.CountryOfResidence IN 
-- Sub Query 
(SELECT se.SearchEntityId FROM tblSearchEntity se WHERE se.SearchEntityTitle 
like 'CountryOfResidence'))

返回:

NULL [主查询]工作正常

1行[主查询]正常

2个或更多ROWS [主查询]不起作用。

IS NULL不能赋予多个值,所以我该怎么办?

3 个答案:

答案 0 :(得分:0)

在此

上更新您的条件
 WHERE EXISTS (SELECT se.SearchEntityId FROM tblSearchEntity se 
    WHERE se.SearchEntityTitle like 'MaritalStatus'
    AND se.SearchEntityId = sp.SearchEntityId)
    AND s.UserId = @UserId))

答案 1 :(得分:0)

 WHERE EXISTS (SELECT se.SearchEntityId FROM tblSearchEntity se 
    WHERE se.SearchEntityTitle like 'MaritalStatus'
    AND se.SearchEntityId = sp.SearchEntityId)
    AND s.UserId = @UserId))

不使用上述内容,最好使用JOINS。例如,以上将具有以下连接

LEFT OUTER JOIN [tblSearchEntity] se on se.searchentityId = sp.searchentityId

答案 2 :(得分:0)

假设我理解你尝试做什么,我认为在几个CTE的帮助下,主要查询中的一些变化,你将得到你想要的。

这是我想出的。请记住,由于您未提供样本数据或所需结果,因此我无法对其进行测试。

;WITH MaritalStatusCte AS
(
    SELECT SearchEntityId 
    FROM tblSearchEntity 
    WHERE SearchEntityTitle = 'MaritalStatus'  
), CountryOfResidenceCte AS
(
    SELECT SearchEntityId 
    FROM tblSearchEntity 
    WHERE se.SearchEntityTitle = 'CountryOfResidence'  
)


SELECT * 
FROM tblUser as u
WHERE 
(
    (SELECT COUNT(*) FROM MaritalStatusCte) = 0)
    OR EXISTS
    (
        SELECT 1
        FROM MaritalStatusCte 
        WHERE SearchEntityId = uMaritalStatus
    )
)
AND 
(
    (SELECT COUNT(*) FROM CountryOfResidenceCte) = 0)
    OR EXISTS
    (
        SELECT 1
        FROM CountryOfResidenceCte 
        WHERE SearchEntityId = CountryOfResidence
    )
)