我想用两个SELECTS做一个UNION并放在一个表中

时间:2015-03-03 07:44:48

标签: sql sql-server select union

到目前为止,我有这个代码,我想让他们联合成一个问题,但我无法让它工作。我一直在努力做一个新的选择围绕演员和一切到As Nvarchar。

DECLARE @tableHTML NVARCHAR(MAX);
SET @tableHTML = 
N'<H3>Felaktiga rader</H3>'+
N'<table border="1">'+
N'<tr><th>ID</th>'+
N'<th>Value</th>'+
N'<th>Reason</th>'+

CAST ((SELECT td=ID,'',
td = Value,'',
td = Reason,''

FROM Mail.dbo.CheckMe
WHERE Value = '120' OR Value = '220'
UNION
Mail.dbo.CheckMeTwo
WHERE Value = '120' OR Value = '220'

for XML path ('tr'), TYPE
) as NVARCHAR(MAX))+
N'</table>';

EXEC msdb.dbo.sp_send_dbmail
@recipients = 'ZZXXYY@gmail.com;',
@subject = ' Felaktiga Rader',
@body = @tableHTML,
@body_format = 'HTML';

2 个答案:

答案 0 :(得分:0)

您忘了在第二个查询中选择列!!!!

SELECT td=ID,'',td = Value,'', td = Reason,''
FROM Mail.dbo.CheckMe
WHERE Value = '120' OR Value = '220'
UNION
SELECT td=ID,'',td = Value,'', td = Reason,''
FROM Mail.dbo.CheckMeTwo
WHERE Value = '120' OR Value = '220'

您需要在UNION构造中为每个查询选择一个列表!

答案 1 :(得分:0)

我这样解决了。

FROM (SELECT * FROM Mail.dbo.CheckMe
WHERE Value = '120' OR Value = '220'
UNION
SELECT * FROM Mail.dbo.CheckMeTwo
WHERE Value = '120' OR Value = '220') T