sql 查询 - 无效的列名
Posted
技术标签:
【中文标题】sql 查询 - 无效的列名【英文标题】:sql query - Invalid column name 【发布时间】:2013-11-20 08:39:57 【问题描述】:执行以下 sql 查询时出现错误。
SELECT
RTRIM(name) AS [Segment Name],
growth,groupid AS [Group Id],
filename AS [File Name],
CAST(size/128.0 AS DECIMAL(10,2)) AS [Size in MB],
CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS DECIMAL(10,2)) AS [Space Used],
CAST(size/128.0-(FILEPROPERTY(name, 'SpaceUsed')/128.0) AS DECIMAL(10,2)) AS [Available Space],
CAST((CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS DECIMAL(10,2))/CAST(size/128.0 AS DECIMAL(10,2)))*100 AS DECIMAL(10,2)) AS [Percent_Used]
FROM
sysfiles
WHERE
growth = 0 AND Percent_Used > 60
ORDER BY
groupid DESC
错误提示:
消息 207,第 16 层,状态 1,第 7 行 列名“Percent_Used”无效。
为什么会出现这个错误??
【问题讨论】:
我不太了解 sql-server,但是删除下划线怎么样(因为上面的列别名似乎可以正常工作) 参见Logical Processing Order of the SELECT statement:“因为 SELECT 子句是第 8 步,所以在该子句中定义的任何列别名或派生列都不能被前面的子句引用 ... 4. WHERE ... 8. SELECT ...” 【参考方案1】:如果您看到查询的逻辑顺序处理 where 子句在选择之前进行评估。 要使其工作,您需要使用派生表概念。
1. FROM
2. ON
3. OUTER
4. **WHERE**
5. GROUP BY
6. CUBE | ROLLUP
7. HAVING
8. **SELECT**
http://blog.sqlauthority.com/2009/04/06/sql-server-logical-query-processing-phases-order-of-statement-execution/
Select * from
(
SELECT
RTRIM(name) AS [Segment Name],
growth,groupid AS [Group Id],
filename AS [File Name],
CAST(size/128.0 AS DECIMAL(10,2)) AS [Size in MB],
CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS DECIMAL(10,2)) AS [Space Used],
CAST(size/128.0-(FILEPROPERTY(name, 'SpaceUsed')/128.0) AS DECIMAL(10,2)) AS [Available Space],
CAST((CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS DECIMAL(10,2))/CAST(size/128.0 AS DECIMAL(10,2)))*100 AS DECIMAL(10,2)) AS [Percent_Used]
FROM
sysfiles
) DT
WHERE growth = 0 AND Percent_Used > 60
ORDER BY groupid DESC
【讨论】:
【参考方案2】:您正在尝试使用您在WHERE
子句中定义的列进行过滤。表sysfiles
中不存在该列
如果您愿意,可以将 SELECT
包装在另一个 SELECT
中,并对后者 SELECT
进行过滤。这样该列就已经“存在”了。
【讨论】:
【参考方案3】:WITH cte
AS
(
SELECT
RTRIM(name) AS [Segment Name],
growth,groupid AS [Group Id],
filename AS [File Name],
CAST(size/128.0 AS DECIMAL(10,2)) AS [Size in MB],
CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS DECIMAL(10,2)) AS [Space Used],
CAST(size/128.0-(FILEPROPERTY(name, 'SpaceUsed')/128.0) AS DECIMAL(10,2)) AS [Available Space],
CAST((CAST(FILEPROPERTY(name, 'SpaceUsed')/128.0 AS DECIMAL(10,2))/CAST(size/128.0 AS DECIMAL(10,2)))*100 AS DECIMAL(10,2)) AS [Percent_Used]
FROM
sysfiles
)
SELECT *
FROM cte
WHERE
growth = 0
AND Percent_Used > 60
ORDER BY [Group Id] DESC
【讨论】:
以上是关于sql 查询 - 无效的列名的主要内容,如果未能解决你的问题,请参考以下文章