SQL Server 如何将所有两个表UNION成一个临时表?

2w2cym1i  于 2022-12-03  发布在  其他
关注(0)|答案(1)|浏览(495)

我一直在尝试将两个表合并到一个临时表中。
我试了几种方法:1.

SELECT * INTO #temp FROM Customers.Emails
UNION ALL
SELECT * INTO #temp FROM Customers.Location
SELECT *
INTO #temp
(Select
    All column names here etc
FROM Customer.Emails
UNION
SELECT
    All column names here etc
FROM Customer.Location)

当我尝试2时,出现此错误
Msg 263,级别16,状态1,第1行必须指定要从中进行选择的表。Msg 1038,级别15,状态5,第1行缺少对象名或列名,或者该名称为空。对于SELECT INTO语句,请验证每一列都有名称。对于其他语句,请查找空的别名。不允许使用定义为“”或[]的别名。请将别名更改为有效的名称。

eh57zj3b

eh57zj3b1#

这里有3种方法来执行INSERT INTO #temp。方法1要求两个表具有完全相同的列名和计数。另外2种方法要求您定义要插入的列,因为我们不再使用SELECT *

CREATE TABLE emails (
  email_address nvarchar(50)
);
  
CREATE TABLE locations (
  email_address nvarchar(50)
);
 
INSERT INTO emails VALUES ('test@test.com');
INSERT INTO locations VALUES ('test2@test2.com');

--Method 1
SELECT * INTO #temp FROM emails
UNION ALL
SELECT * FROM locations

SELECT *
FROM #temp;

--Method 2
SELECT *
INTO #temp2
FROM (
  SELECT
    email_address
  FROM emails
  UNION ALL
  SELECT
    email_address
  FROM locations
) as tbl

SELECT *
FROM #temp2;

--Method 3
WITH prelim AS (
  SELECT
      email_address
    FROM emails
    UNION ALL
    SELECT
        email_address
    FROM locations
)
SELECT *
INTO #temp3
FROM prelim;

SELECT *
FROM #temp3;

方法1结果:
| 电子邮件地址|
| - -|
| test@test.com |
| test2@test2.com |
方法2结果:
| 电子邮件地址|
| - -|
| test@test.com |
| test2@test2.com |
方法3结果:
| 电子邮件地址|
| - -|
| test@test.com |
| test2@test2.com |
fiddle

相关问题