2012-02-03 27 views
2

我想要做這樣的事情。更新列基於SELECT參數來自UPDATE

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) 

我想更新country_id這些來自不同數據庫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_idcountry_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) 

我想更新上面使用此表tbl_statescountry_id列表中的主列在select語句之後獲得主鍵。

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

對不起,標題,我不知道這是叫什麼。你能幫我解決這個問題嗎?

+0

+1我不知道該怎麼稱呼它!謝天謝地(有時)谷歌可以讀取頭腦... – WienerDog 2012-03-23 17:00:13

回答

3
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 
+0

拍攝,還沒睡過哈哈。謝謝! – 2012-02-03 21:44:37