I am looking for a way to prevent execution of bad DDL from making an entire transaction uncommitable. The simplest use case I can provide is:
DECLARE @SQL NVARCHAR(MAX);
BEGIN TRANSACTION
Print 'In Transaction'
BEGIN TRY
PRINT 'In Try.'
SET @SQL = N'CREATE VIEW DeleteMe AS SELECT 1 AS ABC';
EXEC (@SQL);
END TRY
BEGIN CATCH
PRINT 'In catch. Error = '+ERROR_MESSAGE()+' XACT_STATE = ' + CAST(XACT_STATE() AS VARCHAR);
END CATCH;
PRINT 'XACT_STATE prior to outer commit: ' + CAST(XACT_STATE() AS VARCHAR);
COMMIT;
Expected results (with no exceptions thrown) are:
In Transaction
In Try.
XACT_STATE prior to outer commit: 1
Of course we know that dynamic execution of DDL can cause an uncommitable transaction.
However it seems that there must be a way to parse, explain or otherwise validate the SQL before executing it causes an uncommitable transaction.
Who has ideas that can meet the expected results without throwing an exception?