使用 sp_send_dbmail 发送附件时出现错误无法初始化

Sending attachment with sp_send_dbmail getting error Failed to initialize sqlcmd library with error number -2147467259(使用 sp_send_dbmail 发送附件时出现错误无法初始化 sqlcmd 库,错误号为 -2147467259)
本文介绍了使用 sp_send_dbmail 发送附件时出现错误无法初始化 sqlcmd 库,错误号为 -2147467259的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码测试在 SQL 中发送附件.我收到错误 - 无法初始化 sqlcmd 库,错误号为 -2147467259.发送电子邮件工作正常,只有在添加 @query 时我才开始收到此错误.我错过了什么?

I am trying to test sending an attachment in SQL with the code below. I get an error -Failed to initialize sqlcmd library with error number -2147467259. Sending emails works just fine, only when adding the @query do I start getting this error. What am I missing?

DECLARE @query nvarchar(max) = 'select top (1) * from employees';
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Email',
@recipients = 'me@gmail.com',
@query = @query,                     
@query_attachment_filename = 'employees.csv',      
@body_format = 'HTML',
@subject = 'Test';

推荐答案

使用 @query 参数为 sp_send_dbmail 运行的查询在 msdb 的上下文中运行.这意味着对于您的查询,您实际上是在尝试引用对象 msdb.dbo.employees.该对象不太可能存在于 msdb 中,因为它是一个系统数据库(如果存在,我建议移动它),并且由于该对象不存在,查询无法解析并且 sp_send_dbmail 生成错误.

Queries run using the @query parameter for sp_send_dbmail are run in the context of msdb. This means that for your query, you are effectively trying to reference an object msdb.dbo.employees. This object is unlikely to exist in msdb, as it is a system database (and if it does, I would suggest moving it), and as the object doesn't exist the query fails to parse and sp_send_dbmail generates an error.

要解决此问题,请在为 @query 参数定义的查询中使用 3 部分命名:

To fix the problem, use 3 part naming in the query you define for the @query parameter:

DECLARE @query nvarchar(MAX) = N'SELECT TOP (1) * FROM YOurDatabase.dbo.employees ORDER BY YourColumn;'; --Replace values as needed
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Email',
@recipients = 'me@gmail.com',
@query = @query,                     
@query_attachment_filename = 'employees.csv',      
@body_format = 'HTML',
@subject = 'Test';

这篇关于使用 sp_send_dbmail 发送附件时出现错误无法初始化 sqlcmd 库,错误号为 -2147467259的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)