如何在SQL数据库中插入并更新不同服务器中另一个数据库中的某些记录?

时间:2015-11-16 06:27:21

标签: sql-server tsql triggers

2个不同的SQL Server中有2个不同的数据库,因此有2个连接字符串。

我想要一个触发器,如果​​在database1中插入了一条记录,某些字段将在database2中更新。

例如:

数据库1:

ServerIP : x.x.x.x
ServerPort : 1433
Username : x1
password : x2

的Database2:

ServerIP : y.y.y.y
ServerPort : 1590
Username : y1
Password : y2

enter image description here

那么如何为此目的编写触发器或任何其他内容?

1 个答案:

答案 0 :(得分:0)

这应该可以正常工作。如果您对以下内容感到满意,请投票回答,谢谢。

            CREATE TABLE dbo.TestData (
            ServerIP VARCHAR(20),
            ServerPort SMALLINT,
            Username VARCHAR(100),
            [Password] VARCHAR(100)
            );

            GO

            -- Table created on other server/instance after you set up linked server
            CREATE TABLE [dbo].[TestData2] (
            ServerIP VARCHAR(20),
            ServerPort SMALLINT,
            Username VARCHAR(100),
            [Password] VARCHAR(100)
            );

            GO

            -------- Insert trigger ------
            CREATE TRIGGER dbo.AI_InsertConnectionInfo ON [dbo].[TestData]
            AFTER INSERT
            AS


              INSERT INTO [YourServerName].[DatabaseName].[dbo].[TestData2] (ServerIP, ServerPort, Username, [Password])
              SELECT I.ServerIP
                    ,I.ServerPort
                    ,I.UserName
                    ,I.[Password]
              FROM dbo.TestData AS T
              INNER JOIN inserted AS I ON T.ServerIP = I.ServerIP;

            GO

            INSERT INTO dbo.TestData
            VALUES ('192.168.1.1', 1433, 'TestUserName', 'Test123');

            GO

            -- Connect to your new server and query the table to confirm the data's there.

            SELECT * 
            FROM dbo.TestData2;



            -------- Update trigger -------

            CREATE TRIGGER dbo.AU_UpdateConnectionInfo ON [dbo].[TestData]
            AFTER UPDATE
            AS


              UPDATE T
              SET    T.ServerIP = I.ServerIP
                    ,T.ServerPort = I.ServerPort
                    ,T.UserName = I.UserName
                    ,T.[Password] = I.[Password]
              FROM [YourServerName].[DatabaseName].[dbo].[TestData2]  AS T
              INNER JOIN inserted AS I ON T.ServerIP = I.ServerIP;