我在两个不同的数据库中有两个同名的表。 TableA
中的DatabaseA
包含ServerName
列,而TableA
中的另一个DatabaseB
包含ServerId
列。我在TableB
中有第三个表DatabaseB
,其中包含ServerId
和ServerName
,我希望将ServerName
映射到DatabaseA
,其中ServerId
DatabaseB
,DatabaseB
TableA
{/ 1}}。{/ 1>
例如......
在DatabaseA
:
TableA
:
ServerName
MyServer
HisServer
HerServer
在DatabaseB
:
TableB
:
ServerId | ServerName
1 MyServer
2 HisServer
3 HerServer
我想将 ServerNames 映射到 ServerIds ,并将Ids插入 DatabaseB的TableA 。
提前致谢。
答案 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