将SQL查询的结果保存到本地SQL变量中

时间:2015-11-05 13:26:51

标签: sql sql-server sql-server-2012

我的下面的代码没有按预期工作:

DECLARE @MySelect varchar(max), @MyRecipients varchar(max), @MyId 
char(4),@MyResult varchar(max);


SET @MyId = '1';
SET @MySelect = 'SELECT SQL_Script FROM AutoSendMail.dbo.A01_St WHERE 
ID =' + @MyId; 


USE msdb
EXEC sp_send_dbmail
@profile_name='Operator',
@recipients='Mail@test.com',
@subject='Mail test',
@body= 'This is a test-mail',
@mailitem_id='1',
@query= @MyResult, 
@attach_query_result_as_file = 1

我需要将选择查询的结果@MySelect保存到变量@MyResult中,因为我需要通过Mail发送SELECT的结果。但我找不到办法做到这一点。查询应返回单个字符串值。

3 个答案:

答案 0 :(得分:0)

您可以声明表变量,在其中插入执行查询的结果,然后选择结果变量:

DECLARE @t TABLE(SQL_Script varchar(max))
INSERT INTO @t EXEC(@MySelect)
SELECT TOP 1 @MyResult = SQL_Script FROM @t

您还可以使用sp_executesql过程和输出参数,例如:

SET @MyId = '1';
SET @MySelect = 'SELECT @MyResult = SQL_Script FROM AutoSendMail.dbo.A01_St WHERE 
ID =' + @MyId; 

EXEC sp_executesql @MySelect, '@MyResult varchar(max) OUTPUT', @MyResult OUTPUT

答案 1 :(得分:0)

您可以在没有动态SQL的情况下执行此操作,如下所示:

DECLARE @MyRecipients VARCHAR(MAX) ,
    @MyId CHAR(4) = '1' ,
    @MyResult VARCHAR(MAX);


SET @MyId = '1';

SELECT TOP 1
        @MyResult = SQL_Script
FROM    AutoSendMail.dbo.A01_St
WHERE   ID = @MyId


USE msdb
EXEC sp_send_dbmail @profile_name = 'Operator', @recipients = 'Mail@test.com',
    @subject = 'Mail test', @body = 'This is a test-mail', @mailitem_id = '1',
    @query = @MyResult, @attach_query_result_as_file = 1

不是说你需要动态SQL,但请注意,这样做:

SET @MySelect = 'SELECT SQL_Script FROM AutoSendMail.dbo.A01_St WHERE ID =' + @MyId; 

不执行任何代码,它只是设置@MySelect的值。您需要调用execute命令来运行SQL:

EXEC SP_EXECUTESQL @MySelect

答案 2 :(得分:0)

这个怎么样?

select  @MyResult = stuff((
                           select  ',' + convert(nvarchar(20), SQL_Script)
                           from    AutoSendMail.dbo.A01_St
                           where   ID = @MyId
                           for
                           xml path('')
                           ), 1, 1, '')

这会输出逗号分隔的字符串