Sunday, February 26, 2012

exit from script

I need to exit from a script after checking some conditions . for example I need to check if a store procedure does not exist make it other wise go exit . I try following code but became an error

if exists(select ..... )

create store procedure ...

<<error becomes>>

or

if exists(select .... ) return

go

create store procedure .....

go

<<both command runs>>

Moved to T-SQL forum.

|||

A good way to check before creation is something like this: Note: RETURN in not required.

The CREATE PROCEDURE code will execute after the PROCEDURE has been deleted.

Code Snippet


IF EXISTS
( SELECT name
FROM sys.Procedures
WHERE name = 'MyProcedureName'
)
DROP PROCEDURE dbo.MyProcedureName
GO


CREATE PROCEDURE dbo.MyProcedureName
( @.Parameters etc )
AS
...


GO

|||

Unfortunately you can't do it here.Create procedure script should not be batched on IF statement.

As per the specification Create Procedure/Function/Trigger/View should be the first statement of your query

The best approach is,

Code Snippet

IF EXISTS (Procedure)

Drop Procedure ...

go

Create Proc ....

|||

If you use GO on your batch you can't stop it. You can only return / stop the current query (which is enclosed by GO).. When you return or use goto, it will automatically fetch the next script..

So always check the object is available, if available drop it & recreate it.

No comments:

Post a Comment