简体   繁体   中英

SQL Server union functionality?

I have a question regarding my attempt to combine two tables in sql server...

I have one table that has about 30 columns (table a), and a second table that has about 5 (table b), those 5 being present in the 30 column table. I want to be able to add table b to the end of table a, and just use 0 values for the nonexistent columns in the new rows.

Is there a way to do this? Obviously a regular union wouldnt work if I want to keep the other columns in table a.

The basic idea is this, assuming col3 does not exist in TableB :

select col1, col2, col3 from TableA

union all

select col1, col2, 0 as col3 from TableB

Be careful to keep the data types the same within each column.

To keep the TableB records at the end, do:

select col1, col2, col3
from (
    select 1 as Rank, col1, col2, col3 from TableA

    union all

    select 2 as Rank, col1, col2, 0 as col3 from TableB
) a
order by Rank

You can just insert the rows in:

insert into A(col1, col2, col3, col4, col5)
    select col1, col2, col3, col4, col5
    from B

This will apply the default values for the remaining columns. The defaults would typically be NULL, but could be changed in the create table statement. In order to get 0s, you would have to include the columns and specify values:

insert into A(col1, col2, col3, col4, col5, col6 . . . col30)
    select col1, col2, col3, col4, col5, 0 . . . 0
    from B

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