Local variables in sp_send_dbmail?

99封情书 提交于 2019-12-23 15:09:02

问题


I'm working on an SQL stored procedure that is supposed to send an attachment with the results of a query.

I am using sp_send_dbmail to send the email.

Within the query I'd like to send, I join the to a table variable. When I executed the stored procedure, I got an error message which said that the variable didn't exist.

My code:

 DECLARE @t TABLE (
    id INT IDENTITY(1,1),
    some fields
 )

DECLARE @query VARCHAR(MAX)
SET @query =  'SELECT 
    some values
 FROM @t t
  INNER JOIN dbo.Table d ON t.field = d.field
EXEC msdb.dbo.sp_send_dbmail @recipients=@recipients_list,
        @subject = @subject,
        @query = @query,
        @attach_query_result_as_file = 1, 
        @query_result_width = 4000, 
        @query_attachment_filename = 'Details.txt'

Is there any way for me to refer to the local variable within this stored procedure? If not, why not?

TIA!

(I am using SQL Server 2005)


回答1:


The query runs in a different context than your original code body, so it is not aware of any local variables. Try using a global temp table instead.

CREATE TABLE ##t (
    id INT IDENTITY(1,1),
    some fields
 )

DECLARE @query VARCHAR(MAX)
SET @query =  'SELECT 
    some values
 FROM ##t t
  INNER JOIN dbo.Table d ON t.field = d.field'
EXEC msdb.dbo.sp_send_dbmail @recipients=@recipients_list,
        @subject = @subject,
        @query = @query,
        @attach_query_result_as_file = 1, 
        @query_result_width = 4000, 
        @query_attachment_filename = 'Details.txt'

DROP TABLE ##t


来源:https://stackoverflow.com/questions/4739682/local-variables-in-sp-send-dbmail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!