0
votes

When I try to run below query(Sql Server) I get exception saying

ExecuteSqlScriptwithTransaction: failed with exception ALTER DATABASE statement not allowed within multi-statement transaction.

DECLARE @sql nvarchar(500)

IF((SELECT (size * 8 /1024.0)*1000 FROM sys.database_files df WHERE df.name like 'Test') < 9000000)  
   BEGIN    
      SET @sql = 'ALTER DATABASE Test MODIFY FILE ( NAME = N''Test'', SIZE = 10000000KB );'
      EXEC (@sql)          
  END 

GO

Tried like below but same error

DECLARE @sql nvarchar(500)

IF((SELECT (size * 8 /1024.0)*1000 FROM sys.database_files df WHERE df.name like 'Test') < 9000000)
BEGIN
ALTER DATABASE Test MODIFY FILE ( NAME = N'Test', SIZE = 10000000KB )
END

GO
1
Is your script larger then this snippit? maybe you have a transaction and this is inside it? - Brad
@Brad That is the complete script...I have not added any transaction...I am not good in Sql so I am not sure if I have to add transaction here... - reddy
No, it was a thought because it is not clear on the question that was just a thought based on your error. I think the answer below may work for you/ - Brad
You've got an ambient transaction open somewhere. 'rollback transaction' before you execute it or open a new Connection. - StuartLC

1 Answers

2
votes

The ExecuteSqlScriptwithTransaction method named in the title suggests the code executes the script in a transaction. The ALTER DATABASE documentation specifically states:

The ALTER DATABASE statement must run in autocommit mode (the default transaction management mode) and is not allowed in an explicit or implicit transaction.

So the solution is to execute the script using a different method, one without an explict transaction.