Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check existence of a sql server object and drop it?

EDIT: the function creation was missing, sorry about that

I have a T-SQL request that goes:

DECLARE @IsSomething bit
SET @IsSomething = 0
IF /some tests/ SET @IsSomething = 1
EXEC('
CREATE FUNCTION IsSomething ()
RETURNS bit
AS
BEGIN
    RETURN ' + @IsSomething + '
END')

Of course if I run it twice I get

There is already an object named 'IsSomething ' in the database. 

How would I do something like this:

IF EXIST @IsSomething DESTROY @IsSomething // (Pseudo bad code)
like image 542
marcgg Avatar asked Jul 16 '09 20:07

marcgg


People also ask

How do you drop an object in SQL Server?

A DROP statement in SQL removes a component from a relational database management system (RDBMS). Syntax: DROP object object_name Examples: DROP TABLE table_name; table_name: Name of the table to be deleted. DROP DATABASE database_name; database_name: Name of the database to be deleted.

How do you drop a database if it exists in SQL?

To remove an existing database from a SQL Server instance, you use the DROP DATABASE statement. In this syntax, you specify the name of the database that you want to drop after the DROP DATABASE keywords.


1 Answers

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id (N'[dbo].[IsSomething]') AND OBJECTPROPERTY(id, N'IsFunction') = 1) 

DROP function IsSomething
GO
like image 97
Chris McCall Avatar answered Oct 14 '22 07:10

Chris McCall