简体   繁体   English

具有别名表名称的两个查询“ select语句”之间的区别

[英]Difference between two queries 'select statement' with alias table name

I want to ask about the difference between these two queries: 我想问一下这两个查询之间的区别:

select ProductName = case when p.ProductID is null then 'Unknown' else p.ProductName end

and

select p.ProductName = case when p.ProductID is null then 'Unknown' else p.ProductName end

(p is an alias for table Product) (p是表Product的别名)

What is the difference between them in sql server management studio 2008 R2? 在sql server management studio 2008 R2中它们之间有什么区别? When I executed the first one, it was executed succesfully, but for the second one I got an error message "Incorrect syntax near '='." 当我执行第一个脚本时,它已成功执行,但是对于第二个脚本,我收到一条错误消息“'='附近的语法不正确”。

Anyone can explain me about this? 有人可以向我解释一下吗? Thanks. 谢谢。

in the first case ProductName is not a table column, it is an alias . 在第一种情况下, ProductName不是表列,而是别名 think of it like this: 这样想:

select case when p.ProductID is null then 'Unknown' else p.ProductName end as ProductName

in the second incorrect query you are trying to do something illegal because you are trying to both select a column from a table and assign to it as if it were an alias you are generating from an expression. 在第二个不正确的查询中,您试图做一些非法的事情,因为您试图同时从表中选择一列并分配给它,就像它是从表达式生成的别名一样。

I think your confusion is that you think ProductName is always a column because there is a column with that name in that table, but in this context ProductName is not a column name; 我认为您的困惑是您认为ProductName始终是一列,因为在该表中有一个具有该名称的列,但是在这种情况下ProductName 不是列名; it is an alias for the case statement results. 它是case语句结果的别名 so when you try p.ProductName you are telling the SQL engine to select the ProductName column from the p table and then you try to assign a case statement as if it were an alias (which it isn't in the p.ProductName context). 因此,当您尝试使用p.ProductName您要告诉SQL引擎从p表中选择ProductName列,然后尝试分配一个case语句,就好像它是一个别名(不在p.ProductName上下文中) 。

you could just as easily use any name for the case statement since it is an alias. 您可以轻松地为case语句使用任何名称,因为它是别名。 you could do: 你可以做:

select DerivedProductName = case when p.ProductID is null then 'Unknown' else p.ProductName end

does that example make it more clear that you aren't dealing with column names when you use this syntax? 该示例是否更清楚地表明您在使用这种语法时不会处理列名?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM