SQL查询 - 列名无效

时间:2013-11-20 08:39:58

标签: sql sql-server

执行以下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

错误说:

  

Msg 207,Level 16,State 1,Line 7
  列名称'Percent_Used'无效。

为什么我会收到此错误?

3 个答案:

答案 0 :(得分:4)

如果您看到查询的逻辑顺序处理,则在select之前评估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

答案 1 :(得分:3)

您正尝试使用已定义的列在WHERE子句中进行过滤。表sysfiles

中不存在此列

如果您愿意,可以将SELECT包裹在另一个SELECT中,并对后者SELECT进行过滤。这样,该列已经“存在”。

答案 2 :(得分:0)

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