我正在尝试将查询结果添加到现有表的列中。到目前为止,下面的查询找到了电线30公里范围内最近的变电站。
Select el1.id,
el1.geog4269.STAsText(),
(Select TOP 1 es.name from Test.dbo.electric_substations as es
with (index(sidx_es))
WHERE el1.geog4269.STDistance(es.geog) < 30000
order by el1.geog4269.STDistance(es.geog)
)As NearestElectricSubstation
from Test.dbo.electric_lines AS el1;
现在我要做的是更新名为NNElines的表,该表具有以下模式:
CREATE TABLE NNElines
(
id INT NOT NULL PRIMARY KEY,
Location geography NOT NULL,
Nearest_Esub varchar(50) NOT NULL
);
我想用结果中的el1.id更新id,使用el1.geog4269.STAsText()更新id,使用NearestElectricSubstation更新Nearest_Esub。我正在尝试更新查询,但没有得到任何东西。任何帮助表示赞赏。谢谢
Update Test.dbo.NNElines
SET id = el1.id,
Location = el1.geog4269.STAsText()
From(
Select
fnc.el1.id,
fnc. el1.geog4269.STAsText()
From Test.dbo.electric_lines AS el1
CROSS APPLY
(Select TOP 1 es.name from Test.dbo.electric_substations as es
with (index(sidx_es))
WHERE el1.geog4269.STDistance(es.geog) < 30000
order by el1.geog4269.STDistance(es.geog)
) fnc
--As NearestElectricSubstation
--from Test.dbo.electric_lines AS el1;
);
答案 0 :(得分:0)
试试这个。更新表时可以使用JOIN。因此,我将您的查询加入了ID上的NNElines表,并使用查询中的相应值更新NNElines表。
UPDATE NNElines
SET a.location = b.geog4269.STAsText(),
a.Nearest_Esub = b.NearestElectricSubstation
FROM NNElines a
JOIN
(Select el1.id,
el1.geog4269.STAsText(),
(Select TOP 1 es.name from Test.dbo.electric_substations as es with (index(sidx_es))
WHERE el1.geog4269.STDistance(es.geog) < 30000
order by el1.geog4269.STDistance(es.geog)
)As NearestElectricSubstation
from Test.dbo.electric_lines AS el1) b
ON a.id = b.id