1

Let's say I have the table TEST that looks like this:

    ID  |  Value |  FK_ForeignKey
    ---------------------------
    1   |  Foo   |  3
    2   |  Bar   |  4

and another table FK:

    ID  |  Email
    -------------
    3   |  Foo@bar.com
    4   |  Bar@foo.com

I have the following code:

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'test'
, @recipients = @email
, @subject = 'test'
, @body= 'test'
, @query = @query
, @query_result_separator = ' '
, @query_result_no_padding = 1;

I need to send some values based on a FK to certain e-mail addresses.

If I give

@query = 
  'SELECT Value FROM TEST WHERE FK_ForeignKey = 3'

and run it, it correctly sends the e-mail with the results.

If I put it in a while loop and give

@query = 
  'SELECT Value FROM TEST WHERE FK_ForeignKey = @id'

with @id going from MIN(ID) to MAX(ID) of table FK, I have an error.

The error message is:

[SQLSTATE 42000] (Error 22050)  Failed to initialize sqlcmd library with error number -2147467259.

I have tried both a WHILE loop and a CURSOR and I have the same issue.

I have also tried hardcoding @email to receive multiple e-mails on a single address based on how many IDs there are in FK.

I have browsed online and seems like everyone points to security permissions but I am not running this from SQLAgent, but from the SSMS Query window.

TLDR: Sending e-mail from SQL Server works only if not in a loop.


Found the issue shortly after re-reading what I posted. I guess it paid off to write my issue. I'm embarassed how long it took me to notice this novice mistake.

@query = 
  'SELECT Value FROM TEST WHERE FK_ForeignKey = @id'

should've been

@query = 
  'SELECT Value FROM TEST WHERE FK_ForeignKey =' + CONVERT(varchar(1), @id)
AlexC
  • 15
  • 3

1 Answers1

0

I would imagine the query has a problem with @id given that you are sending a string.

You should try:

@query = 
  'SELECT Value FROM TEST WHERE FK_ForeignKey = ' + CAST(@id as varchar(5))
JMabee
  • 2,230
  • 2
  • 9
  • 13