【问题标题】:Update existing table with query results SQL Server 2012使用查询结果更新现有表 SQL Server 2012
【发布时间】:2014-07-21 23:32:30
【问题描述】:

我正在尝试将我的查询结果添加到现有表的列中。到目前为止,下面的查询找到了距离电线 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() 更新位置,用 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;
    );

【问题讨论】:

  • 您需要使用INSERT with SELECT
  • 这令人困惑。您是要 UPDATE NNElines 中存在的现有行还是 INSERT 新行?
  • 表已经创建了行,所以我只是想更新表。希望现在很清楚,我刚开始使用它,如有任何混淆,请见谅
  • @Jonast92 我已经更新了到目前为止我尝试过的内容。谢谢
  • 更新语句的工作方式如下:更新列 SET 字段 = 值 WHERE 条件。在这种情况下,您的值是 select 语句,最好配置连接但不一定。

标签: sql sql-server-2012-express


【解决方案1】:

试试这个。更新表时可以使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    • 2015-09-04
    • 2020-11-10
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多