如果满足某些条件,如何从数据库发送电子邮件?

问题描述 投票:0回答:1

我是初学者。

我们有:

数据库, 模式, 表名

Table包含列:NumberStateExportTimeImportTime

我需要创建一个过程,如果记录的数量大于5(对于State = 2的记录),它将从数据库(MSSQL)向我的邮箱发送一封电子邮件。该电子邮件必须按降序包含该表的所有行(如果满足条件)。

然后,该过程必须每小时作为一个作业执行,并使用链接服务器连接到服务器...

我只知道如何使用select来编写两个语句以获取我需要的数据,但仅此而已。

SELECT
  *
FROM schemaname.tablename
WHERE state = 2
ORDER BY ExportDateTime DESC

SELECT
  COUNT(*) AS Queued
FROM schemaname.tablename
WHERE state = 2

有小费吗?

sql sql-server linked-server management-studio-express
1个回答
0
投票

这是我们的解决方案:

首先,创建以下proc(帽子提示给Tony Rogerson,SQL Server MVP)

CREATE PROC [dbo].[email_object_as_html]
    @source_db    sysname,       --  Where the @object_name is resident
    @schema       sysname,       --  Schema name eg.. dbo.
    @object_name  sysname,       --  Table or view to email
    @order_clause NVARCHAR(MAX), --  The order by clause eg. x, y, z
    @email        NVARCHAR(MAX),  --  Email recipient list
    @subject      NVARCHAR(MAX),
    @body_prefix  NVARCHAR(MAX),
    @body_suffix  NVARCHAR(MAX),
    @bcc NVARCHAR(MAX) = ''
AS
BEGIN
    /**
        Convert's the specified table or view into an html table and emails it.

        Tony Rogerson, SQL Server MVP
        28 March 2008
        http://sqlblogcasts.com/blogs/tonyrogerson

        You are free to use and modify this,
        just keep the above in place;
        I offer no warranties, you get this as is.

    **/
    IF LEN(LTRIM(RTRIM(ISNULL(@order_clause,N'')))) = 0
        SET @order_clause = N''
    ELSE
        SET @order_clause = ' order by ' + @order_clause

    declare
               @body    nvarchar(max)

    --  Get columns for table headers..
    exec( '
    declare col_cur cursor for
        select name
        from ' + @source_db + '.sys.columns
        where object_id = object_id( ''' + @source_db + '.' + @schema + '.' + @object_name + ''')
        order by column_id
        ' )

    open col_cur

    declare @col_name sysname
    declare @col_list nvarchar(max)

    fetch next from col_cur into @col_name

    set @body = N'<table border=1 cellpadding=1 cellspacing=1><tr>'

    while @@fetch_status = 0
    begin
        set @body = cast( @body as nvarchar(max) )
                  + N'<th>' + @col_name + '</th>'

        set @col_list = coalesce( @col_list + ',', '' ) + ' td = ' + cast( @col_name as nvarchar(max) ) + ', '''''

        FETCH NEXT FROM col_cur INTO @col_name

    END

    DEALLOCATE col_cur

    SET @body = CAST( @body AS NVARCHAR(MAX) )
              + '</tr>'

    DECLARE @query_result NVARCHAR(MAX)
    DECLARE @nsql NVARCHAR(MAX)

    --  Form the query, use XML PATH to get the HTML
    SET @nsql = '
        select @qr =
               cast( ( select ' + CAST( @col_list AS NVARCHAR(MAX) )+ '
                       from ' + @source_db + '.' + @schema + '.' + @object_name +
                       @order_clause + '
                       for xml path( ''tr'' ), type
                       ) as nvarchar(max) )'

    EXEC sp_executesql @nsql, N'@qr nvarchar(max) output', @query_result OUTPUT

    SET @body = CAST( @body AS NVARCHAR(MAX) )
              + @query_result

    --  Send notification
    IF @subject IS NULL OR @subject = ''
    SET @subject = 'Your table as requested'

    SET @body = @body + CAST( '</table>' AS NVARCHAR(MAX) )

    SET @body = '<p>' + @body_prefix + '</p>'
              + CAST( @body AS NVARCHAR(MAX) )
              + '<br><br>' + @body_suffix

    SET @body = REPLACE(REPLACE(@body, '&lt;', '<'), '&gt;','>')              


    EXEC msdb.dbo.sp_send_dbmail 
                                  @recipients = @email,
                                  @body = @body,
                                  @body_format = 'HTML',
                                  @subject = @subject,
                                  @blind_copy_recipients = @bcc
END

然后,使用临时表和查询结果,您可以像这样调用电子邮件过程:

SELECT * 
INTO #temp
FROM schemaname.tablename
WHERE state=2
ORDER BY ExportDateTime DESC

IF (SELECT COUNT(*) AS Queued FROM #temp ) > 5

    EXEC dbo.email_object_as_html 
        @source_db = 'tempdb',
        @schema = '',
        @object_name = '#temp',
        @order_clause = N'ExportDateTime',
        @email = N'[email protected]', 
        @subject = N'schemaname.tablename results',
        @body_prefix = N'Here are your query results:',
        @body_suffix = N'This email brought to you by digital.aaron @ StackOverflow',
        @bcc = N'[email protected]'
© www.soinside.com 2019 - 2024. All rights reserved.