Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL DROP TYPE IF EXISTS [duplicate]

I'm currently working on a script in T-SQL in SQL Server 2014.

I need to drop a user-defined table type, but only if it exists, and create it again after the delete/drop type.

I did some research on the web and found a solution, which does, unfortunately, not work at all.

My current script looks like this:

IF OBJECT_ID('MySchema.tProjectType', 'U') IS NOT NULL
        DROP TYPE [MySchema].[tProjectType];

CREATE TYPE [MySchema].[tProjectType] AS TABLE
    (
        Id INT
        , IsPrivate BIT
        , IsPublic BIT
    );

My error message:

The type 'MySchema.tProjectType' already exists, or you do not have permission to create it.

Do you know how to successfully check if a user defined table type exists before I can delete it in SQL Server 2014?

like image 879
TimHorton Avatar asked Jul 13 '17 13:07

TimHorton


People also ask

How do you drop a type in SQL?

Remove an alias data type or user-defined type (CLR) from the current database. Syntax DROP TYPE [schema.] type [ ; ] Key type Name of the type (alias or user-defined) to be dropped.

How do I get rid of user-defined type?

You can drop a user-defined type (UDT) using the DROP statement. You cannot drop a UDT if it is used: In a column definition for an existing table or view.

What happens on drop if exist and the table does not exist?

The DROP TABLE statement deletes the specified table, and any data associated with it, from the database. The IF EXISTS clause allows the statement to succeed even if the specified tables does not exist. If the table does not exist and you do not include the IF EXISTS clause, the statement will return an error.


1 Answers

Please try this, use type_id instead of object_id

IF type_id('[MySchema].[tProjectType]') IS NOT NULL
        DROP TYPE [MySchema].[tProjectType];


CREATE TYPE [MySchema].[tProjectType] AS TABLE
    (
        Id INT
        , IsPrivate BIT
        , IsPublic BIT
    );
like image 193
Ronaldo Cano Avatar answered Sep 20 '22 18:09

Ronaldo Cano