Sql server union but keep order

前端 未结 4 700
悲&欢浪女
悲&欢浪女 2020-12-05 09:58

Is there a way to union two tables, but keep the rows from the first table appearing first in the result set?

For example:

Table1

name                


        
4条回答
  •  臣服心动
    2020-12-05 10:36

    .Like this?

    CREATE TABLE #Table1 (Names VARCHAR(50))
    CREATE TABLE #Table2 (Names VARCHAR(50))
    
    INSERT INTO #Table1
    (
        Names
    )
    VALUES
        ('John Doe'), ('Bob Marley'), ('Ras Tafari') 
    
    INSERT INTO #Table2
    (
        Names
    )
    VALUES
        ('Lucky Dube'), ('Abby Arnold') 
    
    
    SELECT ArbSeq   = 1, *
    FROM #Table1
    UNION ALL
    SELECT ArbSeq   = 2, *
    FROM #Table2
    ORDER BY ArbSeq
    

    It should be noted that ordering is not guaranteed when not explicitly defined. If the table features a clustered index, the rows will typically be returned in the index's order - but this is not guaranteed.

提交回复
热议问题