簡體   English   中英

sql server合並兩個具有不同結構的表

[英]sql server merge two tables with different structures

我遇到的情況是必須合並兩個表而不會丟失任何數據。 這兩個表具有不同的結構。 以下是我的桌子的結構

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)

我嘗試通過在表B中包含偽列來使用UNION ALL,如下所示

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

但在結果集中,我得到1900-01-01作為Ship_Date而不是“”。 如何消除呢?

使用NULL值而不是空字符串。 如果您不介意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_Datedate數據類型,為什么不使用NULL作為虛擬占位符呢?

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

您得到1900-01-01因為該列類型為DATETIME。 使用NULL而不是''如果你希望它是“空”。

嘗試:

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