How to check existence of a sql server object and drop it?
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[IsSomething]') AND OBJECTPROPERTY(id, N'IsFunction') = 1)
DROP function IsSomething
GO
The answer to your edited question is:
if object_id('IsSomething', 'fn') is not null drop function IsSomething
go
The template, from Visual Studio 2008 Add -> Stored Procedure Script
is
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'Stored_Procedure_Name')
BEGIN
DROP Procedure Stored_Procedure_Name
END
GO
CREATE Procedure Stored_Procedure_Name
/*
(
@parameter1 int = 5,
@parameter2 datatype OUTPUT
)
*/
AS
GO
/*
GRANT EXEC ON Stored_Procedure_Name TO PUBLIC
GO
*/
For a Procedure, Sql Server Management Studio gives the following script to drop
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_DeleteXyz]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[usp_DeleteXyz]
likewise for a Function it's generated script is
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[udf_GetXyz]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[udf_GetXyz]
I've mostly seen the latter forms (2-line versions) in most codebases I've worked on, and there's no need to declare a variable.