Get sql text of a UDT - sql-server

When creating a function or a trigger, you can find its creation command in sys.sql_modules
But what i cannot seem to find is the same for UDTs.
When I create a type like this
CREATE TYPE dbo.UserIds AS TABLE (value int NOT NULL PRIMARY KEY);
it doesnt show up in sys.sql_modules.
The only information I can find is from sys.types
select * from sys.types where is_user_defined = 1
but there is no SQL statement. So where do i find it?

You could get info about table type and columns from metadata:
CREATE TYPE dbo.UserIds AS TABLE (value int NOT NULL PRIMARY KEY);
--
DECLARE #name SYSNAME = 'UserIds';
SELECT sch = SCHEMA_NAME(t.schema_id)
,t.name
,type = TYPE_NAME(t.user_type_id)
,c.name
,col_type = TYPE_NAME(c.user_type_id)
,c.is_nullable
--.... more info about max_length (if text) and so on
FROM sys.table_types t
JOIN sys.columns c
ON t.type_table_object_id = c.object_id
WHERE t.name = #name;
Based on that info you could recreate DDL statement.
EDIT:
If you want to script it the easiest way is to use SSMS.
Right-click -> Script object as (same for simple types).

It's not so simple to get a type definition, you can prove it to yourself ly launching Profiler and asking SSMS to generate a script as CREATE for your type.
Here is what I've got:
exec sp_executesql N'SELECT
SCHEMA_NAME(tt.schema_id) AS [Schema],
tt.name AS [Name]
FROM
sys.table_types AS tt
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
WHERE
(tt.name=#_msparam_0 and SCHEMA_NAME(tt.schema_id)=#_msparam_1)',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000)',#_msparam_0=N'YourType',#_msparam_1=N'dbo'
exec sp_executesql N'SELECT
clmns.column_id AS [ID],
clmns.name AS [Name]
FROM
sys.table_types AS tt
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
INNER JOIN sys.all_columns AS clmns ON clmns.object_id=tt.type_table_object_id
WHERE
(tt.name=#_msparam_0 and SCHEMA_NAME(tt.schema_id)=#_msparam_1)
ORDER BY
[ID] ASC',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000)',#_msparam_0=N'YourType',#_msparam_1=N'dbo'
exec sp_executesql N'SELECT
p.name AS [Name]
FROM
sys.table_types AS tt
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
INNER JOIN sys.all_columns AS clmns ON clmns.object_id=tt.type_table_object_id
INNER JOIN sys.extended_properties AS p ON p.major_id=tt.user_type_id AND p.minor_id=clmns.column_id AND p.class=8
WHERE
(clmns.name=#_msparam_0)and((tt.name=#_msparam_1 and SCHEMA_NAME(tt.schema_id)=#_msparam_2))
ORDER BY
[Name] ASC',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000),#_msparam_2 nvarchar(4000)',#_msparam_0=N'id_banca',#_msparam_1=N'YourType',#_msparam_2=N'dbo'
exec sp_executesql N'SELECT
p.name AS [Name]
FROM
sys.table_types AS tt
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
INNER JOIN sys.extended_properties AS p ON p.major_id=tt.user_type_id AND p.minor_id=0 AND p.class=6
WHERE
(tt.name=#_msparam_0 and SCHEMA_NAME(tt.schema_id)=#_msparam_1)
ORDER BY
[Name] ASC',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000)',#_msparam_0=N'YourType',#_msparam_1=N'dbo'
exec sp_executesql N'SELECT
cstr.name AS [Name]
FROM
sys.table_types AS tt
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
INNER JOIN sys.check_constraints AS cstr ON cstr.parent_object_id=tt.type_table_object_id
WHERE
(tt.name=#_msparam_0 and SCHEMA_NAME(tt.schema_id)=#_msparam_1)
ORDER BY
[Name] ASC',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000)',#_msparam_0=N'YourType',#_msparam_1=N'dbo'
exec sp_executesql N'SELECT
ISNULL(s1tt.name, N'''') AS [Owner],
CAST(case when tt.principal_id is null then 1 else 0 end AS bit) AS [IsSchemaOwned],
tt.name AS [Name],
tt.type_table_object_id AS [ID],
SCHEMA_NAME(tt.schema_id) AS [Schema],
obj.create_date AS [CreateDate],
obj.modify_date AS [DateLastModified],
tt.max_length AS [MaxLength],
tt.is_nullable AS [Nullable],
ISNULL(tt.collation_name, N'''') AS [Collation],
CAST(case when tt.is_user_defined = 1 then 1 else 0 end AS bit) AS [IsUserDefined]
FROM
sys.table_types AS tt
LEFT OUTER JOIN sys.database_principals AS s1tt ON s1tt.principal_id = ISNULL(tt.principal_id, (TYPEPROPERTY(QUOTENAME(SCHEMA_NAME(tt.schema_id)) + ''.'' + QUOTENAME(tt.name), ''OwnerId'')))
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
LEFT OUTER JOIN sys.objects AS obj ON obj.object_id = tt.type_table_object_id
WHERE
(tt.name=#_msparam_0 and SCHEMA_NAME(tt.schema_id)=#_msparam_1)',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000)',#_msparam_0=N'YourType',#_msparam_1=N'dbo'
exec sp_executesql N'SELECT
clmns.name AS [Name],
clmns.column_id AS [ID],
clmns.is_nullable AS [Nullable],
clmns.is_computed AS [Computed],
CAST(ISNULL(cik.index_column_id, 0) AS bit) AS [InPrimaryKey],
clmns.is_ansi_padded AS [AnsiPaddingStatus],
CAST(clmns.is_rowguidcol AS bit) AS [RowGuidCol],
CAST(ISNULL(COLUMNPROPERTY(clmns.object_id, clmns.name, N''IsDeterministic''),0) AS bit) AS [IsDeterministic],
CAST(ISNULL(COLUMNPROPERTY(clmns.object_id, clmns.name, N''IsPrecise''),0) AS bit) AS [IsPrecise],
CAST(ISNULL(cc.is_persisted, 0) AS bit) AS [IsPersisted],
ISNULL(clmns.collation_name, N'''') AS [Collation],
CAST(ISNULL((select TOP 1 1 from sys.foreign_key_columns AS colfk where colfk.parent_column_id = clmns.column_id and colfk.parent_object_id = clmns.object_id), 0) AS bit) AS [IsForeignKey],
clmns.is_identity AS [Identity],
CAST(ISNULL(ic.seed_value,0) AS bigint) AS [IdentitySeed],
CAST(ISNULL(ic.increment_value,0) AS bigint) AS [IdentityIncrement],
(case when clmns.default_object_id = 0 then N'''' when d.parent_object_id > 0 then N'''' else d.name end) AS [Default],
(case when clmns.default_object_id = 0 then N'''' when d.parent_object_id > 0 then N'''' else schema_name(d.schema_id) end) AS [DefaultSchema],
(case when clmns.rule_object_id = 0 then N'''' else r.name end) AS [Rule],
(case when clmns.rule_object_id = 0 then N'''' else schema_name(r.schema_id) end) AS [RuleSchema],
ISNULL(ic.is_not_for_replication, 0) AS [NotForReplication],
CAST(COLUMNPROPERTY(clmns.object_id, clmns.name, N''IsFulltextIndexed'') AS bit) AS [IsFullTextIndexed],
CAST(COLUMNPROPERTY(clmns.object_id, clmns.name, N''StatisticalSemantics'') AS int) AS [StatisticalSemantics],
CAST(clmns.is_filestream AS bit) AS [IsFileStream],
CAST(clmns.is_sparse AS bit) AS [IsSparse],
CAST(clmns.is_column_set AS bit) AS [IsColumnSet],
usrt.name AS [DataType],
s1clmns.name AS [DataTypeSchema],
ISNULL(baset.name, N'''') AS [SystemType],
CAST(CASE WHEN baset.name IN (N''nchar'', N''nvarchar'') AND clmns.max_length <> -1 THEN clmns.max_length/2 ELSE clmns.max_length END AS int) AS [Length],
CAST(clmns.precision AS int) AS [NumericPrecision],
CAST(clmns.scale AS int) AS [NumericScale],
ISNULL(xscclmns.name, N'''') AS [XmlSchemaNamespace],
ISNULL(s2clmns.name, N'''') AS [XmlSchemaNamespaceSchema],
ISNULL( (case clmns.is_xml_document when 1 then 2 else 1 end), 0) AS [XmlDocumentConstraint],
CASE WHEN usrt.is_table_type = 1 THEN N''structured'' ELSE N'''' END AS [UserType]
FROM
sys.table_types AS tt
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
INNER JOIN sys.all_columns AS clmns ON clmns.object_id=tt.type_table_object_id
LEFT OUTER JOIN sys.indexes AS ik ON ik.object_id = clmns.object_id and 1=ik.is_primary_key
LEFT OUTER JOIN sys.index_columns AS cik ON cik.index_id = ik.index_id and cik.column_id = clmns.column_id and cik.object_id = clmns.object_id and 0 = cik.is_included_column
LEFT OUTER JOIN sys.computed_columns AS cc ON cc.object_id = clmns.object_id and cc.column_id = clmns.column_id
LEFT OUTER JOIN sys.identity_columns AS ic ON ic.object_id = clmns.object_id and ic.column_id = clmns.column_id
LEFT OUTER JOIN sys.objects AS d ON d.object_id = clmns.default_object_id
LEFT OUTER JOIN sys.objects AS r ON r.object_id = clmns.rule_object_id
LEFT OUTER JOIN sys.types AS usrt ON usrt.user_type_id = clmns.user_type_id
LEFT OUTER JOIN sys.schemas AS s1clmns ON s1clmns.schema_id = usrt.schema_id
LEFT OUTER JOIN sys.types AS baset ON (baset.user_type_id = clmns.system_type_id and baset.user_type_id = baset.system_type_id) or ((baset.system_type_id = clmns.system_type_id) and (baset.user_type_id = clmns.user_type_id) and (baset.is_user_defined = 0) and (baset.is_assembly_type = 1))
LEFT OUTER JOIN sys.xml_schema_collections AS xscclmns ON xscclmns.xml_collection_id = clmns.xml_collection_id
LEFT OUTER JOIN sys.schemas AS s2clmns ON s2clmns.schema_id = xscclmns.schema_id
WHERE
(clmns.name=#_msparam_0)and((tt.name=#_msparam_1 and SCHEMA_NAME(tt.schema_id)=#_msparam_2))',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000),#_msparam_2 nvarchar(4000)',#_msparam_0=N'id_banca',#_msparam_1=N'YourType',#_msparam_2=N'dbo'
exec sp_executesql N'SELECT
cstr.name AS [Name]
FROM
sys.table_types AS tt
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
INNER JOIN sys.all_columns AS clmns ON clmns.object_id=tt.type_table_object_id
INNER JOIN sys.default_constraints AS cstr ON cstr.object_id=clmns.default_object_id
WHERE
(clmns.name=#_msparam_0)and((tt.name=#_msparam_1 and SCHEMA_NAME(tt.schema_id)=#_msparam_2))
ORDER BY
[Name] ASC',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000),#_msparam_2 nvarchar(4000)',#_msparam_0=N'id_banca',#_msparam_1=N'YourType',#_msparam_2=N'dbo'
exec sp_executesql N'SELECT
i.name AS [Name],
CAST(i.index_id AS int) AS [ID],
CAST(OBJECTPROPERTY(i.object_id,N''IsMSShipped'') AS bit) AS [IsSystemObject],
ISNULL(s.no_recompute,0) AS [NoAutomaticRecomputation],
i.fill_factor AS [FillFactor],
CAST(CASE i.index_id WHEN 1 THEN 1 ELSE 0 END AS bit) AS [IsClustered],
i.is_primary_key + 2*i.is_unique_constraint AS [IndexKeyType],
i.is_unique AS [IsUnique],
i.ignore_dup_key AS [IgnoreDuplicateKeys],
~i.allow_row_locks AS [DisallowRowLocks],
~i.allow_page_locks AS [DisallowPageLocks],
CAST(ISNULL(INDEXPROPERTY(i.object_id, i.name, N''IsPadIndex''), 0) AS bit) AS [PadIndex],
i.is_disabled AS [IsDisabled],
CAST(ISNULL(k.is_system_named, 0) AS bit) AS [IsSystemNamed],
CAST(INDEXPROPERTY(i.object_id,i.name,N''IsFulltextKey'') AS bit) AS [IsFullTextKey],
CAST(case when i.type=3 then 1 else 0 end AS bit) AS [IsXmlIndex],
case UPPER(ISNULL(xi.secondary_type,'''')) when ''P'' then 1 when ''V'' then 2 when ''R'' then 3 else 0 end AS [SecondaryXmlIndexType],
ISNULL(xi2.name, N'''') AS [ParentXmlIndex],
CAST(ISNULL(spi.spatial_index_type,0) AS tinyint) AS [SpatialIndexType],
CAST(ISNULL(si.bounding_box_xmin,0) AS float(53)) AS [BoundingBoxXMin],
CAST(ISNULL(si.bounding_box_ymin,0) AS float(53)) AS [BoundingBoxYMin],
CAST(ISNULL(si.bounding_box_xmax,0) AS float(53)) AS [BoundingBoxXMax],
CAST(ISNULL(si.bounding_box_ymax,0) AS float(53)) AS [BoundingBoxYMax],
CAST(ISNULL(si.level_1_grid,0) AS smallint) AS [Level1Grid],
CAST(ISNULL(si.level_2_grid,0) AS smallint) AS [Level2Grid],
CAST(ISNULL(si.level_3_grid,0) AS smallint) AS [Level3Grid],
CAST(ISNULL(si.level_4_grid,0) AS smallint) AS [Level4Grid],
CAST(ISNULL(si.cells_per_object,0) AS int) AS [CellsPerObject],
CAST(case when i.type=4 then 1 else 0 end AS bit) AS [IsSpatialIndex],
i.has_filter AS [HasFilter],
ISNULL(i.filter_definition, N'''') AS [FilterDefinition],
CASE WHEN ''FG''=dsi.type THEN dsi.name ELSE N'''' END AS [FileGroup],
CASE WHEN ''PS''=dsi.type THEN dsi.name ELSE N'''' END AS [PartitionScheme],
CAST(CASE WHEN ''PS''=dsi.type THEN 1 ELSE 0 END AS bit) AS [IsPartitioned],
CASE WHEN ''FD''=dstbl.type THEN dstbl.name ELSE N'''' END AS [FileStreamFileGroup],
CASE WHEN ''PS''=dstbl.type THEN dstbl.name ELSE N'''' END AS [FileStreamPartitionScheme],
CAST(CASE WHEN filetableobj.object_id IS NULL THEN 0 ELSE 1 END AS bit) AS [IsFileTableDefined],
CAST(
CASE i.type WHEN 1 THEN 0 WHEN 4 THEN 4
WHEN 3 THEN CASE xi.xml_index_type WHEN 0 THEN 2 WHEN 1 THEN 3 WHEN 2 THEN 7 WHEN 3 THEN 8 END
WHEN 4 THEN 4 WHEN 6 THEN 5 ELSE 1 END
AS tinyint) AS [IndexType],
ISNULL(indexedpaths.name, N'''')
AS [IndexedXmlPathName]
FROM
sys.table_types AS tt
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
INNER JOIN sys.indexes AS i ON (i.index_id > #_msparam_0 and i.is_hypothetical = #_msparam_1) AND (i.object_id=tt.type_table_object_id)
LEFT OUTER JOIN sys.stats AS s ON s.stats_id = i.index_id AND s.object_id = i.object_id
LEFT OUTER JOIN sys.key_constraints AS k ON k.parent_object_id = i.object_id AND k.unique_index_id = i.index_id
LEFT OUTER JOIN sys.xml_indexes AS xi ON xi.object_id = i.object_id AND xi.index_id = i.index_id
LEFT OUTER JOIN sys.xml_indexes AS xi2 ON xi2.object_id = xi.object_id AND xi2.index_id = xi.using_xml_index_id
LEFT OUTER JOIN sys.spatial_indexes AS spi ON i.object_id = spi.object_id and i.index_id = spi.index_id
LEFT OUTER JOIN sys.spatial_index_tessellations as si ON i.object_id = si.object_id and i.index_id = si.index_id
LEFT OUTER JOIN sys.data_spaces AS dsi ON dsi.data_space_id = i.data_space_id
LEFT OUTER JOIN sys.tables AS t ON t.object_id = i.object_id
LEFT OUTER JOIN sys.data_spaces AS dstbl ON dstbl.data_space_id = t.Filestream_data_space_id and (i.index_id < 2 or (i.type = 7 and i.index_id < 3))
LEFT OUTER JOIN sys.filetable_system_defined_objects AS filetableobj ON i.object_id = filetableobj.object_id
LEFT OUTER JOIN sys.selective_xml_index_paths AS indexedpaths ON xi.object_id = indexedpaths.object_id AND xi.using_xml_index_id = indexedpaths.index_id AND xi.path_id = indexedpaths.path_id
WHERE
(i.name=#_msparam_2)and((tt.name=#_msparam_3 and SCHEMA_NAME(tt.schema_id)=#_msparam_4))',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000),#_msparam_2 nvarchar(4000),#_msparam_3 nvarchar(4000),#_msparam_4 nvarchar(4000)',#_msparam_0=N'0',#_msparam_1=N'0',#_msparam_2=N'PK__TT_id_ba__70BD165044265C38',#_msparam_3=N'YourType',#_msparam_4=N'dbo'
exec sp_executesql N'SELECT
(case ic.key_ordinal when 0 then ic.index_column_id else ic.key_ordinal end) AS [ID],
clmns.name AS [Name]
FROM
sys.table_types AS tt
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
INNER JOIN sys.indexes AS i ON (i.index_id > #_msparam_0 and i.is_hypothetical = #_msparam_1) AND (i.object_id=tt.type_table_object_id)
INNER JOIN sys.index_columns AS ic ON (ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0 or ic.is_included_column != 0)) AND (ic.index_id=CAST(i.index_id AS int) AND ic.object_id=i.object_id)
INNER JOIN sys.columns AS clmns ON clmns.object_id = ic.object_id and clmns.column_id = ic.column_id
WHERE
(i.name=#_msparam_2)and((tt.name=#_msparam_3 and SCHEMA_NAME(tt.schema_id)=#_msparam_4))
ORDER BY
[ID] ASC',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000),#_msparam_2 nvarchar(4000),#_msparam_3 nvarchar(4000),#_msparam_4 nvarchar(4000)',#_msparam_0=N'0',#_msparam_1=N'0',#_msparam_2=N'PK__TT_id_ba__70BD165044265C38',#_msparam_3=N'YourType',#_msparam_4=N'dbo'
exec sp_executesql N'SELECT
clmns.name AS [Name],
(case ic.key_ordinal when 0 then ic.index_column_id else ic.key_ordinal end) AS [ID],
CAST(COLUMNPROPERTY(ic.object_id, clmns.name, N''IsComputed'') AS bit) AS [IsComputed],
ic.is_descending_key AS [Descending],
ic.is_included_column AS [IsIncluded]
FROM
sys.table_types AS tt
INNER JOIN sys.schemas AS stt ON stt.schema_id = tt.schema_id
INNER JOIN sys.indexes AS i ON (i.index_id > #_msparam_0 and i.is_hypothetical = #_msparam_1) AND (i.object_id=tt.type_table_object_id)
INNER JOIN sys.index_columns AS ic ON (ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0 or ic.is_included_column != 0)) AND (ic.index_id=CAST(i.index_id AS int) AND ic.object_id=i.object_id)
INNER JOIN sys.columns AS clmns ON clmns.object_id = ic.object_id and clmns.column_id = ic.column_id
WHERE
(clmns.name=#_msparam_2)and((i.name=#_msparam_3)and((tt.name=#_msparam_4 and SCHEMA_NAME(tt.schema_id)=#_msparam_5)))',N'#_msparam_0 nvarchar(4000),#_msparam_1 nvarchar(4000),#_msparam_2 nvarchar(4000),#_msparam_3 nvarchar(4000),#_msparam_4 nvarchar(4000),#_msparam_5 nvarchar(4000)',#_msparam_0=N'0',#_msparam_1=N'0',#_msparam_2=N'id_banca',#_msparam_3=N'PK__TT_id_ba__70BD165044265C38',#_msparam_4=N'YourType',#_msparam_5=N'dbo'
This is to give you an idea how complex it is

Types and UDTs don't appear in either sys.objects or sys.sql_modules, simply because they're not modules but types.
for getting the script of a UDT you gotta join sys.types with sys.schemas, on schema_id field. and still you need to do some parsing and conversion i suppose.

Related

Bypassing LCK_M_SCH_S lock when requesting partition information

I have code to query partition data.
But when the database creates an index, my query does not work because of the LCK_M_SCH_S lock, although I use the NOLOCK hint for all tables.
Is there any way around this lock?
SELECT DB_NAME() AS DatabaseName
, OBJECT_SCHEMA_NAME(p.OBJECT_ID) as TableschemaName
, OBJECT_NAME(p.OBJECT_ID) AS TableName
, p.index_id AS 'IndexId'
, CASE WHEN p.index_id = 0 THEN 'HEAP'
ELSE i.name
END AS 'IndexName'
, p.partition_number AS PartitionNumber
, prv_left.value AS LowerBoundary
, prv_right.value AS UpperBoundary
, ps.name as PartitionScheme
, pf.name as PartitionFunction
, c.name AS [Partitioning Column]
, TYPE_NAME(c.user_type_id) AS [Column Type]
, CASE WHEN fg.name IS NULL THEN ds.name
ELSE fg.name
END AS 'FileGroupName'
, CAST(p.used_page_count * 0.0078125 AS NUMERIC(18,2)) AS UsedPagesMB
, CAST(p.in_row_data_page_count * 0.0078125 AS NUMERIC(18,2)) AS DataPagesMB
, CAST(p.reserved_page_count * 0.0078125 AS NUMERIC(18,2)) AS ReservedPagesMB
, CASE WHEN p.index_id IN (0,1) THEN p.row_count
ELSE 0
END AS RowsQuantity
,CASE WHEN p.index_id IN (0,1) THEN 'data'
ELSE 'index'
END AS Type
FROM sys.dm_db_partition_stats p WITH (NOLOCK)
JOIN sys.indexes i WITH (NOLOCK) ON i.OBJECT_ID = p.OBJECT_ID AND i.index_id = p.index_id
JOIN sys.data_spaces ds WITH (NOLOCK) ON ds.data_space_id = i.data_space_id
LEFT JOIN sys.partition_schemes ps WITH (NOLOCK) ON ps.data_space_id = i.data_space_id
LEFT JOIN sys.partition_functions pf WITH (NOLOCK) ON ps.function_id = pf.function_id
LEFT JOIN sys.destination_data_spaces dds WITH (NOLOCK) ON dds.partition_scheme_id = ps.data_space_id
AND dds.destination_id = p.partition_number
LEFT JOIN sys.filegroups fg WITH (NOLOCK) ON fg.data_space_id = dds.data_space_id
LEFT JOIN sys.partition_range_values prv_right WITH (NOLOCK) ON prv_right.function_id = ps.function_id
AND prv_right.boundary_id = p.partition_number
LEFT JOIN sys.partition_range_values prv_left WITH (NOLOCK) ON prv_left.function_id = ps.function_id
AND prv_left.boundary_id = p.partition_number - 1
LEFT JOIN sys.index_columns ic WITH (NOLOCK) ON ic.[object_id] = i.[object_id]
AND ic.index_id = i.index_id
AND ic.partition_ordinal >= 1
LEFT JOIN sys.columns c WITH (NOLOCK) ON p.OBJECT_ID = c.[object_id]
AND ic.column_id = c.column_id
WHERE OBJECTPROPERTY(p.OBJECT_ID, 'ISMSSHipped') = 0
AND p.index_id IN (0,1)
AND ps.name IS NOT NULL

Optimize long query to find database schema with foreign keys and tables

I am writing a query to get all the tables in the db with their properties but also foreign keys and table that each reference to. I have a following query but it is taking 60 min to complete. Not sure what am I doing wrong?
SELECT
ist.table_name,
isc.column_name,
data_type,
character_maximum_length,
Columnproperty(Object_id(isc.table_name),
isc.column_name, 'IsIdentity') AS identityFlag,
is_nullable,
character_maximum_length,
numeric_scale,
(SELECT 1
FROM information_schema.table_constraints AS C
JOIN information_schema.key_column_usage AS K ON C.table_name = K.table_name
AND C.constraint_catalog = K.constraint_catalog
AND C.constraint_schema = K.constraint_schema
AND C.constraint_name = K.constraint_name
WHERE C.constraint_type = 'PRIMARY KEY'
AND C.table_name = isc.table_name
AND K.column_name = isc.column_name) AS primarykey,
(SELECT TOP 1 1
FROM information_schema.table_constraints AS C
JOIN information_schema.key_column_usage AS K ON C.table_name = K.table_name
AND C.constraint_catalog = K.constraint_catalog
AND C.constraint_schema = K.constraint_schema
AND C.constraint_name = K.constraint_name
WHERE C.constraint_type = 'FOREIGN KEY'
AND C.table_name = isc.table_name
AND K.column_name = isc.column_name) AS foreignKey,
a.parenttablename AS foreignTableName,
a.colname AS foreignColumnName
FROM
information_schema.tables ist
INNER JOIN
information_schema.columns isc ON ist.table_name = isc.table_name
LEFT OUTER JOIN
(SELECT
t.NAME AS parentTableName,
Object_name(f.parent_object_id) TableName,
Col_name(fc.parent_object_id, fc.parent_column_id) ColName
FROM
sys.foreign_keys AS f
INNER JOIN
sys.foreign_key_columns AS fc ON f.object_id = fc.constraint_object_id
INNER JOIN
sys.tables t ON t.object_id = fc.referenced_object_id) a ON a.tablename = ist.table_name
AND a.colname = isc.column_name
It is taking time to find the foreign table names. What is the best way to get db table schema
Firstly, you should stick to the sys schema, as these catalog views are more efficient, and INFORMATION_SCHEMA is only for compatibility
You are over-complicating it. You don't need to query the foreign key twice, you can just check if the LEFT JOIN succeeded by checking for NULL
SELECT
t.name AS table_name,
c.name AS column_name,
typ.name AS data_type,
c.max_length,
c.is_identity AS identityFlag,
c.is_nullable,
c.precision,
c.scale,
CASE WHEN EXISTS (SELECT 1
FROM sys.indexes AS i
JOIN sys.index_columns AS ic
ON ic.object_id = i.object_id
AND ic.index_id = i.index_id
WHERE i.object_id = t.object_id
AND ic.column_id = c.column_id
) THEN 1 ELSE 0 END AS primarykey,
CASE WHEN t_f.name IS NOT NULL THEN 1 ELSE 0 END AS foreignKey,
t_f.name AS foreignTableName,
c_f.name AS foreignColumnName
FROM
sys.tables t
INNER JOIN
sys.columns c ON c.object_id = t.object_id
INNER JOIN
sys.types typ ON typ.user_type_id = c.user_type_id
LEFT OUTER JOIN
sys.foreign_key_columns AS fc
INNER JOIN
sys.tables t_f ON t_f.object_id = fc.referenced_object_id
INNER JOIN
sys.columns c_f ON c_f.object_id = t_f.object_id
AND c_f.column_id = fc.referenced_column_id
ON fc.parent_object_id = t.object_id
AND fc.parent_column_id = c.column_id;

How do I see the size of all the tables

I've created a table in my database by mistake which has zero rows, and I want to know a systemic way to find out that table. I know we can use sp_spaceused to get the number of rows but how can I do it for all the tables.
Paste the output of the below query in a new SQL Editor and do a visual scan of the output
SELECT *
FROM (
SELECT 1000 * ROW_NUMBER () OVER (ORDER BY name) rk,
' sp_spaceused ' + name spused
FROM sys.Tables
UNION ALL
SELECT 1 + 1000 * ROW_NUMBER () OVER (ORDER BY name), ' go'
FROM sys.Tables
) a
ORDER BY a.rk
Below you can find the query with additional details
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
CASE WHEN FG.Name IS NULL THEN DS.Name ELSE FG.Name END AS 'FileGroupName'
,DB_NAME() AS 'DatabaseName'
,OBJECT_SCHEMA_NAME(P.OBJECT_ID) AS 'Schema'
,OBJECT_NAME(P.OBJECT_ID) AS 'TableName'
,CASE WHEN P.index_id = 0 THEN 'HEAP' ELSE I.name END AS 'IndexName'
,CASE WHEN P.index_id IN (0,1) THEN 'data' ELSE 'index' END AS 'Type'
,P.partition_number AS 'PartitionNumber'
,CAST(P.reserved_page_count * 0.008 AS NUMERIC(18,2)) AS 'ReservedSize_MB'
,CAST(P.used_page_count * 0.008 AS NUMERIC(18,2)) AS 'UsedSize_MB'
,P.row_count AS 'RowCount'
FROM
sys.dm_db_partition_stats P
INNER JOIN sys.indexes I ON I.OBJECT_ID = P.OBJECT_ID AND I.index_id = P.index_id
INNER JOIN sys.data_spaces DS ON DS.data_space_id = I.data_space_id
LEFT OUTER JOIN sys.filegroups FG ON FG.data_space_id = DS.data_space_id
WHERE
OBJECTPROPERTY(p.OBJECT_ID, 'ISMSSHipped') = 0
ORDER BY ReservedSize_MB DESC
Below you can find the query for details of partitioned tables
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT
DB_NAME() AS 'DatabaseName'
,OBJECT_NAME(p.OBJECT_ID) AS 'TableName'
,p.index_id AS 'IndexId'
,CASE
WHEN p.index_id = 0 THEN 'heap'
ELSE i.[name]
END AS 'IndexName'
,sp.data_compression_desc
,p.partition_number AS 'PartitionNumber'
,prv_left.[value] AS 'LowerBoundary'
,prv_right.[value] AS 'UpperBoundary'
,CASE
WHEN fg.[name] IS NULL THEN ds.[name]
ELSE fg.[name]
END AS 'FileGroupName'
,CAST(p.used_page_count * 0.0078125 AS numeric(18,2)) AS 'UsedPages_MB'
,CAST(p.in_row_data_page_count * 0.0078125 AS numeric(18,2)) AS 'DataPages_MB'
,CAST(p.reserved_page_count * 0.0078125 AS numeric(18,2)) AS 'ReservedPages_MB'
,p.row_count AS 'RowCount'
,CASE
WHEN p.index_id IN (0, 1) THEN 'data'
ELSE 'index'
END 'Type'
FROM
sys.dm_db_partition_stats p
INNER JOIN sys.indexes i ON i.OBJECT_ID = p.OBJECT_ID
AND i.index_id = p.index_id
INNER JOIN sys.partitions sp ON p.[partition_id] = sp.[partition_id]
INNER JOIN sys.data_spaces ds ON ds.data_space_id = i.data_space_id
LEFT OUTER JOIN sys.partition_schemes ps ON ps.data_space_id = i.data_space_id
LEFT OUTER JOIN sys.destination_data_spaces dds ON dds.partition_scheme_id = ps.data_space_id
AND dds.destination_id = p.partition_number
LEFT OUTER JOIN sys.filegroups fg ON fg.data_space_id = dds.data_space_id
LEFT OUTER JOIN sys.partition_range_values prv_right ON prv_right.function_id = ps.function_id
AND prv_right.boundary_id = p.partition_number
LEFT OUTER JOIN sys.partition_range_values prv_left ON prv_left.function_id = ps.function_id
AND prv_left.boundary_id = p.partition_number - 1
WHERE
OBJECTPROPERTY(p.OBJECT_ID, 'ISMSSHipped') = 0
ORDER BY 2,3,5

Test existing column in query in SQL Server

I have this script below:
---------Part 1--------
SELECT
COLUMN_NAME
FROM
(SELECT
SC.name as TABLE_SCHEMA,
t.name as TABLE_NAME,
ind.name as indexName,
ind.type_desc AS type_Index,
SUBSTRING((SELECT ', ' + AC.name
FROM DATA.sys.[tables] AS T
INNER JOIN DATA.sys.[indexes] I ON T.[object_id] = I.[object_id]
INNER JOIN DATA.sys.[index_columns] IC ON I.[object_id] = IC.[object_id] AND I.[index_id] = IC.[index_id]
INNER JOIN DATA.sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id]
WHERE Ind.[object_id] = I.[object_id] AND Ind.index_id = I.index_id AND IC.is_included_column = 0
ORDER BY IC.key_ordinal
FOR XML PATH('')), 2, 8000) AS COLUMN_NAME
FROM DATA.sys.indexes ind
INNER JOIN DATA.sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
INNER JOIN DATA.sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
INNER JOIN DATA.sys.tables t ON ind.object_id = t.object_id
INNER JOIN DATA.sys.schemas SC ON t.schema_id = SC.schema_id
WHERE SC.name ='SCHEMA1') AS SubQ
WHERE
COLUMN_NAME IN
-------Part 2-------
(SELECT COLUMN_NAME
FROM DATA.INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE IN ('nchar', 'nvarchar')
AND TABLE_SCHEMA IN ('SCHEMA1', 'SCHEMA2'))
When I run the part 1 or the part 2, I got the best the columns, and the two results are the same, but when I run all the script it does not dispaly any thing, and no errors.
Some help please ?
Thank you

SQL - Get databases size

I have implemented Blob storage for sharepoint. The code below works and I want to make sure it's counting the filestream on the drive for the blobs as well.
SELECT [Database Name] = DB_NAME(database_id),
[Type] = CASE WHEN Type_Desc = 'ROWS' THEN 'Data File(s)'
WHEN Type_Desc = 'LOG' THEN 'Log File(s)'
ELSE Type_Desc END,
[Size in MB] = CAST( ((SUM(Size)* 8) / 1024.0) AS DECIMAL(18,2) )
FROM sys.master_files
-- Uncomment if you need to query for a particular database
-- WHERE database_id = DB_ID(‘Database Name’)
GROUP BY GROUPING SETS
(
(DB_NAME(database_id), Type_Desc),
(DB_NAME(database_id))
)
ORDER BY DB_NAME(database_id), Type_Desc DESC
GO
Please try one of these SQL scripts.
SELECT
t.NAME AS TableName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, p.Rows
ORDER BY
t.Name
--- SQL2005
select o.name
, reservedpages = sum(a.total_pages)
, usedpages = sum(a.used_pages)
, pages = sum(case when a.type <> 1 then a.used_pages
when p.index_id < 2 then a.data_pages else 0 end)
, SUM(a.used_pages)*8096 AS 'Size(B)'
, rows = sum(case when (p.index_id < 2) and (a.type = 1) then p.rows else 0 end)
from sys.objects o
join sys.partitions p on p.object_id = o.object_id
join sys.allocation_units a on p.partition_id = a.container_id
where o.type = 'U'
group by o.name
order by 3 desc --biggest tables first
In addition, here are a couple links that will give you some more ideas.
http://ask.sqlservercentral.com/questions/88859/sql-server-2008-r2-table-sizes.html
http://www.sqlmatters.com/Articles/Listing%20all%20tables%20in%20a%20database%20and%20their%20row%20counts%20and%20sizes.aspx

Resources