在 SQL Server 中設置主從數據庫權限涉及幾個關鍵步驟,以確保數據的安全性和完整性。以下是一個基本的指南:
創建用戶和角色:
ReplicationReader
),并授予該角色對主數據庫的讀取權限。-- 創建用戶
CREATE USER [ReplicationUser] FROM EXTERNAL PROVIDER;
-- 授予角色
ALTER ROLE [ReplicationReader] ADD MEMBER [ReplicationUser];
-- 授予角色對主數據庫的讀取權限
GRANT SELECT ON ALL TABLES IN SCHEMA public TO [ReplicationReader];
配置復制:
-- 啟用復制
ALTER DATABASE [YourDatabaseName] SET REPLICATION;
-- 創建發布
EXEC sp_addpublication @publication = 'YourPublicationName', @description = 'YourDescription';
-- 配置發布選項
EXEC sp_publish @publication = 'YourPublicationName', @article = 'YourArticleName', @type = 'none';
創建用戶和角色:
ReplicationSubscriber
),并授予該角色對從數據庫的寫入權限。-- 創建用戶
CREATE USER [ReplicationUser] FROM EXTERNAL PROVIDER;
-- 授予角色
ALTER ROLE [ReplicationSubscriber] ADD MEMBER [ReplicationUser];
-- 授予角色對從數據庫的寫入權限
GRANT INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO [ReplicationSubscriber];
配置訂閱:
-- 創建訂閱
EXEC sp_addsubscription @publication = 'YourPublicationName', @subscriber = 'YourSubscriberServer', @subscriber_db = 'YourSubscriberDatabase', @connection_string = 'YourConnectionString';
檢查權限:
ReplicationUser
只有讀取權限。ReplicationSubscriber
只有寫入權限。審計和日志:
以下是一個完整的示例腳本,展示了如何在主從數據庫中設置權限:
-- 主數據庫配置
USE [YourDatabaseName];
-- 創建用戶
CREATE USER [ReplicationUser] FROM EXTERNAL PROVIDER;
-- 授予角色
ALTER ROLE [ReplicationReader] ADD MEMBER [ReplicationUser];
-- 授予角色對主數據庫的讀取權限
GRANT SELECT ON ALL TABLES IN SCHEMA public TO [ReplicationReader];
-- 啟用復制
ALTER DATABASE [YourDatabaseName] SET REPLICATION;
-- 創建發布
EXEC sp_addpublication @publication = 'YourPublicationName', @description = 'YourDescription';
-- 配置發布選項
EXEC sp_publish @publication = 'YourPublicationName', @article = 'YourArticleName', @type = 'none';
-- 從數據庫配置
USE [YourSubscriberDatabase];
-- 創建用戶
CREATE USER [ReplicationUser] FROM EXTERNAL PROVIDER;
-- 授予角色
ALTER ROLE [ReplicationSubscriber] ADD MEMBER [ReplicationUser];
-- 授予角色對從數據庫的寫入權限
GRANT INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO [ReplicationSubscriber];
-- 創建訂閱
EXEC sp_addsubscription @publication = 'YourPublicationName', @subscriber = 'YourSubscriberServer', @subscriber_db = 'YourSubscriberDatabase', @connection_string = 'YourConnectionString';
通過以上步驟,您可以在 SQL Server 中設置主從數據庫的權限,確保數據的安全性和完整性。