简体   繁体   中英

How do I append a row with specific values to the output of my T-SQL query?

I am using SQL Server 2014 and I have the following T-SQL query which runs fine:

SELECT Id, Name from TravelAgency

The last row of the output of this query is shown below:

Id       Name
---      ----
---      ----
715      AB Ltd

I want to "manually" append the following values to the result set of this query: (999, XY Ltd) so that running the modifed query will give me the following results:

Id       Name
---      ----
---      ----
715      AB Ltd
999      XY Ltd

To simplify, the query pulls the data requested from the TravelAgency table and ADDS the specified values at the end of the output. I need to add those specific values in my query but I just can't figure out how to do it!

Use a union all:

select id, name from xxx -- is your query
union all
select 999 as id, 'XY Ltd' as name 

EDIT: In addition to @ThorstenKettner 's comment: If ID is not nummeric or for any reason you can not use it for the sort, then you could do it like this:

select ID, Name
from 
(
    select 1 as SpecialSort, ID, Name from xxx -- is your query
    union all
    select 2 as SpecialSort, 999 as ID, 'XY Ltd' as Name
) AllData
order by SpecialSort asc -- like this your manually added row will appear at the end

Use UNION to append your required entry along with return result set. It can avoid if the 999 XY Ltd entry is already exists.

SELECT Id, Name FROM TravelAgency
UNION 
SELECT 999 AS [Id], 'XY Ltd' AS [Name]

If the 999 XY Ltd is already return form result set and allow the duplicate entries you can use UNION ALL and ensure the 999 XY Ltd as last record by ORDER BY

SELECT Id, Name FROM (
    SELECT Id, Name FROM TravelAgency
    UNION ALL
    SELECT 999 AS [Id], 'XY Ltd' AS [Name]
) AS T 
ORDER BY Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM