简体   繁体   English

sql server合并两个具有不同结构的表

[英]sql server merge two tables with different structures

I have a situation where in I have to combine two tables without losing any data. 我遇到的情况是必须合并两个表而不会丢失任何数据。 The two tables have different structures. 这两个表具有不同的结构。 Following is the structures of my tables 以下是我的桌子的结构

TABLE A 
ID_NO INT,
Ship_Date DATE,
Status varchar(10),
total decimal(12,2)

TABLE B
ID_NO INT,
Status varchar(10),
total decimal(12,2)

I tried using UNION ALL by including a dummy column in TABLE B as follows 我尝试通过在表B中包含伪列来使用UNION ALL,如下所示

TABLE B
ID_NO INT,
'',
Status varchar(10),
total decimal(12,2)

but in the result set i get 1900-01-01 as Ship_Date instead of ''. 但在结果集中,我得到1900-01-01作为Ship_Date而不是“”。 How to eliminate this? 如何消除呢?

Use a NULL value instead of an empty string. 使用NULL值而不是空字符串。 If you don't mind the Ship_Date result as a string, then you can wrap the UNION in another select statement. 如果您不介意Ship_Date结果作为字符串,则可以将UNION包装在另一个select语句中。

SELECT U._ID_NO, 
       CASE WHEN U.Ship_Date IS NULL 
               THEN ''
               ELSE CONVERT(NVARCHAR(50), U.Ship_Date,101) END AS Ship_Date,
       U.Status, 
       U.total 
FROM
(
  SELECT A.ID_NO, A.Ship_Date, A.Status, A.total 
  FROM TableA

  UNION ALL

  SELECT B.ID_NO, NULL AS Ship_Date, B.Status, B.total 
  FROM TableB
) AS U

Ship_Date is a date datatype, why not use NULL as a dummy placeholder instead? Ship_Datedate数据类型,为什么不使用NULL作为虚拟占位符呢?

TABLE B
ID_NO INT,
NULL,
Status varchar(10),
total decimal(12,2)

You're getting 1900-01-01 because that column type is DATETIME. 您得到1900-01-01因为该列类型为DATETIME。 Use NULL instead of '' if you want it to be "empty". 使用NULL而不是''如果你希望它是“空”。

Try: 尝试:

select 
    ID_NO,
    case
        when Ship_Date is NULL then ''
       else Ship_Date
    end as Ship_Date,
    Status,
    total
from
(
    select
        ID_NO,
        Ship_Date,
        Status,
        total
    from
        table_a

    union all

    select
        ID_NO,
        NULL as Ship_Date,
        Status,
        total
    from
        table_b 
) combined

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

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