从简单的联合语句中创建表

发布于 2025-01-26 17:19:30 字数 220 浏览 3 评论 0原文

这个联盟怎么了?首先“选择”和“)”是不正确的

create table GL_ALL
(
   select *from GL1
)
UNION
(
   select *from GL2
)
UNION
(
   select *from GL3
)
UNION
(
   select *from GL4
)
UNION
(
   select *from GL5
);

What is wrong with this union? first 'select' and ')' are incorrect

create table GL_ALL
(
   select *from GL1
)
UNION
(
   select *from GL2
)
UNION
(
   select *from GL3
)
UNION
(
   select *from GL4
)
UNION
(
   select *from GL5
);

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

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

发布评论

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

评论(1

爱的故事 2025-02-02 17:19:30

这不是在SQL Server中飞出的表格,也不是Union为此而言。

假设您的每个表的模式

SELECT *
INTO GL_ALL FROM GL1 UNION
SELECT * FROM GL2 UNION
SELECT * FROM GL3 UNION
SELECT * FROM GL4 UNION
SELECT * FROM GL5;

与评论中指出的相同,这将适用于初始创建gl_all,但对于表之后的后续插入件,表创建。

如果您需要在以后的时间附加到表上,那么Sytax会更改为:

INSERT INTO GL_ALL
SELECT * FROM GL6;

重要的是要意识到新表将没有主键,任何外国键,索引(聚类或非),约束,默认值等。源表可能具有。如果需要这些,则需要手动创建它们。

并请注意Union联合所有之间的区别,其中Union将排除重复的行。

另请注意,避免选择 *并专门调用要使用的列 - 即使它实际上是所有列,也是最好的做法。

That's not the correct syntax for creating a table on the fly in SQL Server, or UNION for that matter.

Assuming that the schemas of each of your tables are the same

SELECT *
INTO GL_ALL FROM GL1 UNION
SELECT * FROM GL2 UNION
SELECT * FROM GL3 UNION
SELECT * FROM GL4 UNION
SELECT * FROM GL5;

As pointed out in comments, this will work for the initial creation of GL_ALL, but not for subsequent inserts after the table is created.

If you need to append to the table at a later time then the sytax changes to:

INSERT INTO GL_ALL
SELECT * FROM GL6;

It's important to realize that the new table will NOT have a primary key nor any foreign keys, indexes (clustered or non), constraints, defaults, etc. that the source tables may have. If these are needed then you will need to manually create them.

And do note the difference between UNION and UNION ALL, where UNION will exclude duplicate rows.

Also note, it's best practice to avoid SELECT * and to specifically call out the columns you want to work with - even if it actually is all columns.

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