I’d like to write a stored procedure and store it in a SQL Server database. The procedure is supposed to remove all tables regardless of dependency constraints.
CREATE PROCEDURE sp_clear_db AS
BEGIN
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL';
EXEC sp_MSForEachTable 'DROP TABLE ?';
END
However, when I call sp_helptext @objname = 'dbo.sp_clear_db', only the first exec statement is shown. I assume in order to execute the first function, a GO has to be called. But a GO as part of the stored procedure definition won’t work either. Does anyone know a way to fix this? Maybe there is another better option to achieve the same…
Cheers,
Max
You can’t have “GO” in a stored procedure. (http://msdn.microsoft.com/en-us/library/ms188037.aspx) GO is used by SQL Query analyser to separate statements into “Batches” which are then sent to SQL server. So you’d need to make two separate calls, one for the ALTER calls and one for the DROP.
Ideally you would just call “DROP DATABASE” unless you were trying to keep your stored procs and then re-create the tables.
Another solution would be to use a cursor to loop through each row in sys.tables where type=’U’ and generate some dynamic sql to remove the contraints and drop the table.