简体   繁体   English

SQL Server联合功能?

[英]SQL Server union functionality?

I have a question regarding my attempt to combine two tables in sql server... 我有一个关于我尝试在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. 我有一个表有大约30列(表a),第二个表有大约5(表b),这5个表存在于30列表中。 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. 我希望能够将表b添加到表a的末尾,并且只对新行中不存在的列使用0值。

Is there a way to do this? 有没有办法做到这一点? Obviously a regular union wouldnt work if I want to keep the other columns in table a. 显然,如果我想保留表a中的其他列,常规联合将无法工作。

The basic idea is this, assuming col3 does not exist in TableB : 其基本思路是这样的,假设col3中不存在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: 要将TableB记录保留在最后,请执行以下操作:

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. 默认值通常为NULL,但可以在create table语句中更改。 In order to get 0s, you would have to include the columns and specify values: 要获得0,您必须包含列并指定值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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