无法用 SQL UNION 查询替换表名

发布于 2024-12-02 00:29:44 字数 439 浏览 4 评论 0原文

我在 SQL Server 2008 R2 中有两个具有相同架构的表。如果我执行以下查询(括号完好无损),我会从两个表中获得结果。

/*
select distinct Name, Rank, SerNo, OtherStuff from 
*/

(
select Name, Rank, SerNo, OtherStuff from OldPlayers

union 
select Name, Rank, SerNo, OtherStuff from NewPlayers
)

/*
OldPlayers
*/

go

如果我取消注释这两个注释,并注释掉括号中的表达式,我也会得到结果(当然,来自一张表)。

如果我现在在末尾重新注释表名,并取消注释括号表达式以便它可以替换表名,我会收到错误“')'附近的语法不正确”。

为什么我不能用联合表达式替换表名?

I have two tables with identical schema in SQL Server 2008 R2. If I execute the following query, with parentheses intact, I get results from both tables.

/*
select distinct Name, Rank, SerNo, OtherStuff from 
*/

(
select Name, Rank, SerNo, OtherStuff from OldPlayers

union 
select Name, Rank, SerNo, OtherStuff from NewPlayers
)

/*
OldPlayers
*/

go

If I then uncomment both comments, and comment out the expression in parentheses, I also get results (from one table, of course).

If I now re-comment the table name at the end, and uncomment the parenthetical expression so that it can replace the table name, I get the error "Incorrect syntax near ')'."

Why can't I substitute the union expression for the table name?

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

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

发布评论

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

评论(2

番薯 2024-12-09 00:29:44

如果你尝试这样:

select Name, Rank, SerNo, OtherStuff from 
(
select Name, Rank, SerNo, OtherStuff from OldPlayers
union 
select Name, Rank, SerNo, OtherStuff from NewPlayers
) as Players

If you try it like this:

select Name, Rank, SerNo, OtherStuff from 
(
select Name, Rank, SerNo, OtherStuff from OldPlayers
union 
select Name, Rank, SerNo, OtherStuff from NewPlayers
) as Players
悲欢浪云 2024-12-09 00:29:44

我手头没有 SQL Server 的副本,但是当您将表的表达式用作查询的一部分时,情况是否总是如此 - 语法要求您命名结果表(除非它是最外层的部分)查询的名称,以便表名引用表本身)?因此,如果您使用“Select 1”而不是联合查询(我相信这是合法的),您仍然需要命名结果“表”。

所以,

select distinct Name, Rank, SerNo, OtherStuff from 
(
select Name, Rank, SerNo, OtherStuff from OldPlayers
union 
select Name, Rank, SerNo, OtherStuff from NewPlayers
) SYNTAXREQUIRESTABLENAME

应该有效。

I don't have a copy of SQL Server handy, but isn't this always the case when you use an expression for a table as part of a query - the syntax requires you to name the resulting table (unless it is the outermost part of the query, such that the table name would refer to the table itself)? So if instead of a union query you used "Select 1" (I believe that is legal) you would still have to name the resulting "table".

So,

select distinct Name, Rank, SerNo, OtherStuff from 
(
select Name, Rank, SerNo, OtherStuff from OldPlayers
union 
select Name, Rank, SerNo, OtherStuff from NewPlayers
) SYNTAXREQUIRESTABLENAME

should work.

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