Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3240682
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T18:06:46+00:00 2026-05-17T18:06:46+00:00

I have a SQL Statement that works as I want. select COUNT(*), MIN(emailed_to)from email.email_archive

  • 0

I have a SQL Statement that works as I want.

select COUNT(*), MIN(emailed_to)from email.email_archive
group by emailed_to
order by COUNT(*) desc

The output looks like this.

13   deadlockIE12388nnhy32@hepmeplease.com;
8   deadlockIE1277yhygt@hepmeplease.com;
4   deadlockFF17uyt9xx967@hepmeplease.com;
...
...
...
1       deadlockFF17uytsdfa7@hepmeplease.com;

This is simple enough, but then I would have to remember to run the select every day and make sure things are ok. I want to have the stored procedure email me once in a while and I can decide if I have an issue. So I have hacked together the following from many resources:

use MYDB;
go
IF SCHEMA_ID('monitors') IS NULL EXECUTE('CREATE SCHEMA monitors AUTHORIZATION dbo')
GO
if object_id('monitors.email_abuse') is null
 exec('create procedure monitors.email_abuse as print ''stub'' return');
GO
alter procedure monitors.email_abuse
    (@to    varchar(max) = 'itops@hepmeplease.com',
     @sendemail tinyint = 1)
as
set nocount on ;
set transaction isolation level read uncommitted ;
begin try
declare     @errmsg     varchar(max) = '',
        @subject    nvarchar(255);
select @subject = 'Run Away Email Monitor';
select @errmsg = REPLICATE(char(10),1)+
        '# of Emails'+
         REPLICATE(char(9),1)+
         'Email Address'+
         REPLICATE(CHAR(10),1); 
select @errmsg = @errmsg +REPLICATE(char(9),1)+
    CAST(COUNT(*) as CHAR(10))+
    REPLICATE(char(9),1)+ 
    CAST(MIN(emailed_to) as CHAR(45))
from 
    email.email_archive
group by 
    emailed_to
order by 
    COUNT(*) desc;
print @errmsg;
    if @sendemail = 1
    begin
        exec master.dbo.sp_email 
            @to = @to,
            @subject = @subject,
            @body = @errmsg;
    end
end try
begin catch
    -- unexpected errors
    exec sp_raise_error @rethrow = 1, @textdata = N'Error in monitors.email_abuse', @emailTo = N'itops@hepmeplease.com'
    end catch
go

But it then emails me the following output that is just one line. I know that there are many lines but for some reason when I put the COUNT(*), MIN(emailed_to) into the CAST statement this no longer works. I get a email that has the header and one line. If I just print the output of @errmsg I exactly what I get in the email, the header and the one line. just like below.

# of Emails  Email Address
    1           y@y.com;

