I have more SQL scripts (each for different version of the application) and I want to execute all scripts in one transaction.
I’m executing it from c# using:
ExecuteNonQuery(command, conn, trans)
on SqlCommand.
The SQL commands in the scripts are separated by GO separators. My C# code iterates through all scripts and creates collection of the SqlCommand based on the GO separator. The GO separator is excluded from SqlCommand execution. It is just a separator in script file.
All was working fine, but I have found one problem. I have in one script the following command:
ALTER TABLE [dbo].[RoleDataPermissions] WITH NOCHECK ADD CONSTRAINT
[FK_RoleDataPermissions_OrganizationUnits] FOREIGN KEY([OrganizationUnitID])
REFERENCES [OrganizationUnits] ([ID])
and in the another script (in another version of app this constraint was deleted) I have:
ALTER TABLE [dbo].[RoleDataPermissions]
DROP CONSTRAINT FK_RoleDataPermissions_OrganizationUnits
The first command passed fine, but the second one throws the exception:
‘FK_RoleDataPermissions_OrganizationUnits’ is not a constraint. Could not drop constraint. See previous errors.
I’m trying find out what is causing this problem. I think, that the problem is, that if all commands are executed under one transaction, so the first command is not committed and then the second one cannot find this constraint. I have tried also change the isolation level to readuncommited, but it doesn’t help.
Do you have any idea how to deal with this?
thanks
Your analysis is not correct as a transaction can see it’s own uncommitted data. This is easily demonstrated as below.
The syntax you have posted is invalid however so quite likely the constraint isn’t being created due to the syntax error and for some reason the exception isn’t being reported in your application. Or (if your actual syntax is correct) maybe you are dropping the constraint twice.