如何將sql執行的錯誤消息記錄到本地文件中實現
導讀:1建站知識sql語句的錯誤信息都可以在sys.messages表里面找到,下面與大家分享下將sql 執行的錯誤消息記錄到本地文件中,不會的seo網站優化網站建設。
其實大家都知道sql語句的錯誤信息都可以在sys.messages表里面找到
如:
如果在執行語句在try...catch中 我們可以通過以下方法獲取錯誤信息。sql語句如下:
復制代碼 代碼如下:
BEGIN TRY SELECT 3 / 0 END TRY BEGIN CATCH DECLARE @errornumber INT DECLARE @errorseverity INT DECLARE @errorstate INT DECLARE @errormessage NVARCHAR(4000) SELECT @errornumber = ERROR_NUMBER() , @errorseverity = ERROR_SEVERITY() , @errorstate = ERROR_STATE() , @errormessage = ERROR_MESSAGE() SELECT @errornumber , @errorseverity , @seo網站優化軟件errorstate , @errormessage RAISERROR ( @errormessage, -- Message text, @errorseverity, -- Severity, @errorstate, -- State, @errornumber ); END CATCH
當然我這里是故意用RAISERROR再次拋出錯誤信息,運行結果如下:現在我們來定義一個存儲過程,其目的就是往本地文件中寫入信息。
sql腳本如下:
復制代碼 代碼如下:
CREATE網seo優化趨勢 Proc [dbo].[UCreateOrAppendTextFile](@Filename VarChar(100),@Text nVarchar(4000)) AS DECLARE @FileSystem int DECLARE @FileHandle int DECLARE @RetCode int DECLARE @RetVal int DECLARE @CreateOrAppend int EXECUTE @RetCode = sp_OACreate 'Scripting.FileSystemObject' , @FileSystem OUTPUT IF (@@ERROR|@RetCode > 0 Or @FileSystem < 0) RAISERROR ('could not create FileSystemObject',16,1) EXECUTE @RetCode = sp_OAMethod @FileSystem , 'FileExists', @RetVal out, @FileName IF (@@ERROR|@RetCode > 0) RAISERROR ('could not check file existence',16,1) -- If file exists then append else create SET @CreateOrAppend = case @RetVal when 1 then 8 else 2 end EXECUTE @RetCode = sp_OAMethod @FileSystem , 'OpenTextFile' , @FileHandle OUTPUT , @Filename, @CreateOrAppend, 1 IF (@@ERROR|@RetCode > 0 Or @FileHandle < 0) RAISERROR ('could not create File',16,1) EXECUTE @RetCode = sp_OAMethod @FileHandle , 'WriteLine' , NULL , @text IF (@@ERROR|@RetCode > 0 ) RAISERROR ('could not write to File',16,1) EXECUTE @RetCode = sp_OAMethod @FileHandle , 'Close' IF (@@ERROR|@RetCode > 0) RAISERROR ('Could not close file ',16,1) EXEC sp_OADestroy @filehandle IF (@@ERROR|@RetCode > 0) RAISERROR ('Could not destroy file object',16,1) EXEC sp_OADestroy @FileSystem
----------------------------------------然后執行該存儲過程:復制代碼 代碼如下:
exec UCreateOrAppendTextFile 'C:\Error.log','hello majaing'
如果遇到以下錯誤則說明Ole Automation Procedures沒有啟用需要執行以下SQL:
復制代碼 代碼如下:
go sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'Ole Automation Procedures', 1; GO RECONFIGURE; GO
運行即如果如圖:聲明: 本文由我的SEOUC技術文章主頁發布于:2023-05-24 ,文章如何將sql執行的錯誤消息記錄到本地文件中實現主要講述如何將,錯誤,如何將sql執行的錯誤消息記錄到本地網站建設源碼以及服務器配置搭建相關技術文章。轉載請保留鏈接: http://www.bifwcx.com/article/web_6643.html