locked
UNION ALL USING ORDER BY CLAUSE RRS feed

  • Question

  • Hi Everyone,

    I have two table i have to first sort the data   and then do union all ,expected result given below ,not getting how to solve it.

    problem scenario given below

    declare @EMP table
    (
    Name varchar(50)
    )

    declare @EMP1 table
    (
    Name varchar(50)
    )

    INSERT INTO @EMP (Name)
    values('ZEN'),
    ('ALEX'),
    ('BOB')

    INSERT INTO @EMP1 (Name)
    values('RYAN'),
    ('BEN'),
    ('LINDA')

    Result Set given below 

    ALEX
    BOB
    ZEN
    BEN
    LINDA
    RYAN

    Thanks



    Monday, February 29, 2016 4:30 PM

Answers

  • declare @EMP table
    (
    Name varchar(50)
    )
    
    declare @EMP1 table
    (
    Name varchar(50)
    )
    
    INSERT INTO @EMP (Name)
    values('ZEN'),
    ('ALEX'),
    ('BOB')
    
    INSERT INTO @EMP1 (Name)
    values('RYAN'),
    ('BEN'),
    ('LINDA')
    
    ;With cte As
    (Select Name, 1 As TblSource
    From @EMP
    Union All
    Select Name, 2 As TblSource
    From @EMP1)
    Select Name
    From cte
    Order By TblSource, Name;
    

    Tom
    Monday, February 29, 2016 4:42 PM