简体   繁体   English

将 sql 表 (t1) 从一个 db (db1) 导入到另一个 (db2) (t2),然后使用 t2 更新 db2 中表的值

[英]Importing sql table (t1) from one db (db1)to another (db2) (t2)and then use t2 to update values of a table in db2

I need a query to import data of a table into a different table and different database.我需要一个查询来将一个表的数据导入到不同的表和不同的数据库中。 Then using the new table I need to update another table in same database然后使用新表我需要更新同一数据库中的另一个表

As you tagged SSMS, I'm assuming you're using SQL Server.当您标记 SSMS 时,我假设您正在使用 SQL Server。 This answer may apply to other databases, but you'd need to check.此答案可能适用于其他数据库,但您需要检查。

How to refer to other databases如何引用其他数据库

Assuming your database is on the same server, and the table is in the 'dbo' schema, then you can refer to the other database/table as follows假设您的数据库在同一台服务器上,并且表在 'dbo' 架构中,那么您可以按如下方式引用其他数据库/表

SELECT  *
FROM    [db1].[dbo].[t1]

If it's on a different server (but has been set up as a linked server) you can do something similar如果它在不同的服务器上(但已设置为链接服务器),您可以执行类似的操作

SELECT  *
FROM    [servername].[db1].[dbo].[t1]

Making a copy of the data制作数据的副本

To save it as a new table within your current database, you could either create a copy of the table's structure in the current database and use an INSERT INTO command, or instead let SQL Server make the table for you by using the 'INTO' clause in the SELECT eg,要将其保存为当前数据库中的新表,您可以在当前数据库中创建表结构的副本并使用 INSERT INTO 命令,或者让 SQL Server 使用“INTO”子句为您创建表在 SELECT 例如,

SELECT   *
INTO    [db2].[dbo].[t2]     -- Or just simply [t2] if you're running this from that database and are happy with [dbo]
FROM    [db1].[dbo].[t1]

The above copies the data from the t1 table in db1 to a new table t2 in db2.以上将db1中t1表的数据复制到db2中的新表t2中。

You can then use the data in t2 as you normally would use a table.然后,您可以像通常使用表一样使用 t2 中的数据。

If you're running this from within d1, you will always need to refer to the tables in d2 properly (and/or alias them) as below.如果您从 d1 中运行它,您将始终需要正确引用 d2 中的表(和/或别名),如下所示。

UPDATE    t3
SET       xfield = t2.zfield
FROM      [db2].[dbo].[t3] AS t3
          INNER JOIN [db2].[dbo].[t2] AS t2 ON t3.id = t2.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM