Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way to identify whether a stored procedure exists

I've historically used the following as part of a stored procedure deployment script:

IF NOT EXISTS (SELECT * FROM sys.objects O 
   WHERE O.[object_id] = OBJECT_ID(N'[dbo].[SPROC_NAME]') 
   AND OBJECTPROPERTY(O.[object_id],N'IsProcedure') = 1)

    EXEC('CREATE PROCEDURE [dbo].[SPROC_NAME] AS')
GO

ALTER PROCEDURE [dbo].[SPROC_NAME]
AS
BEGIN ...

I did not know about the overload to OBJECT_ID which takes a type for object ID lookup, for example:

OBJECT_ID(N'[dbo].[SPROC_NAME]', N'P')

It seems like using that overload would make the OBJECTPROPERTY lookup unnecessary.

I'd like to know if there is any downside to using just the OBJECT_ID overload and dropping the OBJECTPROPERTY lookup.

like image 277
C B Avatar asked Aug 26 '13 21:08

C B


People also ask

How do you find a stored procedure in a database?

Using SQL Server Management StudioExpand Databases, expand the database in which the procedure belongs, and then expand Programmability. Expand Stored Procedures, right-click the procedure and then click View Dependencies. View the list of objects that depend on the procedure.

How are stored procedures diagnosed?

The Stored Procedure Test tool (SP Test tool) makes the testing of stored procedures easier. It enables you to test various input values for a stored procedure, see the results, and optionally create test scripts without having to write COBOL code to invoke the stored procedure.

How can you tell if a stored procedure has been executed successfully?

Return Value in SQL Server Stored Procedure In default, when we execute a stored procedure in SQL Server, it returns an integer value and this value indicates the execution status of the stored procedure. The 0 value indicates, the procedure is completed successfully and the non-zero values indicate an error.


2 Answers

I prefer this form, and have stopped using the OBJECT* metadata functions as much as possible, since they can block even at loose isolation levels:

IF NOT EXISTS 
(
   SELECT 1 FROM sys.procedures AS p
     INNER JOIN sys.schemas AS s
     ON p.[schema_id] = s.[schema_id]
     WHERE p.name = N'Procedure_Name' AND s.name = N'dbo'
)
BEGIN
  EXEC sp_executesql N'CREATE PROCEDURE dbo.Procedure_Name AS';
END
like image 104
Aaron Bertrand Avatar answered Oct 18 '22 05:10

Aaron Bertrand


My prefered way is :

  if object_id('x') is not null
  begin
    drop procedure x
  end
  go
  create procedure x ...
  ...
like image 33
Mark Kremers Avatar answered Oct 18 '22 06:10

Mark Kremers