将参数传递给动态SQL

时间:2017-07-12 20:01:15

标签: sql sql-server

我正在尝试将一些参数传递给通过动态SQL调用的存储过程,如下所示:

CREATE PROCEDURE someProc
    @StartDate datetime,
    @EndDate datetime
AS
    DECLARE @qry varchar(max) = 'EXEC otherProc @StartDate, @EndDate'

    EXEC msdb.dbo.sp_send_dbmail 
         @recipients = 'test@domain.com',    
         @subject = 'Test',
         @query = @qry,
         @attach_query_result_as_file = 1,
         @query_attachment_filename = 'result.csv',
         @query_result_separator = '    ',
         @query_result_no_padding = 1,
         @query_result_width = 32767

但是当我运行它时,我收到错误

  

必须声明标量变量" @ StartDate"

如何更改查询以使其生效?

1 个答案:

答案 0 :(得分:1)

只是按字面意思写出来?试试这样:

DECLARE @StartDate datetime='20170101';
DECLARE @EndDate datetime=GETDATE();


DECLARE @qry varchar(max) = 'EXEC otherProc {ts''' 
                           + REPLACE(CONVERT(VARCHAR(19),@StartDate,126),'T',' ')  
                           + '''}, {ts''' 
                           + REPLACE(CONVERT(VARCHAR(19),@EndDate,126),'T',' ')  + '''}';

SELECT @qry;

结果:

EXEC otherProc {ts'2017-01-01 00:00:00'}, {ts'2017-07-12 22:20:39'}