如何將SQL執(zhí)行的錯(cuò)誤消息記錄到本地文件中
如:
如果在執(zhí)行語(yǔ)句在try...catch中,我們可以通過(guò)以下方法獲取錯(cuò)誤信息。sql語(yǔ)句如下:
BEGIN TRY SELECT @errornumber , RAISERROR ( |
當(dāng)然我這里是故意用RAISERROR再次拋出錯(cuò)誤信息,運(yùn)行結(jié)果如下:
現(xiàn)在我們來(lái)定義一個(gè)存儲(chǔ)過(guò)程,其目的就是往本地文件中寫(xiě)入信息。
sql腳本如下:
CREATE 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'
如果遇到以下錯(cuò)誤則說(shuō)明Ole Automation Procedures沒(méi)有啟用
需要執(zhí)行以下SQL:
go sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'Ole Automation Procedures', 1; GO RECONFIGURE; GO |
運(yùn)行即如果如圖:
當(dāng)然這里運(yùn)行存儲(chǔ)過(guò)程之前必須保證 文件是存在的。
最后封裝一個(gè)存儲(chǔ)過(guò)程獲取錯(cuò)誤信息,其腳本如下:
CREATE PROCEDURE LOGError(@msg nvarchar(400)) as declare @text nvarchar(400) SELECT @text=text FROM sys.messages WHERE language_id=1033 AND message_id=@@ERROR if len(@text)>1 begin set @msg=@msg +' : '+@text EXEC dbo.UCreateOrAppendTextFile 'C:\Error.log',@msg end |
執(zhí)行存儲(chǔ)過(guò)程及結(jié)果如下:
以上存儲(chǔ)過(guò)程在MSSQL2005、2012中測(cè)試通過(guò)。
這里說(shuō)說(shuō)為什么有這樣的需求吧:目前需要一個(gè)項(xiàng)目用SSIS做數(shù)據(jù)遷移,其中很大部分都是用sql語(yǔ)句實(shí)現(xiàn)的, 如 insert into ....select ... from xxxx.其中原數(shù)據(jù)庫(kù)中難免有什么臟數(shù)據(jù)導(dǎo)致插入失敗,于是我在SSIS中使用msdtc服務(wù),保證數(shù)據(jù)的一致性。雖然SSIS也有錯(cuò)誤處理,但是它只 能記錄那個(gè)sql語(yǔ)句有問(wèn)題,而不能記錄具體問(wèn)題。于是我想到把錯(cuò)誤信心記錄報(bào)數(shù)據(jù)庫(kù)表里面,可是當(dāng)遇到問(wèn)題時(shí)事務(wù)會(huì)回滾,表里面根本就沒(méi)有錯(cuò)誤信息。于 是乎 只能報(bào)錯(cuò)誤信息記錄到文件中了。
如:
有不對(duì)的地方還請(qǐng)大家拍磚哦!
posted on 2013-05-24 10:00 順其自然EVO 閱讀(216) 評(píng)論(0) 編輯 收藏 所屬分類(lèi): 數(shù)據(jù)庫(kù)