On error resume next for Microsoft SQL, when using sp_MSforeachtable?
I am making a script that deletes all tables before recreating them with the Entity Framewor开发者_JS百科k. I did this by implementing an IDatabaseInitializer that does this for me.
However, as you may have guessed, when trying to delete a table that has a foreign key constraint, it fails misserably, and the whole script terminates.
How can I prevent this? Here's how I am dropping the tables.
context.Database.ExecuteSqlCommand("EXEC sp_MSforeachtable @command1 = \"DROP TABLE ?\"");
Now, I put this into a while-loop that keeps executing until all tables are removed. However, since this command deletes all tables in order, and fails when the first table can't be removed, this script is not working.
Is there any way to make Microsoft SQL Server ignore any errors, and resume table deletion with the next entry instead?
No
You have to use some kind of SQL script to iterate several times to deal with several levels of FKs.
DECLARE @retry bit = 1
WHILE @retry = 1
BEGIN
BEGIN TRY
EXEC sp_MSforeachtable @command1 = 'DROP TABLE ?'
SET @retry = 0
END TRY
BEGIN CATCH
SET @retry = 1
END CATCH
END
Note: dropping all tables isn't typically something you'd do in client code. Not least, it requires higher privileges to modify objects
Another way would be drop FKs first by querying sys.objects: Drop all foreign keys in a table then do your DROP TABLEs
A final point: use single quotes not double quotes in SQL because of SET QUOTED_IDENTIFIER
精彩评论