0

If I have a user table type (like CREATE TYPE ...), how do I get to it's definition in the system tables?

I know I can see it through SSMS through GUI, but I would like to have a query to retrieve it from system tables.

I don't see it through any of the modules:

SELECT 
      * 
FROM 
      sys.all_sql_modules m 
WHERE 
      m.definition like 'CREATE TYPE %' --doesn't output any types definitions

1 Answer 1

2

You need to query sys.table_types:

SELECT
    SchemaName = SCHEMA_NAME(TYPE.schema_id),
    TypeName = TYPE.name,
    ColumnID = COL.column_id,
    [Column] = COL.name,
    DataType = ST.name,
    IsNullable = COL.Is_Nullable,
    Length = COL.max_length,
    Precision = COL.[precision],
    Scale = COL.scale,
    Collation = ST.collation
FROM 
    sys.table_types TYPE
    INNER JOIN sys.columns COL ON TYPE.type_table_object_id = COL.object_id
    INNER JOIN sys.systypes AS ST ON ST.xtype = COL.system_type_id
WHERE
    TYPE.is_user_defined = 1
ORDER BY 
    SchemaName,
    TypeName,
    ColumnID

Make sure you are connected to the proper database.

If you want a CREATE TYPE statement like the one from SSMS, you will have to build it from the results of the previous query. That or trace the SSMS's query to see how it builds it when you ask it from the GUI, but there's a chance it's very convoluted (although bulletproof).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.