gpt4 book ai didi

sql-server - 从作业执行 sp_send_dbmail 失败,查询结果作为文件附加

转载 作者:行者123 更新时间:2023-12-03 06:22:13 25 4
gpt4 key购买 nike

我遇到了以下问题:当尝试发送带有作为文件附加的查询结果的电子邮件时,通过执行普通查询使用 sp_send_dbmail 一切似乎都工作正常。

但是如果将相同的代码添加到 JobStep 并运行作业,则会失败。

作业历史记录中有错误

Error formatting query, probably invalid parameters [SQLSTATE 42000] (Error 22050). The step failed.

但是当我注释掉引用文件附加的参数时,它再次开始正常工作。

exec msdb.dbo.sp_send_dbmail 
@profile_name = 'profile_name',
@recipients = 'some@mail.com',
@body = 'body',
@subject = 'subj',
--Parameters that refers to attached file
@attach_query_result_as_file = 1,
@query_result_header = 0,
@query_result_no_padding = 1,
@query = 'select 1',
@query_attachment_filename = 'test.csv'

有什么建议吗?

最佳答案

我已经解决了这个问题。不知道为什么它会起作用,但无论如何。 :)这绝对与安全有关。

我调查了 SQL 代理正在代表域用户运行,例如 DOMAIN\User。它拥有服务器上的全套管理权限(“sysadmin”服务器角色等)。 SQL Server 本身在同一用户下运行。

包含调用sp_send_dbmail的作业步骤在同一DOMAIN\User下运行。

我还发现,当运行 sp_send_dbmail 的查询部分时,它会尝试执行exec xp_logininfo 'DOMAIN\User' 根据 Active Directory 检查该用户是否正常。令人惊讶的是:有些事情绝对不对劲。此检查最终结果为:

Msg 15404, Level 16, State 19, Server SQLC002INS02\SQLC002INS02, Line 1
Could not obtain information about Windows NT group/user 'DOMAIN\User.', error code 0x2.

这在一定程度上可能意味着该用户的密码已过期或用户被锁定或任何其他对该人来说不愉快的事情。

我认为更改代理用户是有风险的。因此,我开始代表“sa”发送邮件,该“sa”具有相同的“sysadmin”服务器角色,但具有 SQL 授权,并省略了此 AD 检查步骤。

看起来就像一个用户冒充管理员要求真正的管理员为他运行危险代码:)

因此,这项工作的最终代码是第一步,也是唯一的一步,如下所示:

execute as login = 'sa'
exec msdb.dbo.sp_send_dbmail
@profile_name = 'profile_name',
@recipients = 'some@mail.com',
@body = 'body',
@subject = 'subj',
--Parameters that refers to attached file
@attach_query_result_as_file = 1,
@query_result_header = 0,
@query_result_no_padding = 1,
@query = 'select 1',
@query_attachment_filename = 'test.csv'
revert

关于sql-server - 从作业执行 sp_send_dbmail 失败,查询结果作为文件附加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15112849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com