【问题标题】:Insert a value based on id from two different tables根据两个不同表中的 id 插入一个值
【发布时间】:2013-07-04 07:17:21
【问题描述】:

我有一个很大的问题。

我正在尝试将一些数据从现有表迁移到新表。我很难弄清楚如何执行以下操作:

在地址表中有两列:

 AddressTable
 ---------------------------------------------
 StateCode(nvarchar) and CountryCode(nvarchar)

两者都包含州和国家/地区代码的两个字母代码。

现在我们在新表中创建了两个外键

 NewAddressTable
 ---------------------
 StateId and CountryId

即对应两个表State和Country

StateTable has (Id,(FK)IdCountry,Name,Code)
CountryTable has (Id,Name,Code)

我正在尝试做的是基于地址表上的州和国家/地区代码如何添加基于州和代码的新表中的值替换旧表中的值。

一个例子:

AddressTable
-------------
City        StateCode   PostalCode  CountryCode
North Haven CT          06473       US

NewAddressTable
---------------
IdCountry   IdState
236         8

CountryTable
--------------- 
Id   Name           Code
236  UNITED STATES  US

StateTable
--------------
Id   IdCountry  Name            Code
8    236            CONNECTICUT CT

谢谢。

【问题讨论】:

  • 您的旧地址表也应该从您的新表中获取国家和州 ID?如果是这样,这是否意味着您必须为此创建新字段或将其放入 statecode 和 countrycode 中?

标签: sql tsql


【解决方案1】:

这样的事情应该可以工作。

insert into newtable
(idCountry, idState)
select country.id, state.id
from oldtable join country on oldtable.CountryCode = Country.Code
join state on oldtable.stateCode = state.code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多