Technical Article

INSERTS that will STAY after a ROLLBACK is issued

,

Sometimes it is usefull to log stuff in SQL server while stored procs are running. If a long stored proc runs you sometimes want to be able to log a message in a loggin file. But what if a rollback occurs.... The message is lost as well.

Here is a method to set up a seperate connection to SQL inside TSQL and log those messages......

Had a discussion a while ago about this but this solution never popped up.....

Run this script and be amazed.........

SET NOCOUNT ON
USE [MASTER]
GO

-- CHECK IF OBJECT ALREADY EXISTS
IF OBJECT_ID('LOGGING_FILE') > 0 
BEGIN
SELECT 'TSQL FAILED BEFORE TABLE WAS NOT DROPPED. DROPPING TABLE .........'
DROP TABLE LOGGING_FILE
END
GO

-- RECREATE THE TABLE FOR THE LOGGING FUNCTION
CREATE TABLE LOGGING_FILE
(
ID TIMESTAMP,
MESSAGE VARCHAR(500)
)
GO

DECLARE @SQLSERVER INTEGER
DECLARE @DATABASE INTEGER
DECLARE @RESULTS INTEGER
DECLARE @SQL  VARCHAR(8000)
DECLARE @ERROR  INTEGER
DECLARE @ERRORMSG VARCHAR(255)
DECLARE @COUNTER INTEGER 
DECLARE @LOGGEDMESSAGE AS VARCHAR(100)

-- CREATE THE SQLSERVER OBJECT
SET @COUNTER = 1
EXEC @ERROR = SP_OACREATE 'SQLDMO.SQLSERVER', @SQLSERVER OUT
EXEC @ERROR = SP_OAMETHOD @SQLSERVER,"CONNECT", NULL, ".", "SA","SA"
EXEC @ERROR = SP_OAGETPROPERTY @SQLSERVER, 'DATABASES("MASTER")', @DATABASE OUT

-- BEGIN THE TRANSACTION
BEGIN TRAN

-- DO A LOOP OF 1000
WHILE @COUNTER <= 1000
BEGIN 
SET @LOGGEDMESSAGE = 'INSERT LOGGING_FILE (MESSAGE) VALUES ( ''LOGGED MESSAGE FROM INSIDE TRANSACTION ' + STR(@COUNTER)+ CHAR(39)+')'

-- INSERT A RECORD THAT WON'T ROLL BACK 
EXEC @ERROR = SP_OAMETHOD @DATABASE,'EXECUTEWITHRESULTSANDMESSAGES', 
@RESULTS OUTPUT, 
@COMMAND = @LOGGEDMESSAGE,

@MESSAGES = @ERRORMSG OUTPUT

-- INSERT A RECORD THAT WILL ROLL BACK

INSERT LOGGING_FILE (MESSAGE) VALUES ('NON LOGGED MESSAGE FROM INSIDE TRANSACTION '+ STR(@COUNTER))
SET @COUNTER = @COUNTER + 1
END

-- SELECT THE COMPLETE RESULTSET 
SELECT * FROM LOGGING_FILE ORDER BY ID
-- ROLLBACK THE TRANSACTION
ROLLBACK TRAN
-- SELECT THE RECORD THAT WERE NOT ROLLED BACK......

SELECT * FROM LOGGING_FILE ORDER BY ID

-- DESTROY THE SQL SERVER OBJECT
EXEC @ERROR = SP_OADESTROY @SQLSERVER
EXEC @ERROR = SP_OADESTROY @DATABASE
EXEC @ERROR = SP_OADESTROY @RESULTS

-- DROP THE LOGGING TABLE 
DROP TABLE LOGGING_FILE

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating