呼叫sp_send_mail時出現Msg 22050和Msg 14661錯誤

hexiaomail發表於2010-06-09

環境:SQL Server 9.0.4053
使用域帳號mydomain\hex登入,利用msdb.dbo.sp_send_dbmail傳送郵件,在使用其中的@query引數後就出現錯誤。
USE msdb
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Myprofile',
    @recipients = 'MyprofileMail@mydomain.com',
    @query = 'select DriveLetter,MB_Free,Status from dbo.DrvSpace',
    @subject = 'MYSER55\SQL2005 Last Backup Report',
    @attach_query_result_as_file = 1 ;
GO
-------------------------------------------
Msg 22050, Level 16, State 1, Line 0
Error formatting query, probably invalid parameters
Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 495
Query execution failed: Msg 15404, Level 16, State 19, Server FIHSER55\SQL2005, Line 1
Could not obtain information about Windows NT group/user 'mydomain\hex', error code 0x5.

Msg 22050, Level 16, State 1, Line 0
Error formatting query, probably invalid parameters
Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 495
Query execution failed: Msg 208, Level 16, State 1, Server MYSER55\SQL2005, Line 1
Invalid object name 'dbo.DrvSpace'.

注:
[ @query = ] 'query' 表示要執行的查詢。 查詢結果可以作為檔案附加,或包含在電子郵件的正文中。 查詢的型別為 nvarchar(max),並且可以包含任何有效的 Transact-SQL 語句。

分析:
在進行一般性傳送郵件都正常,而用上@query查詢功能並做為一個附件就會出錯,錯誤資訊顯示不能得到域帳號的資訊。

通用切換SQL Server帳號test登入執行:
USE msdb
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Myprofile',
    @recipients = 'MyprofileMail@mydomain.com',
    @query = 'select DriveLetter,MB_Free,Status from dbo.DrvSpace',
    @subject = 'MYSER55\SQL2005 Last Backup Report',
    @attach_query_result_as_file = 1 ;
GO
--------------------------------------------------------------------------------------
Msg 22050, Level 16, State 1, Line 0
Error formatting query, probably invalid parameters
Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 495
Query execution failed: Msg 15406, Level 16, State 1, Server MYSER55\SQL2005, Line 1
Cannot execute as the server principal because the principal "test" does not exist, this type of principal cannot be impersonated, or you do not have permission.
是由於沒有伺服器許可權的問題,為什麼還要server principal?

檢視SQL Server服務啟動的帳號為:MYSER55\SQL1,它應該是具有SERVER系統的許可權。
將MYSER55\SQL1帳號加入到msdb資料庫中,並以MYSER55\SQL1做為登入帳號:
USE msdb
EXECUTE AS LOGIN = 'MYSER55\SQL1'
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Myprofile',
    @recipients = 'MyprofileMail@mydomain.com',
    @query = 'select DriveLetter,MB_Free,Status from dbo.DrvSpace',
    @subject = 'MYSER55\SQL2005 Last Backup Report',
    @attach_query_result_as_file = 1 ;
GO
---------------------------------------------------------------------
mail quene.

郵件傳送成功!

如果使上述郵件傳送成功,需要具有Windows 系統相關的許可權.
驗證Windows使用者和 Windows 組的資訊
EXEC sys.xp_logininfo @acctname = 'MYSER55\SQL1'
------------------------------------------------
Command(s) completed successfully.

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9932141/viewspace-664801/,如需轉載,請註明出處,否則將追究法律責任。

相關文章