我有有效的查询:
SELECT TOP (1000) [dashboard_name]
,[dashboard_path]
,[UserName]
,[timestamp]
,(SELECT TOP(1) DATEDIFF(day, timestamp, GETDATE()) FROM [Monitoring].[dbo].[Temporary_logins_log] t WHERE t.dashboard_name = dashboard_name AND t.dashboard_path = dashboard_path AND t.UserName = UserName) AS [Age]
FROM [Monitoring].[dbo].[Temporary_logins_log] where timestamp = CONVERT(VARCHAR(10), getdate(), 111)
我想使用以下方式通过邮件发送结果:
DECLARE @tableHTML NVARCHAR(MAX) ;
SET @tableHTML =
N'<H1>Header</H1>' +
N'<table border="1">' +
N'<tr><th>Report Name</th><th>Report Path</th>' +
N'<th>LoginName</th><th>Date</th><th>Age (days)</th></tr>' +
CAST ( ( SELECT td = t.dashboard_name, '',
td = t.dashboard_path, '',
td = t.UserName, '',
td = t.timestamp, '',
td = (SELECT TOP(1) DATEDIFF(day, l.timestamp, GETDATE()) FROM [Monitoring].[dbo].[Temporary_logins_log] l WHERE t.dashboard_name = l.dashboard_name AND t.dashboard_path = l.dashboard_path AND t.UserName = l.UserName) AS [Age], ''
FROM [Monitoring].[dbo].[Temporary_logins_log] t where timestamp = CONVERT(VARCHAR(10), getdate(), 111)
FOR XML PATH('tr'), TYPE
) AS NVARCHAR(MAX) ) + N'</table>' ;
EXEC msdb.dbo.sp_send_dbmail @recipients='name@work.com',
@subject = 'SQL Report',
@body = @tableHTML,
@body_format = 'HTML' ;
但是我在关键字AS 附近收到语法错误。是否可以使用此代码发送子查询结果,或者我必须重新处理它以使其自身与表联接,而无需使用子查询?
答案 0 :(得分:1)
查询中的这一行没有意义:
td = (SELECT TOP(1) DATEDIFF(day, l.timestamp, GETDATE())
FROM [Monitoring].[dbo].[Temporary_logins_log] l
WHERE t.dashboard_name = l.dashboard_name AND
t.dashboard_path = l.dashboard_path AND
t.UserName = l.UserName
) AS [Age], ''
您是否希望列别名为td
或[Age]
?我猜是td
。如果是这样,请删除as [Age]
。