无法用 SQL UNION 查询替换表名
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你尝试这样:
If you try it like this:
我手头没有 SQL Server 的副本,但是当您将表的表达式用作查询的一部分时,情况是否总是如此 - 语法要求您命名结果表(除非它是最外层的部分)查询的名称,以便表名引用表本身)?因此,如果您使用“Select 1”而不是联合查询(我相信这是合法的),您仍然需要命名结果“表”。
所以,
应该有效。
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,
should work.