MSSQL:如何检查是否调用sysmail_add_account_sp?

时间:2018-06-04 14:56:37

标签: sql-server email

我有一个MS-SQL安装脚本的片段,它添加了sysmail帐户(然后是sysmail配置文件......)

EXECUTE msdb.dbo.sysmail_add_account_sp
    @account_name = 'myaccount',
    @description = 'xxx',
    @email_address = 'myaddress@example.com',
    @replyto_address = 'myaddress@example.com',
    @display_name = 'My Mailer Account',
    @mailserver_name = 'smtp.example.com' ;

如何检查SQL脚本内部是否已存在该帐户(跳过可能导致错误的双重安装)?

我应该查询msdb.dbo.sysmail_account视图吗?或者,如果帐户不存在,我应该TRY ... CATCH EXEC msdb.dbo.sysmail_help_account_sp @account_name='myaccount'失败吗?

还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用该查询检查该帐户是否已存在,然后更新(如果需要)或创建。

DECLARE 
    @AccountName VARCHAR(100) = 'account_name',
    @email_address VARCHAR(100) = 'email_address',
    @display_name VARCHAR(100) = 'display_name',
    @replyto_address VARCHAR(100) = 'replyto_address',  
    @description VARCHAR(100) = 'description',   
    @mailserver_name VARCHAR(100) = 'server_name',   
    @mailserver_type VARCHAR(100) = 'server_type',   
    @port VARCHAR(100) = 587,
    @timeout INT = 30,  
    @username VARCHAR(100) = 'username',  
    @password VARCHAR(100) = 'password',  
    @use_default_credentials BIT = 1,
    @enable_ssl BIT = 0


IF EXISTS (SELECT 'email account already created' FROM msdb.dbo.sysmail_account AS T WHERE T.name = @AccountName)

    EXEC msdb.dbo.sysmail_update_account_sp 
        @account_name = @AccountName,  
        @email_address = @email_address,   
        @display_name = @display_name,   
        @replyto_address = @replyto_address,  
        @description = @description,   
        @mailserver_name = @mailserver_name,   
        @mailserver_type = @mailserver_type,   
        @port = @port,   
        @timeout = @timeout,  
        @username = @username,  
        @password = @password,  
        @use_default_credentials = @use_default_credentials,  
        @enable_ssl = @enable_ssl 

ELSE

    EXECUTE msdb.dbo.sysmail_add_account_sp
        @account_name = @AccountName,  
        @email_address = @email_address,   
        @display_name = @display_name,   
        @replyto_address = @replyto_address,  
        @description = @description,   
        @mailserver_name = @mailserver_name,   
        @mailserver_type = @mailserver_type,   
        @port = @port,
        @username = @username,  
        @password = @password,  
        @use_default_credentials = @use_default_credentials,  
        @enable_ssl = @enable_ssl