user2864154 user2864154 - 2 months ago 12
SQL Question

Define a sub query outside of the main query for easiler readability

Is the a way to define a sub query outside of the main query so the sql code becomes easier to read? For example:

Instead of this:

Select *
From
Select *
From
Select *
From TableName


I want:

Select *
From A

Define A = Select * From B
Define B = Select * From TableName


I'm using SQL Server 2008 if that's relevant.

Answer

Please try something like this. with Common Table Expressions.

;

WITH B
AS (
    SELECT *
    FROM TableName
    )
    ,A
AS (
    SELECT *
    FROM B
    )
SELECT *
FROM A;
Comments