SQL Server:根据两个表的数据将值插入一个表

时间:2011-10-17 11:02:07

标签: sql-server-2008-r2

我在两个不同的数据库中有两个同名的表。 TableA中的DatabaseA包含ServerName列,而TableA中的另一个DatabaseB包含ServerId列。我在TableB中有第三个表DatabaseB,其中包含ServerIdServerName,我希望将ServerName映射到DatabaseA,其中ServerId DatabaseBDatabaseB TableA {/ 1}}。{/ 1>

例如......

DatabaseA

TableA

ServerName
  MyServer
  HisServer
  HerServer

DatabaseB

TableB

ServerId | ServerName
1          MyServer
2          HisServer
3          HerServer

我想将 ServerNames 映射到 ServerIds ,并将Ids插入 DatabaseB的TableA

提前致谢。

1 个答案:

答案 0 :(得分:0)

这是一个完整的脚本。

USE master;
IF EXISTS (SELECT * FROM sys.databases WHERE name = N'DatabaseA')
    DROP DATABASE DatabaseA;
IF EXISTS (SELECT * FROM sys.databases WHERE name = N'DatabaseB')
    DROP DATABASE DatabaseB;
CREATE DATABASE DatabaseA;
CREATE DATABASE DatabaseB;
GO
USE DatabaseA;
GO
CREATE TABLE dbo.TableA (
    ServerName  sysname     NOT NULL
);
INSERT INTO dbo.TableA VALUES (N'MyServer');
INSERT INTO dbo.TableA VALUES (N'HisServer');
INSERT INTO dbo.TableA VALUES (N'HerServer');
SELECT * FROM dbo.TableA;
GO
USE DatabaseB;
GO
CREATE TABLE dbo.TableA (
    ServerID    smallint    NOT NULL
);

CREATE TABLE dbo.TableB (
    ServerID    smallint    NOT NULL,
    ServerName  sysname     NOT NULL
);
INSERT INTO dbo.TableB VALUES (1, N'MyServer');
INSERT INTO dbo.TableB VALUES (2, N'HisServer');
INSERT INTO dbo.TableB VALUES (3, N'HerServer');
SELECT * FROM dbo.TableB;

-- "I want to map the ServerNames to the ServerIds and insert the Ids into DatabaseB's TableA."

INSERT INTO dbo.TableA (
    ServerID
)
SELECT bb.ServerID
FROM DatabaseA.dbo.TableA   AS aa
JOIN DatabaseB.dbo.TableB   AS bb
  ON aa.ServerName = bb.ServerName;

SELECT * FROM dbo.TableA;

输出:

ServerName
-------------
MyServer
HisServer
HerServer

ServerID ServerName
-------- -------------------
       1 MyServer
       2 HisServer
       3 HerServer

ServerID
--------
       1
       2
       3