2012-12-27 16 views
-3

我有一個已經有數據的表。用於從另一個表中輸入數據並在源表中創建一列以鏈接另一個表的SQL腳本

Table -> Address: 
AddressID, Address 1, Address 2, email etc... 

Table -> Branches: 
BranchesID, StoreName, Address 1, Address 2 

現在我需要一個腳本,它可以在其中具有新複製的數據AddressID這樣我就可以使用地址表參考分行地址分行復制所有數據從分支表地址表和創建列。

請幫忙。

到目前爲止,我已經嘗試過這麼多。

INSERT Address1, Address2, City, ZipCode) 
OUTPUT AddressID 
INTO Addresses 
SELECT Address1, Address2 
FROM Baranches; 

但我不知道如何插入從地址表中新創建的記錄ID爲設有分公司表...

tahnks

+0

ü想什麼........ –

+0

看到我的編輯請 –

+0

我需要建立一個具有AddressID列。我需要將分支表中的所有數據複製到地址表中,並且需要這些地址ID –

回答

1

首先,你需要AddressId字段添加到Branches。我不知道該怎麼做RDBMS使用所以這裏是MSSQL一個例子,但它應該有一些變化的所有RDBMS工作:

ALTER TABLE BRANCHES ADD AddressID bigint; 

然後從branches插入地址到Address表。我猜AddressId是autoincremented PK ?.此查詢中的WHERE聲明允許避免地址重複。

insert into ADDRESS (Address1, Address2) 
select Address1, Address2 
    from BRANCHES 
     where 
     not exists(select AddressID 
         from ADDRESS 
         where Address1=BRANCHES.Address1 
           and 
           Address2=BRANCHES.Address2) 

現在我們應填寫AddressID領域的分支:

update BRANCHES SET AddressId=(select TOP 1 AddressId from Address where 
            Address1=BRANCHES.Address1 
            and 
            Address2=BRANCHES.Address2) 
+0

這就是我正在尋找的.. .thanks人... –

+0

我要去嘗試這個在某個時候,讓你知道是否需要任何變化 –

相關問題