无法在WHERE中添加别名的解决方案

时间:2014-08-05 19:02:02

标签: sql sql-server tsql

我知道在SQL服务器中,不能在WHERE子句中使用别名作为列名。虽然WHERE中的过滤器目前似乎不起作用,但我已尝试多次按扩展名(仅LDF和MDF)过滤文件,但它不起作用。以下是我所拥有的,我想知道是否有人知道实现这一目标的方法。

我在输出集中想要的只是在FileType列中包含LDF或MDF的行。

这是我试过的

SELECT DISTINCT
        CWV.SystemName ,
        CIL.CIL_INSTANCE_NAME AS [Instance Name] ,
        CWV.DriveLetter ,
        UPPER(RIGHT(CIDFP.physical_name, 3)) AS FileType ,
        CIDFP.physical_name AS [Physical Name]
FROM    CCS_InstanceDatabaseFilesProperty AS CIDFP
        INNER JOIN CCS_INSTANCE_LIST AS CIL ON CIL.CIL_ID = CIDFP.CIL_ID
        INNER JOIN CCS_InstanceServerProperty AS CSP ON CSP.CIL_ID = CIDFP.CIL_ID
        LEFT OUTER JOIN CCS_Win32_Volume AS CWV ON CIL.CSL_ID = CWV.CSL_ID
                                                   AND LEFT(CIDFP.physical_name,
                                                      2) = CWV.DriveLetter
WHERE   ( CWV.SystemName IS NOT NULL )
        AND ( CWV.DriveLetter IS NOT NULL )
        OR RIGHT(CIDFP.physical_name, 3) = 'mdf'
        OR RIGHT(CIDFP.physical_name, 3) = 'ldf'

提前感谢任何输入/回答。

2 个答案:

答案 0 :(得分:2)

将WHERE子句更改为:

WHERE   ( CWV.SystemName IS NOT NULL )
        AND ( CWV.DriveLetter IS NOT NULL )
        AND (RIGHT(CIDFP.physical_name, 3) = 'mdf'
        OR RIGHT(CIDFP.physical_name, 3) = 'ldf')

答案 1 :(得分:2)

您的AND / OR逻辑未正确分组。

如果您希望DriveLetter不为空AND physical_name =' mdf' OR' ldf'你可能会改变它:

WHERE   CWV.SystemName IS NOT NULL
    AND CWV.DriveLetter IS NOT NULL 
    AND RIGHT(CIDFP.physical_name, 3) in ('mdf', 'ldf')