如何从查询结果中构建Sp_send_dbmail附件字符串

时间:2015-10-05 20:01:43

标签: sql sql-server do-while sp-send-dbmail

我需要为查询中的每个结果附加一个文件,可能是单个结果可能是10.使用Microsoft SQL Server 2012。

示例:select ItemNumber from table where column_x=22:

结果:

  

125487,

     

25645124

Declare @path nvarchar(255);
Set @path = 'C:\Users\Public\Documents\'

Declare @attachment nvarchar(255);
  Set @attachment = @path + result1 + '.txt' + ',' + @path + result2 + '.txt'

1 个答案:

答案 0 :(得分:-1)

CREATE Procedure [dbo].[GetItems]
@TransNumber INT,
 @attachment nvarchar(MAX)  OUTPUT
AS 

 Begin

 DECLARE @path nvarchar(255);
 SET @path = 'C:\Users\Public\Documents\WineCards\';
 set @attachment = ''


 SELECT @attachment += CONCAT(';', @path, 'wn', ItemLookupcode, '.pdf')
 FROM TransactionEntry
 Left Join Item on TransactionEntry.ItemID = Item.ID
 WHERE TransactionEntry.TransactionNumber=@TransNumber and         dbo.fn_FileExists(CONCAT(@path, 'wn', ItemLookupcode, '.pdf') )=1
 Group by Itemlookupcode

选择@attachment = STUFF(@attachment,1,1,''); - 删除初始“;”

结束