【问题标题】:Invalid Column Name for computed column? [duplicate]计算列的列名无效? [复制]
【发布时间】:2019-04-09 11:23:47
【问题描述】:

我有以下查询,如果我注释掉导致我的问题的部分(正如我在下面已经完成的那样),它就可以正常工作。

Declare @mPoint As varchar(50) = 'POINT (-107.657141 41.033581)'
Declare @iRadius As int = 5000 --5km for testing. 4 results, 1 with PriorityType = 0.

SELECT FLOOR([Position].STDistance(geography::STGeomFromText(@mPoint, 4326))) AS Distance,
    CASE 
        WHEN [Type] & 64 = 64 THEN 0
        --insert other types as needed. 
        ELSE 1000 
    END AS PriorityType,
    *
FROM [tblAddress]
WHERE DeletedOn IS NULL 
    --AND Distance <= @iRadius --        <-- This is Line 13
ORDER BY PriorityType ASC, Distance ASC; 

这个查询应该过滤数据库中大约 1700 条记录,并根据上述 (static) 结果返回 4 行,其中一个的 PriorityType 为 0。

问题是,Microsoft SQL Server Management Studio(简称 SSMS)给了我错误

Msg 207, Level 16, State 1, Line 13
Invalid column name 'Distance'.

AND Distance &lt;= @iRadius 的“距离”下方还有一条红线。

如果我注释掉该行(如上例所示),我会根据需要获取整个表格。显然,该列存在!那么为什么我会收到错误消息?

【问题讨论】:

  • 您不能在WHERE 中引用SELECT 中的列,因为WHERE 是在SELECT之前确定的。您需要使用 CTE/子查询或在 WHERE 中重复表达式。
  • Where 子句将在 Select 子句之前执行。距离是您在 where 子句中提供的别名。所以查询不会找到距离列。所以尝试在 where 子句中写 FLOOR([Position].STDistance(geography::STGeomFromText(@mPoint, 4326))) 而不是 Distance 或写子查询。

标签: sql-server calculated-columns ssms-2017


【解决方案1】:

检查这个修改后的解决方案,

Declare @mPoint As varchar(50) = 'POINT (-107.657141 41.033581)' Declare @iRadius As int = 5000 SELECT FLOOR([Position].STDistance(geography::STGeomFromText(@mPoint, 4326))) AS Distance, CASE WHEN [Type] & 64 = 64 THEN 0 ELSE 1000 END AS PriorityType, * FROM [tblAddress] WHERE DeletedOn IS NULL AND FLOOR([Position].STDistance(geography::STGeomFromText(@mPoint, 4326)))<= @iRadius ORDER BY PriorityType ASC, Distance ASC;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多