I am not sure what I am doing wrong with my cast statement.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T18:06:47+00:00Added an answer on May 17, 2026 at 6:06 pm

    Explanation:

    My guess is that the code you are actually using is slightly different from the code you have posted here because when I take your code and the following data in a test database, things work out fine.

    create table email_archive
    (
        id int,
        emailed_to nvarchar(255)
    )
    
    insert into email_archive values
        ( 1, 'one@helpme.com'), ( 2, 'two@helpme.com'), ( 3, 'three@helpme.com'),
        ( 4, 'four@helpme.com'), ( 5, 'one@helpme.com'), ( 6, 'two@helpme.com'),
        ( 7, 'three@helpme.com'), ( 8, 'four@helpme.com'), ( 9, 'one@helpme.com'),
        (10, 'two@helpme.com'), (11, 'three@helpme.com'), (12, 'four@helpme.com'),
        (13, 'one@helpme.com'), (14, 'two@helpme.com'), (15, 'three@helpme.com'),
        (16, 'four@helpme.com'), (17, 'one@helpme.com'), (18, 'one@helpme.com'),
        (19, 'one@helpme.com'), (20, 'three@helpme.com'), (21, 'three@helpme.com')
    

    I am thinking you may have hit upon an issue discussed here: http://bit.ly/cMlnjt

    Since I can’t be sure I offer you two alternative solutions that will definitely get the job done, even though as others have mentioned this aggregate concatenation should work without an issue.

    Alternatives:

    To get what you are looking for, I prefer one of the following two options

    1) Just make sp_send_dbmail do the work for you.

    2) Go with a cursor solution

    Option 1:

    EXEC msdb..sp_send_dbmail    @profile_name = 'MyMailProfile', 
                            @recipients = 'my_email@domain.com',
                            @subject = 'Runaway Email Monitor',
                            @body = 'Runaway emails found',
                            @query = 'SELECT COUNT(*), emailed_to FROM mydb.dbo.email_archive GROUP BY emailed_to HAVING COUNT(*) > 5 ORDER BY COUNT(*) DESC'
    

    Note: The having clause makes this only display rows where the count is greater than 5.

    Option 2:

    USE test
    
    IF EXISTS ( SELECT name FROM test.sys.sysobjects WHERE type = 'P' AND name = 'usp_MonitorEmails' )
    BEGIN
        DROP PROCEDURE dbo.usp_MonitorEmails
    END
    GO
    
    CREATE PROCEDURE usp_MonitorEmails
        @Subject nvarchar(255) = '',
        @Importance varchar(6) = 'NORMAL',
        @Sensitivity varchar(12) = 'NORMAL',
        @Recipients varchar(MAX) = NULL,
        @MinimumCount int = 0
    AS
    BEGIN
        SET NOCOUNT ON
    
        IF UPPER(@Importance) NOT IN ('LOW', 'NORMAL', 'HIGH') SET @Importance = 'NORMAL'
        IF UPPER(@Sensitivity) NOT IN ('NORMAL', 'PERSONAL', 'PRIVATE', 'CONFIDENTIAL') SET @Sensitivity = 'NORMAL'
    
    
        DECLARE @run bit,
                @message nvarchar(MAX)
    
        SELECT  @run = 0,
                @subject =  'Run Away Email Monitor',
                @message =  'Run away emails found' + CHAR(13)+CHAR(10) + 
                            'Count        Email Address' + CHAR(13)+CHAR(10) + 
                            '-----------  ------------------------------------------------------------------------------' + CHAR(13)+CHAR(10)
        DECLARE @count int, 
                @email nvarchar(255)
        DECLARE BodyCursor CURSOR STATIC FOR
            SELECT COUNT(*), emailed_to FROM email_archive GROUP BY emailed_to HAVING COUNT(*) > @MinimumCount ORDER BY COUNT(*) DESC
        OPEN BodyCursor
        FETCH NEXT FROM BodyCursor
            INTO @count, @email
    
        WHILE @@FETCH_STATUS = 0
        BEGIN
            SELECT @message = @message + REPLICATE(N' ', 11-LEN(CAST(@count AS nvarchar(22)))) + CAST(@count AS nvarchar(22)) + '  ' + @email + CHAR(13)+CHAR(10), @run = 1
    
            FETCH NEXT FROM BodyCursor
                INTO @count, @email
        END
        CLOSE BodyCursor
        DEALLOCATE BodyCursor
    
        IF @run = 1 AND LEN(@Recipients) > 0
        BEGIN
            EXEC msdb..sp_send_dbmail   @profile_name = 'MyMailProfile', 
                                        @recipients = @Recipients,
                                        @subject = @Subject,
                                        @body = @Message,
                                        @body_format = 'TEXT',
                                        @importance = @Importance,
                                        @sensitivity = @Sensitivity
        END
    END
    
    GO
    

    Note: I prefer this method because of the flexibility I have in the way the messages are formatted. This will also only send the email if there are rows returned where the minimum count is reached.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some SQL that does an order by case statement. It works fine.
I have a SQL statement that looks like: SELECT [Phone] FROM [Table] WHERE (
I have a long running SQL statement that I want to run, and no
i have sql statement like this SELECT DISTINCT results_sp_08.material_number FROM results_sp_08 INNER JOIN courses
I have a SQL statement similar to this: SELECT COUNT(*) AS foo, SUM(foo) AS
I have the following SQL-statement: SELECT DISTINCT name FROM log WHERE NOT name =
Let's say I have an SQL statement that's syntactically and semantically correct so it
I have an annoying SQL statement that seem simple but it looks awfull. I
I sometimes need to see what SQL statement SubSonic generates. That works great with:
I have a SQL statement, in ColdFusion, and I want to limit the size

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.