【问题标题】:Update Column based on SELECT with Parameter coming from UPDATE基于 SELECT 更新列,参数来自 UPDATE
【发布时间】:2012-02-03 21:24:46
【问题描述】:

我想做这样的事情。

UPDATE tbl_states AS ts
SET    tbl_states.country_id = (SELECT tbl_countries.country_id
                                FROM   tbl_states ts1
                                       JOIN tbl_countries
                                         ON tbl_countries.country_id_id =
                                            ts1.country_id
                                WHERE  ts1.country_id_id = ts.country_id_id)  

我想根据插入新数据库的新主键将来自不同数据库的 old country_id 更新为 new country_id。这里给你一个想法是架构。

CREATE TABLE [dbo].[tbl_countries](
    [country_id] [int] IDENTITY(1,1) NOT NULL,
    [country_id_id] [int] NULL,
    [country_name] [varchar](50) NULL)

country_id_id 是下表中引用的 country_id 我将向您展示tbl_states

CREATE TABLE [dbo].[tbl_states](
    [state_id] [int] IDENTITY(1,1) NOT NULL,
    [state_name] [varchar](50) NULL,
    [country_id] [int] NULL,
    [state_abbr] [char](3) NOT NULL)

我想使用下面的 select 语句将这个表的 country_idtbl_states 更新为上表的主列来获取主键。

SELECT tbl_countries.country_id
FROM   tbl_states_old
       JOIN tbl_countries
         ON tbl_countries.country_id_id = tbl_states_old.country_id  

对不起标题,我不知道这叫什么。你能帮我解决这个问题吗?

【问题讨论】:

  • +1 我也不知道该怎么称呼它!谢天谢地(有时)谷歌可以读心......

标签: sql-server-2008 sql-update sql


【解决方案1】:
UPDATE s
    SET country_id = c.country_id
    FROM tbl_states s
        INNER JOIN tbl_countries c
            ON s.country_id = c.country_id_id

【讨论】:

  • 拍,还没睡哈哈。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-18
  • 2020-11-29
  • 1970-01-01
相关资源
最近更新 更多