【问题标题】:Add data from one table into another with same column names将数据从一个表添加到另一个具有相同列名的表中
【发布时间】:2018-03-12 21:02:18
【问题描述】:

我在这里、YouTube 和一般的 Google 搜索中找到了许多示例,但我仍然碰壁。我有两个具有(我相信)相同的表、结构等的数据库。

db1.dbo.table 比 db2.dbo.table 包含更多的信息。我想将 db1.dbo.table 中的一些信息复制到已经创建的 db2.dbo.table 中(其中有一些我想保留的现有值)。

这是一个例子:

SELECT * FROM table WHERE TYPE = '1'

如果我对 db1.dbo.table 运行它,它会返回 12 行的值。当针对 db2.dbo.table 运行时,它会返回 2 行。我想保留这两行,然后从 db1.dbo.table 中添加其他 12 行。

如果我使用:

select * into db2.dbo.table from db1.dbo.table

我得到表已经存在的错误。

如果我尝试以下操作:

Use db1
go
insert into table
select *
from table
where type (this is one of my column names) = '1' (one of the appropriate values)

我收到“只有在使用列列表并且 IDENTITY_INSERT 为 ON 时,才能为表 'table' 中的标识列指定显式值。”在研究中,我尝试了以下方法:

Set Identity_Insert table (the name of my table) ON
Go
Insert into db2.dbo.table(column 1,column2,etc.,)
select (here, I've tried * as well as the same column1,column2,etc., values as above)
From db1.dbo.table

我还没有找到正确的组合。我想说我仍然是 SQL 的新手,但我了解技术并且理解在我阅读/尝试为我的环境编辑和执行的示例中发生了什么,我只是不确定如何正确排除故障。我将在下面重申我想要完成的任务。

我想复制从以下位置返回的值:

SELECT * FROM TABLE WHERE TYPE = '1' in db1 (returns 12 rows)
into db2 (where the same returns 2 rows, I want this to return the same 2, plus the 12 from the other db when I'm done).

【问题讨论】:

  • 你在用什么dbms?表的结构是什么?检查insertselect 查询之间的列类型和列顺序。另见minimal reproducible example

标签: sql


【解决方案1】:

尝试使用 INSERT INTO 代替 SELECT INTO:

INSERT INTO 
    db2.dbo.table 
        (
        col1, 
        col2, 
        col3, 
        etc.
        )
    SELECT 
        col1, 
        col2, 
        col3, 
        etc. 
    FROM 
        db1.dbo.table
    WHERE 
        TYPE = '1' 

【讨论】:

  • 谢谢你,它成功了。在尝试导入三个“类型”值之一时,我遇到了“外键相同表约束”,但能够弄清楚这一点。就我而言,我只需要删除其中一个字段。
猜你喜欢
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
  • 2022-01-26
  • 2021-12-27
  • 2015-06-11
相关资源
最近更新 更多