mercredi 8 juin 2016

exec stored procedure with flexible parameter for "select count(*)..." and sending an eMail

i want to write a SP to send an eMail when the select count(*) value is bigger then the value "Menge" This SP should be used fleixble due the Params for more Tables and/or "where criteria"

Unfortunately i get this erorr and iam not able to fix it :(

Msg 245, Level 16, State 1, Procedure sp_eMail_Test3, Line 23 Conversion failed when converting the varchar value 'select count(*) from test where not [sys_completed] is null' to data type int. Blockquote

Can you help me?

My SP:

create PROCEDURE [dbo].[sp_eMail_Test3]
 @recordCount as int = 0, 
 @FileN as varchar(max) =null,
 @DatSubj as varchar(20) =null,
 @DatFile as varchar(20) =null,
 @SQL_Count as varchar(max) =null,

 @MySQL as varchar(max)=null,
 @MyTable as varchar(max)=null,
 @MyWhere as varchar(max)=null,

 @Menge as int = 0,

 @eMail_TO varchar(max) =null,
 @eMail_Subject varchar(max) =null,
 @eMail_Body varchar(max) =null

AS
BEGIN
    SET NOCOUNT ON;     
    set @MySQL = 'select count(*) from ' +@MyTable + ' where ' + @MyWhere 
    set @SQL_Count = @MySQL 
    set @recordCount = convert(int, @SQL_Count ) -- <<--this is the error

    IF (@recordCount > @Menge)  
    begin           
        -- variablen zuweisung
        set @DatSubj =  CONVERT(varCHAR(20),  GETDATE() ,120) --datum fürs subject
        set @DatFile =  replace(convert(varchar, getdate(), 120), ':','_') --datum für filename
        set @FileN ='Eska_Report_' + @DatFile +'.csv' --filename

        EXEC msdb.dbo.sp_send_dbmail
            @body_format = 'HTML',
            @profile_name = 'testmailprofile',
            @recipients = @eMail_TO,         
            @subject =  @eMail_Subject ,
            @Body = @eMail_Body  ,
            @query = 'SET NOCOUNT ON;
                        select * from Test where sys_gueltig = ''Y'' 
                        and not sys_completed is null  ',
         @attach_query_result_as_file = 1       , 
         @query_attachment_filename= @FileN     , 
         @query_result_separator = ';'      ,
         @query_result_no_padding= 1,       
         @exclude_query_output =1,      
         @append_query_error = 1,   
         @query_result_header =1
    end    
END

I call the SP in this way

exec sp_eMail_Test3
    @Menge = 0,
    @eMail_TO = 'testuser@test.xx' ,
    @eMail_Subject = 'test3 ',
    @eMail_Body = 'Hallo, das ist ein Test',
    @MyTable ='test'    ,
    @MyWhere = 'not [sys_completed] is null'

In the future i want to call the SP via ADO conenct in VBA

Aucun commentaire:

Enregistrer un commentaire