简体   繁体   English

在CTE SQL查询中使用Union子句时出错

[英]Error on using union clause in cte sql query

I'm trying to do following but getting an max recursive error. 我正在尝试执行以下操作,但遇到了最大递归错误。 Can someone please help? 有人可以帮忙吗?

Sample code to demonstrate what I'm trying to achieve: 示例代码演示了我要实现的目标:

DECLARE @SecurityMaster AS TABLE
(
    ID              INT,
    SecurityAlias   INT,
    LegNumber       INT
)

INSERT INTO @SecurityMaster
SELECT 12829, 3030106, NULL 
UNION ALL
SELECT 12829, 3030107, 1

SELECT * FROM @SecurityMaster;

WITH CTE1 (ID, SecurityAlias, LegNumber)
AS
(
    SELECT S.ID, S.SecurityAlias, S.LegNumber
    FROM @SecurityMaster S 
    WHERE S.LegNumber IS NOT NULL

    UNION ALL

    select s.ID, s.SecurityAlias, s.LegNumber
    from @SecurityMaster S inner join CTE1 c on s.ID = c.ID
    where s.LegNumber is NULL
)

SELECT *
FROM CTE1;

Result I'm expecting: 我期望的结果:

ID          SecurityAlias       LegNumber
-----------------------------------------
12829       3030107             1
12829       3030106             NULL

Your questionis difficult to understand, but will this work for you? 您的问题很难理解,但这对您有用吗?

select s.ID, s.SecurityAlias, s.LegNumber
from @SecurityMaster S
where s.LegNumber is NULL
And s.id in (SELECT f.ID
FROM @SecurityMaster f
WHERE f.LegNumber IS NOT NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM