views:

105

answers:

2

I'm working on versioning our database and now searching for a way to drop all stored procedures and functions from a C# Console Application. I'd rather not create a stored procedure that drops all stored procedures and functions. I has to be some sql executed from C#.

I tried to drop the stored procedure before creating it, but I get this message:

System.Data.SqlClient.SqlException: 'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.

Script for one SP for example:

DROP PROCEDURE [dbo].[sp_Economatic_LoadJournalEntryFeedbackByData]
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE PROCEDURE [dbo].[sp_Economatic_LoadJournalEntryFeedbackByData]
    @Data VARCHAR(MAX)
AS
BEGIN
    ...
END

So I guess before creating all SP's and functions I'll need to drop all SP's and functions first with one sql script.

A: 

you need to put "GO" between each statement block. Please see: http://msdn.microsoft.com/en-us/library/ms188037.aspx

so your above code would become:

DROP PROCEDURE [dbo].[sp_Economatic_LoadJournalEntryFeedbackByData]

-- this makes it execute the above statement, before continuing.
GO

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

CREATE PROCEDURE [dbo].[sp_Economatic_LoadJournalEntryFeedbackByData]
@Data VARCHAR(MAX)

AS
  BEGIN
    ...
  END
alex
If you're executing sql from C#, then GO gives an error.
Lieven Cardoen
it depends how you are executing the SQL.... if you are using the SqlCommand object then it will.You really should be doing this kind of operation in a stored procedure.
alex
+1  A: 

You can check for existence before dropping:

IF EXISTS (SELECT * FROM [dbo].[sysobjects]
           WHERE ID = object_id(N'[dbo].[YourProcName]') AND 
                 OBJECTPROPERTY(id, N'IsProcedure') = 1)
    DROP PROCEDURE [dbo].[YourProcName]
GO

... then create it...

I would add this for each stored procedure you want to create.

Cătălin Pitiș
I'm with you this is the way to go, if you drop all procs and the recreate them, then the users are dead in the water until the process is substantially done. This way each proc is only down for a millisecond or so.
HLGEM
Actually, Murphy doesn't sleep :). It might be that this stored procedure will be called exactly between dropping and creating. I would recommend to perform such DDL manipulations when the database is offline or used as less as possible.
Cătălin Pitiș
Well, that's not really the problem, although it could become one. This solution will still not work from C# (executing sql text). You'll get the same error saying CREATE/ALTER PROCEDURE ...
Lieven Cardoen