/*============================================================================
  File:     ShowRollingBack.sql

  Summary:  This script shows transactions rolling
			back when CHECKDB runs

  SQL Server Versions: 2005 onwards
------------------------------------------------------------------------------
  Written by Paul S. Randal, SQLskills.com

  (c) 2016, SQLskills.com. All rights reserved.

  For more scripts and sample code, check out 
    http://www.SQLskills.com

  You may alter this code for your own *non-commercial* purposes. You may
  republish altered code as long as you include this copyright and give due
  credit, but you must obtain prior permission before blogging this code.
  
  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
  ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
  TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
  PARTICULAR PURPOSE.
============================================================================*/

USE [master];
GO

IF DATABASEPROPERTYEX (N'Company_Snapshot', N'Version') > 0
BEGIN
	DROP DATABASE [Company_Snapshot];
END
GO
IF DATABASEPROPERTYEX (N'Company', N'Version') > 0
BEGIN
	ALTER DATABASE [Company] SET SINGLE_USER
		WITH ROLLBACK IMMEDIATE;
	DROP DATABASE [Company];
END
GO

-- Create a database
CREATE DATABASE [Company];
GO

USE [Company];
GO

CREATE TABLE [t1] ([c1] int);
GO

EXEC sp_cycle_errorlog;
GO

BEGIN TRAN
INSERT INTO [t1] VALUES (1);
GO

-- In other window, CHECKDB the database

EXEC xp_readerrorlog;
GO

-- In other window, create a snapshot

EXEC xp_readerrorlog;
GO

-- What are the database IDs? In the messages...
SELECT [name], [database_id] FROM sys.databases
WHERE [name] LIKE N'company%';
GO

-- Clean up
ROLLBACK TRAN;
GO

-- What snapshots exist?
SELECT * FROM sys.databases
WHERE [source_database_id] IS NOT NULL;
GO

-- Cleanup
IF DATABASEPROPERTYEX (N'Company_Snapshot', N'Version') > 0
BEGIN
	DROP DATABASE [Company_Snapshot];
END
GO