更新 table 中的地理列

Update Geography column in table

我有以下table

Geo 列(数据类型 Geography)为 null 我目前在此 table 中有 11913 行我想做的是使用以下语句更新 Geo 列并填充包含 Geography::STGeomFromText

提供的数据的地理列
DECLARE @Temp TABLE
(
Id bigint,
Latitude decimal(9,6),
Longitude decimal(9,6)
)

Insert Into @Temp (Id, Latitude, Longitude)
    Select id, Latitude, Longitude from Location.Cities 
where Active = 1

Update Location.Cities
set Geo = geography::STGeomFromText (POINT(Select Latitude, Longitude from  @Temp), 4326)
where Id = -- massively confused.....

我遇到的两个问题 Select 来自@Temp 的纬度、经度它说 POINT 不是公认的内置函数名称,另一个是我如何确保更新正确record/row 我从中选择纬度和经度的地方。

我需要这样做的原因是因为在我们的应用程序中,我们允许最终用户按半径搜索。

任何帮助都会很棒。

您不需要临时 table @Temp。您可以直接在 table Location.Cities 上使用 geography::Point

类似这样。

Update Location.Cities
set Geo = geography::Point(Latitude, Longitude , 4326)

如果想用geography::STGeomFromText,可以这样用

    Update Location.Cities
        set Geo = geography::STGeomFromText('POINT(' + CONVERT(VARCHAR(30),Longitude ) + ' ' + CONVERT(VARCHAR(30),Latitude) + )',4326)

ughai 的回答可以,但您会发现性能问题。你最好使用 STPointFromText:

UPDATE Location.Cities
SET Geo = geography::STPointFromText('POINT(' + CAST([Longitude] AS VARCHAR(20)) + ' ' + CAST([Latitude] AS VARCHAR(20)) + ')', 4326)

附带说明一下,您收到错误的原因是因为该函数需要一个 varchar 参数作为它的第一个参数。

如果是我,我会这样做: 声明@batchsize int = 1000; 而(1=1) 开始

    Update top(@batchsize) Location.Cities
    set Geo = geography::Point(Latitude, Longitude), 4326)
    where Geo is null;

    if (@@rowcount < @batchsize)
       break;

end

几点注意事项

  • Point 静态方法是 MS 扩展。也就是说,它不是标准的 OGC 方法。但这很好,它会给你相同的结果。我发现它更具可读性,因为您不需要创建代表该点的 WKT。
  • 我正在批量更新。 无关紧要,因为您的 table 大约有 10k 行,但如果它更大就很重要。这个成语很好学。