SQL Server 2012如果一个表为空,则将表作为返回值

时间:2017-04-14 17:52:58

标签: tsql sql-server-2012

我在两个表上使用With As语句,并从每个表中返回几列。每个查询本身都可以正常工作。当数据在两个满足Where子句的表中时,它可以正常工作。但是,当一个表没有任何符合where子句的表时,另一个表得到一个空的返回。看起来内部where子句不会影响另一个表,但我看不出我做错了什么。

;WITH Issue AS
(
    SELECT  
        I.[Title] as [Issue],
        dbo.udf_StripHTML([Discussion]) as Discussion
    FROM 
        [PSMADO].[dbo].[MSP_EpmProject_UserView] AS P
    JOIN
        [psmado].[dbo].[MSP_WssIssue_OlapView] AS I ON I.[projectUID] = P.[projectUID]
    WHERE
        I.[status] LIKE '%Active%'
        AND I.[Category] LIKE '%Factors%'
        AND p.[Workstream] LIKE 'PSO'
), Risk AS
(
    SELECT 
        I.[Title] as [Risk], 
        dbo.udf_StripHTML([MitigationPlan]) AS Mitigation
    FROM 
        [PSMADO].[dbo].[MSP_EpmProject_UserView] AS P
    JOIN
        [psmado].[dbo].[MSP_WssRisk_OlapView] AS I ON I.[projectUID] = P.[projectUID]
    WHERE
        I.[status] LIKE '%Active%'
        AND I.[Category] LIKE '%Factors%'
        AND p.[Workstream] LIKE 'PSO'
)
SELECT *
FROM Issue, Risk

1 个答案:

答案 0 :(得分:0)

我认为您需要的是LEFT JOIN,所有riskissue条件都会放在join clause中。

SELECT 
    P.projectUID, 
    risk.[Title] as [Risk], 
    dbo.udf_StripHTML(risk.[MitigationPlan]) AS Mitigation,
    I.[Title] as [Issue],
    dbo.udf_StripHTML(I.[Discussion]) as Discussion
FROM 
    [PSMADO].[dbo].[MSP_EpmProject_UserView]  P
LEFT JOIN [psmado].[dbo].[MSP_WssRisk_OlapView] risk 
    ON (risk.[projectUID] = P.[projectUID] AND risk.[status] LIKE '%Active%' 
         AND risk.[Category] LIKE '%Factors%')
LEFT JOIN
    [psmado].[dbo].[MSP_WssIssue_OlapView]  I 
    ON (I.[projectUID] = P.[projectUID]  AND I.[status] LIKE '%Active%' 
        AND I.[Category] LIKE '%Factors%')
WHERE
    p.[Workstream] LIKE 'PSO'

我注意到p.[Workstream] LIKE 'PSO'等于p.[Workstream] = 'PSO'

也许你需要p.[Workstream] LIKE '%PSO%'