0

I have a hierarchical query with Common Table Expressions:

WITH Revision(REV, MonitoringGroupId, BusinessLineId, REVTYPE, REVEND) AS
(
    SELECT REV, MonitoringGroupId, BusinessLineId, REVTYPE, REVEND
    FROM MonitoringGroupBusinessLine_AUD
    WHERE REV = 1045
    UNION ALL
    SELECT rev.REV, rev.MonitoringGroupId, rev.BusinessLineId, rev.REVTYPE, rev.REVEND
    FROM MonitoringGroupBusinessLine_AUD rev
    INNER JOIN Revision ON rev.REVEND = Revision.REV
)
SELECT 
    DISTINCT
    MonitoringGroupId, 
    BusinessLineId, 
    IIF(REVTYPE = 2, 'REMOVE', 'ADD') as Operation
FROM Revision

And I want to use it in as a sub-query, something like that:

SELECT audit.MonitoringGroupId, audit.BusinessLineId, audit.Operation
FROM
(
    WITH Revision(REV, MonitoringGroupId, BusinessLineId, REVTYPE, REVEND) AS
    (
        SELECT REV, MonitoringGroupId, BusinessLineId, REVTYPE, REVEND
        FROM MonitoringGroupBusinessLine_AUD
        WHERE REV = 1045
        UNION ALL
        SELECT rev.REV, rev.MonitoringGroupId, rev.BusinessLineId, rev.REVTYPE, rev.REVEND
        FROM MonitoringGroupBusinessLine_AUD rev
        INNER JOIN Revision ON rev.REVEND = Revision.REV
    )
    SELECT 
        DISTINCT
        MonitoringGroupId, 
        BusinessLineId, 
        IIF(REVTYPE = 2, 'REMOVE', 'ADD') as Operation
    FROM Revision
) audit

I have an error:

Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

I tried to add ; before WITH, but it still does not work. How to use my hierarchical query as a subquery ?

2
  • Well, as you have learned, SQL Server doesn't support that syntax. Commented Aug 28, 2018 at 17:07
  • 1
    Why do you want to do that? You can already query the CTE as you would a table, what does using it as a subquery accomplish? Commented Aug 28, 2018 at 17:10

1 Answer 1

1

You make the subquery in the output.

;WITH Revision(REV, MonitoringGroupId, BusinessLineId, REVTYPE, REVEND) AS
(
    SELECT REV, MonitoringGroupId, BusinessLineId, REVTYPE, REVEND
    FROM MonitoringGroupBusinessLine_AUD
    WHERE REV = 1045
    UNION ALL
    SELECT rev.REV, rev.MonitoringGroupId, rev.BusinessLineId, rev.REVTYPE, rev.REVEND
    FROM MonitoringGroupBusinessLine_AUD rev
    INNER JOIN Revision ON rev.REVEND = Revision.REV
)
SELECT audit.MonitoringGroupId, audit.BusinessLineId, audit.Operation
FROM
(
    SELECT 
        DISTINCT
        MonitoringGroupId, 
        BusinessLineId, 
        IIF(REVTYPE = 2, 'REMOVE', 'ADD') as Operation
    FROM Revision
) audit
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.