1.下载安装postgres odbc driver
https://www.postgresql.org/ftp/odbc/versions/msi/
2.创建odbc 服务器
创建sqlserver 链接服务器
USE [Card3500]
exec sp_addlinkedserver
@server='postgres11', --ODBC里面data source name
@srvproduct='postgres', --自己随便
@provider='MSDASQL', --固定这个
@datasrc=NULL,
@location=NULL,
@provstr='DRIVER={PostgreSQL ANSI};SERVER=127.0.0.1;DATABASE=postgres;UID=postgres;PORT=5432;',
@catalog = NULL
GO
USE [Card3500]
---创建连接postgres数据库的账号及密码
exec sp_addlinkedsrvlogin
@rmtsrvname='postgres11',----ODBC里面data source name
@useself='false',
@rmtuser='postgres',---postgres账号
@rmtpassword='';--postgres账号其密码
GO
--测试是否可以访问mysql数据库中的表
select * from openquery(postgres11,'SELECT * FROM tb; ')
-----建立允许远程访问连接操作
USE [Card3500]
GO
EXEC Card3500.dbo.sp_serveroption @server=N'postgres11',@optname=N'rpc out',@optvalue=N'TRUE'
GO
EXEC Card3500.dbo.sp_serveroption @server=N'postgres11',@optname=N'remote proc transaction promotion',@optvalue=N'false'
GO
--建立LOOPBACK 服务器链接 (回路)
USE [Card3500]
GO
EXEC sp_addlinkedserver @server=N'loopback1',@srvproduct=N' ',@provider=N'SQLNCLI',
@datasrc=@@SERVERNAME
go
--设置服务器链接选项,阻止SQL Server 由于远过程调用而将本地事务提升为分布事务(重点)
USE [Card3500]
GO
EXEC Card3500.dbo.sp_serveroption @server=N'loopback1',@optname=N'rpc out',@optvalue=N'TRUE'
GO
EXEC Card3500.dbo.sp_serveroption @server=N'loopback1',@optname=N'remote proc transaction promotion',@optvalue=N'false'
GO
---编写触发器和存储过程
--insert
USE [Card3500]
GO
CREATE TRIGGER TR_INSERT_pg_TB ON Card3500.DBO.TB
FOR INSERT
AS
DECLARE @ID INT,@QTY INT
SELECT @ID=ID,@QTY=QTY FROM INSERTED;
BEGIN
EXEC loopback1.Card3500.dbo.sp_insert_pg_tb @id,@qty;
END
go
USE [Card3500]
GO
CREATE PROCEDURE SP_INSERT_pg_tb
@ID INT,
@QTY INT
AS
BEGIN
SET NOCOUNT ON
INSERT OPENQUERY(postgres11,'select * from tb')(id,qty) values (@id,@qty);
SET NOCOUNT OFF
END
GO
---update
USE [Card3500]
GO
CREATE TRIGGER TR_UPDATE_pg_TB ON Card3500.DBO.TB
FOR UPDATE
AS
DECLARE @ID INT,@QTY INT
SELECT @ID=ID,@QTY=QTY FROM INSERTED;
BEGIN
EXEC loopback1.Card3500.dbo.sp_update_pg_tb @id,@qty;
END
GO
USE [Card3500]
GO
CREATE PROCEDURE SP_UPDATE_pg_tb
@ID INT,
@QTY INT
AS
BEGIN
SET NOCOUNT ON
UPDATE OPENQUERY(postgres11,'select * from tb') SET qty=@qty WHERE id=@id
SET NOCOUNT OFF
END
go
--delete
USE [Card3500]
GO
CREATE TRIGGER TR_DELETE_pg_TB ON Card3500.DBO.TB
FOR DELETE
AS
DECLARE @ID INT
SELECT @ID=ID FROM DELETED;
BEGIN
EXEC loopback1.Card3500.dbo.sp_DELETE_pg_tb @id;
END
go
USE [Card3500]
GO
CREATE PROCEDURE SP_DELETE_pg_tb
@ID INT
AS
BEGIN
SET NOCOUNT ON
DELETE OPENQUERY(postgres11,'select * from tb') WHERE id=@id
SET NOCOUNT OFF
END
go