I want to write a stored procedure to send an e-mail when the select count(*)
value is bigger than the value Menge
.
This stored procedure should be used flexible due the params for more tables and/or "where criteria"
Unfortunately I get this error and I am 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.
Can you help me?
My stored procedure:
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 stored procedure via ADO conenct in VBA