0

我正在设置查询以通过电子邮件发送结果,但结果格式不正确。

我想从表 1 中某个字段为空的两个表中选择值,并从表 2 中添加一个相关字段,其中表 1 id = 表 2 id。但也包括表 1 中可能不在表 2 中但某些字段为空的字段。

 DECLARE @TITLE NVARCHAR(MAX)
 DECLARE @BODY NVARCHAR(MAX)

 SET @TITLE =CAST(( SELECT DISTINCT A.CUSTKEY as 'td','',
 B.CUSTPROJ as 'td','',   A.ITEMS AS 'td','', A.SOLDDATE as 'td','',
 A.LASTORDEREDDATE as 'td','', A.OBJID as 'td'
 FROM PRODUCTDATA AS A LEFT OUTER JOIN CLIENT_TABLE as B
 on A.CUSTkey = B.CUSTkey 
 WHERE LASTORDEREDDATE IS NULL GROUP BY A.CUSTKEY,B.CUSTPROJ, 
 A.ITEMS, A.SOLDDATE, A.OBJID,A.LASTORDEREDDATE
 FOR XML PATH ('tr'), ELEMENTS) AS NVARCHAR(MAX))

 SET @BODY = '<html><body><H4>NEW CLIENT PURCHASES</H4>
 <table border = 2>
 <tr>
 <th> CUST KEY </th> <th> CLIENT NAME </th> <th> NEW PURCHASES </th>
 <th> SOLD DATE </th> <th> ORDERED DATE </th> <th> PRODUCT ID </th></tr>'

 SET @BODY = @BODY + @TITLE + '</TABLE></BODY></HTML>'

EXEC msdb.dbo.sp_send_dbmail @profile_name='DB Admin',
@body =   @BODY,
@body_format = 'HTML';

但它显示如下:

NEW CLIENT PURCHASES
CUSTkEY CLIENT NAME NEW PURCHASES    SOLD DATE      ORDERED DATE PRODUCT ID 
9189ad  PHOEBE       LDS              20130107T12:15:00    NULL         BGD01 
8765ad  MONICA       PANTS            20130107T12:15:00    NULL         BGD01 
3421ad  JOEY         BAG              20130107T12:15:00    NULL         BGD01 
2354ad  RACHEL       HAT              20130107T12:15:00    NULL         BGD01   
7653ef  SHOES     20121213T06:15:00                                     hfd00       

如您所见,最后一行恰好是表 1 中的一行,其中客户端不存在于客户端表 2 中,因此该行应如下所示:

  CUSTkEY   CLIENT NAME NEW PURCHASES    SOLD DATE       ORDERED DATE    PRODUCT ID 

   7653ef                  SHOES       20121213T06:15:00   NULL             hfd00
4

1 回答 1

1

当您有多个具有相同名称的列时,要包含空标签,您必须将每列包装到其自己的 XML 生成器中,如下所示:

SELECT 
 (SELECT (SELECT n1) FOR XML PATH('td'),TYPE),
 (SELECT (SELECT n2) FOR XML PATH('td'),TYPE), 
 (SELECT (SELECT n3) FOR XML PATH('td'),TYPE)
FROM (VALUES(NULL,NULL,1))x(n1,n2,n3)
FOR XML PATH('tr'), ELEMENTS 
于 2013-01-08T22:19:29.710 回答