| 
 | 
								
									
										|  |  
										|  |  
										| | This procedure reads the SQL Server error log using sp_readerrorlog and imports the error log's contents into a specified table. It accepts three parameters: 
 @log_name is the name of the table into which the error log will be imported
 @log_number is the error log number, 0 is default and refers to current error log
 @overwrite -- specify 1 for this parameter, so that the target table could be overwritten, if it already exists
 
 Read the comments section inside the procedure for examples.
 | 
 |  Click here to copy the following block |  | CREATE PROC sp_import_errorlog (
 @log_name sysname,
 @log_number int = 0,
 @overwrite bit = 0
 )
 AS
 
 
 BEGIN
 SET NOCOUNT ON
 
 DECLARE @sql varchar(500)
 
 IF (SELECT OBJECT_ID(@log_name,'U')) IS NOT NULL
 BEGIN
 IF @overwrite = 0
 BEGIN
 RAISERROR('Table already exists. Specify another name or pass 1 to @overwrite parameter',18,1)
 RETURN -1
 END
 ELSE
 BEGIN
 EXEC('DROP TABLE ' + @log_name)
 END
 END
 
 
 
 CREATE TABLE #errlog
 (
 err varchar(1000),
 controw tinyint
 )
 
 
 INSERT #errlog
 EXEC sp_readerrorlog @log_number
 
 
 SET ROWCOUNT 4
 DELETE #errlog
 SET ROWCOUNT 0
 
 
 SET @sql =    'SELECT
 CONVERT(DATETIME,LEFT(err,23)) [Date],
 SUBSTRING(err,24,10) [spid],
 RIGHT(err,LEN(err) - 33) [Message],
 controw
 INTO ' + QUOTENAME(@log_name) +
 ' FROM #errlog ' +
 'WHERE controw = 0'
 
 
 EXEC (@sql)
 
 
 DROP TABLE #errlog
 
 SET NOCOUNT OFF
 PRINT 'Error log successfully imported to table: ' + @log_name
 END
 | 
 |  
										|  |  
										|  |  
 
	
		| Submitted By :
					Nayan Patel 
					 (Member Since : 5/26/2004 12:23:06 PM) |  
		|  |  
		| 
				 | Job Description :   
			He is the moderator of this site and  currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |  
		| View all (893) submissions by this author 
			(Birth Date : 7/14/1981 ) |  |  |