How to check existence of user-define table type in SQL Server 2008?

e0uiprwp  于 2023-06-04  发布在  SQL Server
关注(0)|答案(5)|浏览(175)

I have a user-defined table type. I want to check it's existence before editing in a patch using OBJECT_ID(name, type) function.

What type from the enumeration should be passed for user-defined table types?

N'U' like for user defined table doesn't work, i.e. IF OBJECT_ID(N'MyType', N'U') IS NOT NULL

bwntbbo3

bwntbbo31#

You can look in sys.types or use TYPE_ID:

IF TYPE_ID(N'MyType') IS NULL ...

Just a precaution: using type_id won't verify that the type is a table type--just that a type by that name exists. Otherwise gbn's query is probably better.

ffvjumwh

ffvjumwh2#

IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'MyType')
    --stuff

sys.types ... they aren't in sys.objects under their normal name

Update, Mar 2013

You can use TYPE_ID too

i5desfxk

i5desfxk3#

IF EXISTS(SELECT 1 FROM sys.types WHERE name = 'Person' AND is_table_type = 1 AND schema_id = SCHEMA_ID('VAB'))
DROP TYPE VAB.Person;
go
CREATE TYPE VAB.Person AS TABLE
(    PersonID               INT
    ,FirstName              VARCHAR(255)
    ,MiddleName             VARCHAR(255)
    ,LastName               VARCHAR(255)
    ,PreferredName          VARCHAR(255)
);
nwsw7zdq

nwsw7zdq4#

Following examples work for me, please note "is_user_defined" NOT "is_table_type"

IF TYPE_ID(N'idType') IS NULL
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go

IF not EXISTS (SELECT * FROM sys.types WHERE is_user_defined = 1 AND name = 'idType')
CREATE TYPE [dbo].[idType] FROM Bigint NOT NULL
go
hgc7kmma

hgc7kmma5#

You can use also system table_types view

IF EXISTS (SELECT *
           FROM   [sys].[table_types]
           WHERE  user_type_id = Type_id(N'[dbo].[UdTableType]'))
  BEGIN
      PRINT 'EXISTS'
  END

相关问题