SQL Server:通过电子邮件发送动态SQL查询的结果

时间:2015-10-06 12:08:58

标签: sql-server sql-server-2008-r2

我正在尝试使用游标构建一个循环,以便向具有此类延迟服务器的客户端发送延迟订单列表。

光标的WHILE循环是正常的,我正确地获取当前的@idClient@email,但我不知道如何在{{上过滤查询1}}。

这是我到目前为止所做的(非工作)陈述:

@idClient

我的问题是:我应该如何制定exec msdb..sp_send_dbmail @profile_name='sql_mail_lu', @recipients = @email, @subject = 'Your backorders', @body = 'Please find in attachment the list of your items in backorder.', @execute_query_database = 'ERPSQL', @query = ' SELECT TOP 100 NoDoc, Refer Product, Comm Ordered, isnull(Livr, 0) Delivered, BackOrder, VRef FROM erpSQL.dbo.vwBoClients WHERE idclient = ' + @idClient' , @attach_query_result_as_file = 1, @query_attachment_filename ='backorders.txt' 部分才能使其发挥作用?

1 个答案:

答案 0 :(得分:0)

你需要逃避这些单引号:

exec msdb..sp_send_dbmail @profile_name='sql_mail_lu',
                    @recipients=@email,
                    @subject='Your backorders',
                    @body= 'Please find in attachment the list of your items in backorder.',
                    @execute_query_database = 'ERPSQL', 
                    @query = '
                              SELECT TOP 100
                              NoDoc, Refer Product, Comm Ordered, isnull(Livr, 0) Delivered, BackOrder, VRef
                              FROM   erpSQL.dbo.vwBoClients
                              WHERE  idclient = ''' + @idClient + ''' ,
                    @attach_query_result_as_file = 1, 
                    @query_attachment_filename =''backorders.txt'''