0

我有一个问题想出解决这个问题的方法。即,即使使用 WHERE 子句找不到该行,我也希望第二个 SELECT 语句返回空值。

我尝试了许多不同的解决方案,但没有任何效果(使用 IF、CTE 等)。你能帮忙吗?

    SELECT  RA.id
        ,AllEngagementsAndJobCodes =
        (
            SELECT 
            (
                SELECT
                (...)

                For JSON Path
            ) AS  engagements
            ,
            (
                SELECT [someColumn] as [id], [someColumn2] as [name]
                FROM [someInterface].[someSchema].[someTable]
                WHERE [someID] = '12345'

                For JSON Path, INCLUDE_NULL_VALUES
            ) as jobCodes
        For JSON Path, WITHOUT_ARRAY_WRAPPER
        )

其输出应该是一列(对于这个问题来说很简单)和包含 JSON 路径的第二列,看起来应该是这样的:

    {
        "engagements": [
            {
                //results of the first query, not siginificant for the question
            }
        ],
        "jobCodes": [
            {
                "id": null,
                "name": null
            }
        ]
    }

请注意,如果查询确实返回了某些内容,则它可能不止一行,并且所有这些都需要包含在输出 JSON 中。

4

2 回答 2

1

一种方法是使用公用表表达式和union all

;WITH CTEInnerQuery AS
(
    SELECT [someColumn] as [id], [someColumn2] as [name]
    FROM [someInterface].[someSchema].[someTable]
    WHERE [someID] = '12345'
), CTEInnerJson AS
(
    SELECT *
    FROM CTEInnerQuery
    UNION ALL
    SELECT NULL as [id], NULL as [name]
    WHERE NOT EXISTS(SELECT 1 FROM CTEInnerQuery)
)

SELECT  RA.id
    ,AllEngagementsAndJobCodes =
    (
        SELECT 
        (
            SELECT
            (...)

            For JSON Path
        ) AS  engagements
        ,
        (
            SELECT *
            FROM CTEInnerJson
            For JSON Path, INCLUDE_NULL_VALUES
        ) as jobCodes
    For JSON Path, WITHOUT_ARRAY_WRAPPER
    )
于 2020-02-05T09:45:22.293 回答
0

您可以使用此技巧解决您的问题

IF(NOT EXISTS (...))
BEGIN
    SELECT  0 AS UserID
            ,N'' UserName
    WHERE 1 = 2

    RETURN;
END
于 2020-02-05T09:45:21.763 回答