我需要通过电子邮件发送的sql查询结果采用可读形式。更改html将允许在表中创建结果。我需要在下面的代码中实现html的帮助。
USE msdb
go
SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS ON
IF EXISTS (select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny = 1)
BEGIN
EXEC sp_send_dbmail @profile_name='PROFILE',
@recipients='myadres@email.com',
@query_result_header=0,
@attach_query_result_as_file=0,
@query="select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny=1 ORDER BY Kod",
@body_format='text',
@subject='warning';
END;
GO
“ MgSam”帖子Convert a SQL query result table to an HTML table for email中包含的示例实际上解决了转换为html和创建表的问题。但是,我不知道如何实现'if'条件。
根据MgSam准则,以下代码有效-但如果查询未返回数据,则发送电子邮件。
SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS ON
DECLARE @html nvarchar(MAX);
EXEC spQueryToHtmlTable @html = @html OUTPUT, @query = "select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny = 1", @orderBy = N'ORDER BY Kod';
EXEC msdb.dbo.sp_send_dbmail
@profile_name='PROFILE',
@recipients='my@email.com',
@subject = 'WARNING',
@body = @html,
@body_format = 'HTML',
@query_no_truncate = 1,
@attach_query_result_as_file = 0;
答案 0 :(得分:0)
嗯,SQL Server中的IF语句非常简单,请在此处查看: https://docs.microsoft.com/en-us/sql/t-sql/language-elements/if-else-transact-sql
根据您的示例:
SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS ON
DECLARE @html nvarchar(MAX);
EXEC spQueryToHtmlTable @html = @html OUTPUT, @query = "select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny = 1", @orderBy = N'ORDER BY Kod';
IF DATALENGTH(@html) > 0
EXEC msdb.dbo.sp_send_dbmail
@profile_name='PROFILE',
@recipients='my@email.com',
@subject = 'WARNING',
@body = @html,
@body_format = 'HTML',
@query_no_truncate = 1,
@attach_query_result_as_file = 0;
ELSE PRINT 'No results, don't email';
答案 1 :(得分:0)
我使用了 IF EXISTS 。有效的代码。
SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS ON
DECLARE @html nvarchar(MAX);
IF EXISTS (select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny = 1)
BEGIN
EXEC spQueryToHtmlTable @html = @html OUTPUT, @query = "select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny = 1", @orderBy = N'ORDER BY Kod';
EXEC msdb.dbo.sp_send_dbmail
@profile_name='PROFILE',
@recipients='my@email.com',
@subject = 'WARNING',
@body = @html,
@body_format = 'HTML',
@query_no_truncate = 1,
@attach_query_result_as_file = 0;
END;
GO