代码之家  ›  专栏  ›  技术社区  ›  pepr

MSSQL:如何检查是否调用Sysmail附加帐户SP?

  •  1
  • pepr  · 技术社区  · 6 年前

    我有一个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脚本中检查帐户是否已存在(跳过可能导致错误的duplicit安装)?

    我应该问一下 msdb.dbo.sysmail_account 视野?或者我应该 TRY ... CATCH 这个 EXEC msdb.dbo.sysmail_help_account_sp @account_name='myaccount' 如果账户不存在,那就失败了?

    有更好的办法吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   EzLo tumao kaixin    6 年前

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

    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