数据库邮件TXT附件显示问题
用数据库邮件功能把查询结果作为附件发送时,查询结果会按照表结构的从长度生成TXT文件的格式,致使附件显示走形 。这种情况该如何解决?
[解决办法]
因原字段定义过长,例如varchar(100)的实际只存几个字符,但结果显示时仍然会占用100的长度..
导致这种显示效果.
建议修改查询语句,如
select cast([字段名] as varchar([实际长度])) as '[字段名]', ... from ...
[解决办法]
如果要用html的话我这里倒有个例子:
DECLARE @tableHTML NVARCHAR(MAX) ;
DECLARE @date SMALLDATETIME
SET @date = CONVERT(CHAR(10), GETDATE(), 120)
DECLARE @title NVARCHAR(64)
SELECT @title = CONVERT(CHAR(10), GETDATE(), 120) + ' Jobs Report '
DECLARE @DBA NVARCHAR(1024)
SET @DBA = 'XXX@XXX.com;XXX@139.com'
SET @tableHTML = N'<H1>Jobs Report</H1>' + N'<table border="1">'
+ N'<tr><th>作业名</th><th>最近执行时间</th>'
+ N'<th>最近执行状态</th><th>运行持续时间</th><th>最近运行状态信息</th>'
+ N'<th>下次运行时间</th></tr>'
+ CAST(( SELECT td = [sJOB].[name] ,
'' ,
td = CASE WHEN ( [sJOBH].[run_date] IS NULL
OR [sJOBH].[run_time] IS NULL
) THEN NULL
ELSE CAST(CAST([sJOBH].[run_date] AS CHAR(8))
+ ' ' + STUFF(STUFF(RIGHT('000000'
+ CAST([sJOBH].[run_time] AS VARCHAR(6)),
6), 3, 0, ':'), 6,
0, ':') AS DATETIME)
END ,
'' ,
td = CASE [sJOBH].[run_status]
WHEN 0 THEN N'失败'
WHEN 1 THEN N'成功'
WHEN 2 THEN N'重试'
WHEN 3 THEN N'取消'
WHEN 4 THEN N'正在运行' -- In Progress
END ,
'' ,
td = STUFF(STUFF(RIGHT('000000'
+ CAST([sJOBH].[run_duration] AS VARCHAR(6)),
6), 3, 0, ':'), 6, 0, ':') ,
'' ,
td=[sJOBH].[message] ,
'' ,
td = CASE [sJOBSCH].[NextRunDate]
WHEN 0 THEN NULL
ELSE CAST(CAST([sJOBSCH].[NextRunDate] AS CHAR(8))
+ ' ' + STUFF(STUFF(RIGHT('000000'
+ CAST([sJOBSCH].[NextRunTime] AS VARCHAR(6)),
6), 3, 0, ':'), 6, 0,
':') AS DATETIME)
END,''
FROM [msdb].[dbo].[sysjobs] AS [sJOB]
LEFT JOIN ( SELECT [job_id] ,
MIN([next_run_date]) AS [NextRunDate] ,
MIN([next_run_time]) AS [NextRunTime]
FROM [msdb].[dbo].[sysjobschedules]
GROUP BY [job_id]
) AS [sJOBSCH] ON [sJOB].[job_id] = [sJOBSCH].[job_id]
LEFT JOIN ( SELECT [job_id] ,
[run_date] ,
[run_time] ,
[run_status] ,
[run_duration] ,
[message] ,
ROW_NUMBER() OVER ( PARTITION BY [job_id] ORDER BY [run_date] DESC, [run_time] DESC ) AS RowNumber
FROM [msdb].[dbo].[sysjobhistory]
WHERE [step_id] = 0
) AS [sJOBH] ON [sJOB].[job_id] = [sJOBH].[job_id]
AND [sJOBH].[RowNumber] = 1
ORDER BY [sJOBH].[run_status] ,[sJOB].[name]
FOR
XML PATH('tr') ,
TYPE
) AS NVARCHAR(MAX)) + N'</table>'
EXEC msdb.dbo.sp_send_dbmail @recipients = @DBA, @subject = @title,
@body = @tableHTML, @body_format = 'HTML' ;