我想做这样的事情。
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_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 语句来获取主键,将此表 tbl_states
的 country_id
列更新为上表的主列。
SELECT tbl_countries.country_id
FROM tbl_states_old
JOIN tbl_countries
ON tbl_countries.country_id_id = tbl_states_old.country_id
对不起,我不知道这个标题叫什么。你能帮我解决这个问题吗?
最佳答案
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
关于sql-server-2008 - 基于 SELECT 更新列,参数来自 UPDATE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9135701/