选择使用联合查询

发布于 2024-09-28 20:10:49 字数 342 浏览 4 评论 0原文

我想使用以下查询在 SQL Server 中创建一个新表。我无法理解为什么这个查询不起作用。

查询 1:有效

SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2 

查询 2:无效。 错误:消息 170,级别 15,状态 1,第 7 行 第 7 行:“)”附近的语法不正确。

SELECT * INTO [NEW_TABLE]
FROM
(
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2
)

谢谢!

I want to create a new table in SQL Server with the following query. I am unable to understand why this query doesn't work.

Query1: Works

SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2 

Query2: Does not Work.
Error: Msg 170, Level 15, State 1, Line 7
Line 7: Incorrect syntax near ')'.

SELECT * INTO [NEW_TABLE]
FROM
(
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2
)

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

捎一片雪花 2024-10-05 20:10:49

您必须为 SQL Server 中的派生表定义表别名:

SELECT x.* 
  INTO [NEW_TABLE]
  FROM (SELECT * FROM TABLE1
        UNION
        SELECT * FROM TABLE2) x

“x”是本示例中的表别名。

You have to define a table alias for a derived table in SQL Server:

SELECT x.* 
  INTO [NEW_TABLE]
  FROM (SELECT * FROM TABLE1
        UNION
        SELECT * FROM TABLE2) x

"x" is the table alias in this example.

伴梦长久 2024-10-05 20:10:49
select *
into new_table
from table_A
UNION
Select * 
From table_B

仅当 Table_A 和 Table_B 具有相同架构时才有效

select *
into new_table
from table_A
UNION
Select * 
From table_B

This only works if Table_A and Table_B have the same schemas

做个ˇ局外人 2024-10-05 20:10:49

您还可以尝试:

create table new_table as
select * from table1
union
select * from table2

You can also try:

create table new_table as
select * from table1
union
select * from table2
在巴黎塔顶看东京樱花 2024-10-05 20:10:49
INSERT INTO #Temp1
SELECT val1, val2 
FROM TABLE1
 UNION
SELECT val1, val2
FROM TABLE2
INSERT INTO #Temp1
SELECT val1, val2 
FROM TABLE1
 UNION
SELECT val1, val2
FROM TABLE2
一刻暧昧 2024-10-05 20:10:49

以下是 SQL Server 2017 的一种工作语法:

USE [<yourdb-name>]
GO

SELECT * INTO NEWTABLE 
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>

Here's one working syntax for SQL Server 2017:

USE [<yourdb-name>]
GO

SELECT * INTO NEWTABLE 
FROM <table1-name>
UNION ALL
SELECT * FROM <table2-name>
终陌 2024-10-05 20:10:49

在 MS Access 中,您可以:

SELECT x.* INTO NEWTABLE
FROM (
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2) AS x

与 OMG Ponies 的答案相同,只是使用了关键字“AS”。

In MS Access you can:

SELECT x.* INTO NEWTABLE
FROM (
SELECT * FROM TABLE1
UNION
SELECT * FROM TABLE2) AS x

It's the same a OMG Ponies's answer except the keyword "AS" is used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文