最近遇到這樣一個案例,需要修改所有SQL Server的Database Mail的SMTP,原來的SMTP為10.xxx.xxx.xxx, 現在需要修改為192.168.xxx.xxx, 另外需要規範郵件地址,以前這類郵件[email protected]的尾碼需要修改為Serve... ...
最近遇到這樣一個案例,需要修改所有SQL Server的Database Mail的SMTP,原來的SMTP為10.xxx.xxx.xxx, 現在需要修改為192.168.xxx.xxx, 另外需要規範郵件地址,以前這類郵件[email protected]的尾碼需要修改為[email protected](信息做了脫敏處理)。
如果使用SSMS客戶端的UI界面去修改的話, 那麼多伺服器一臺一臺去修改,不僅費時費力,而且枯燥無聊。只能使用腳本,一旦寫好一個腳本,而後使用Multiple Server Query Execution(極力推薦使用這個管理、維護資料庫),執行一次腳本,全部搞定。剩下的時間你可以喝喝茶、學習下新知識!
DECLARE @EmailAccount sysname;
DECLARE @SmtpServer sysname;
DECLARE @EmailAddress NVARCHAR(120);
DECLARE @EmailSuffix NVARCHAR(32);
DECLARE @NewEamilAddress NVARCHAR(120);
--DECLARE @ActualEmailSuffix NVARCHAR(32)='xxxx.com'; SQL Server 2005不支持此功能,會報Cannot assign a default value to a local variable.
DECLARE @ActualEmailSuffix NVARCHAR(32);
DECLARE @ActualSmtpServer sysname;
SET @ActualEmailSuffix='xxx.com';
SET @ActualSmtpServer='192.168.xxx.xxx';
DECLARE EmailAccount_Cursor CURSOR FAST_FORWARD
FOR
SELECT sa.[name]
,ss.[servername]
,sa.email_address
FROM [msdb].[dbo].[sysmail_server] ss
INNER JOIN [msdb].[dbo].[sysmail_account] sa
ON ss.[account_id]=sa.[account_id];
OPEN EmailAccount_Cursor;
FETCH NEXT FROM EmailAccount_Cursor INTO @EmailAccount, @SmtpServer,@EmailAddress;
WHILE @@FETCH_STATUS = 0
BEGIN
IF LTRIM(RTRIM(@SmtpServer))!=@ActualSmtpServer
BEGIN
EXECUTE msdb.dbo.sysmail_update_account_sp
@account_name = @EmailAccount
,@mailserver_name=@ActualSmtpServer;
PRINT @SmtpServer;
PRINT @EmailAccount;
END;
SET @EmailSuffix=SUBSTRING(@EmailAddress,CHARINDEX('@',@EmailAddress)+1, LEN(@EmailAddress) -CHARINDEX('@',@EmailAddress))
IF @EmailSuffix!=@ActualEmailSuffix
BEGIN
SET @NewEamilAddress= REPLACE(@EmailAddress,@EmailSuffix,@ActualEmailSuffix);
EXECUTE msdb.dbo.sysmail_update_account_sp
@account_name = @EmailAccount
,@email_address=@NewEamilAddress
,@mailserver_name=@SmtpServer;
PRINT @EmailAccount;
PRINT @NewEamilAddress;
END;
FETCH NEXT FROM EmailAccount_Cursor INTO @EmailAccount, @SmtpServer,@EmailAddress;
END
CLOSE EmailAccount_Cursor;
DEALLOCATE EmailAccount_Cursor;