Theory question on CTE

Mikhail Firsov 1,876 Reputation points
2021-03-31T10:49:36.82+00:00

Hello!

Theory on Derived Tables: "~ ...when creating DTs you can define INLINE or EXTERNAL column aliases".

Practice on Derived Tables: I prefer EXTERNAL column aliases - and it works:
83207-q1.png

Theory on CTE: "~ define either INLINE or EXTERNAL column aliases".

Practice on CTE:
83188-q2.png

I failed to define the external column alias in CTE (I tried in various ways) and did not find any example on the matter either.
How can I "define external column aliases" in CTE?

Thank you in advance,
Michael

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,551 questions
0 comments No comments
{count} votes

Accepted answer
  1. Dan Guzman 9,206 Reputation points
    2021-03-31T11:30:22.343+00:00

    With a CTE, specify the external column aliases after the CTE name declaration per the syntax documentation:

    WITH CTE_EmDep (Employee, DepartmentName)  
    AS  
    (  
     SELECT BusinessEntityID, Name  
     FROM HumanResources.EmployeeDepartmentHistory  
     INNER JOIN HumanResources.Department ON HumanResources.EmployeeDepartmentHistory.DepartmentID = HumanResources.Department.DepartmentID  
    )  
    SELECT Employee, DepartmentName  
    FROM CTE_EmDep;  
    

    Instead of images, please post code as text formatted with the Code Sample button going forward. Than will help us better help you.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Mikhail Firsov 1,876 Reputation points
    2021-03-31T11:53:31.18+00:00

    Oh, I did not think the "column_name - Specifies a column name in the common table expression." means "external column aliases" ( I thought they must be defined after AS like in the DT).

    Thank you very much!

    Regards,
    Michael

    0 comments No comments