• sqlrd22 (10/15/2012)


    Abu Dina (10/15/2012)


    Okay so something like the below might work for you:

    IF (select count(*) from [e009]) > 0

    begin

    exec msdb.dbo.sp_send_dbmail

    @profile_name = 'Default',

    @recipients = 'me@example.com',

    @subject = 'warning',

    @query = 'select * from [e009]',

    @attach_query_result_as_file = 1,

    @query_attachment_filename = 'warning.csv'

    end

    Thanks, this will be hard to test as I have no control over whether the data comes in or not as it is sent into our database by an external source and this type of data only comes in when there is something wrong (hence the name warning) but I'll try it out.

    There's a small tweek that I'd make to that. As written above, both the COUNT(*) and the @query each make a table scan of the e009 table (or view). While I do understand that there's usually nothing in the table/view and that it runs only twice a day and there's not much in the table/view when it actually contains something, there's no need for any extra reads/cpu time on the system if you can avoid them. It also helps folks that look for code for their particular different problem.

    With that thought in mind, if you change the IF in Abu Dina's good code to just check for the presence of at least 1 row, you accomplish the same thing but with fewer reads/cpu time.

    IF EXISTS(SELECT TOP 1 1 FROM [e009])

    begin

    exec msdb.dbo.sp_send_dbmail

    @profile_name = 'Default',

    @recipients = 'me@example.com',

    @subject = 'warning',

    @query = 'select * from [e009]',

    @attach_query_result_as_file = 1,

    @query_attachment_filename = 'warning.csv'

    end

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)