Tải bản đầy đủ - 0 (trang)
8-6. Analyzing SQL Server Table Metadata

8-6. Analyzing SQL Server Table Metadata

Tải bản đầy đủ - 0trang

Chapter 8 ■ Metadata



-- Table data

CREATE TABLE #MetaData_Tables

(

SCHEMA_NAME sysname NOT NULL,

TABLE_NAME sysname NOT NULL,

object_id INT NOT NULL,

TableType NVARCHAR(60) NULL,

DateCreated datetime NOT NULL,

DateModified datetime NOT NULL,

uses_ansi_nulls BIT NULL,

text_in_row_limit INT NULL,

large_value_types_out_of_row BIT NULL,

IsCDCTracked BIT NULL,

lock_escalation_desc NVARCHAR(60) NULL,

LobDataSpace sysname NULL,

FilestreamDataSpace sysname NULL,

DataSpace VARCHAR(250) NULL,

DataSpaceType VARCHAR(250) NULL,

NbrColumns smallint NULL,

IsHeap BIT NULL,

NoIndexes BIT NULL,

NoRows BIGINT NULL,

HasAfterTrigger BIT NULL,

HasDeleteTrigger BIT NULL,

HasInsertTrigger BIT NULL,

HasInsteadOfTrigger BIT NULL,

HasUpdateTrigger BIT NULL,

IsAnsiNullsOn BIT NULL,

IsEncrypted BIT NULL,

IsIndexed BIT NULL,

IsIndexable BIT NULL,

IsQuotedIdentOn BIT NULL,

IsSystemTable BIT NULL,

IsUserTable BIT NULL,

DeleteTriggerCount SMALLINT NULL,

FullTextBackgroundUpdateIndexOn BIT NULL,

FulltextCatalogId SMALLINT NULL,

FulltextChangeTrackingOn BIT NULL,

FulltextKeyColumn SMALLINT NULL,

HasActiveFulltextIndex BIT NULL,

HasCheckCnst BIT NULL,

HasClustIndex BIT NULL,

HasDefaultCnst BIT NULL,

HasForeignKey BIT NULL,

HasForeignRef BIT NULL,

HasIdentity BIT NULL,

HasIndex BIT NULL,

HasNonclustIndex BIT NULL,

HasPrimaryKey BIT NULL,

HasRowGuidCol BIT NULL,

HasTextImage BIT NULL,



435

www.it-ebooks.info



Chapter 8 ■ Metadata



HasTimestamp BIT NULL,

HasUniqueCnst BIT NULL,

HasVarDecimalStorageFormat BIT NULL,

InsertTriggerCount SMALLINT NULL,

TextInRowLimit SMALLINT NULL,

UpdateTriggerCount SMALLINT NULL,

HasColumnSet BIT NULL,

DataCompression NVARCHAR(60)

)

INSERT INTO #MetaData_Tables

(

SCHEMA_NAME

,TABLE_NAME

,object_id

,TableType

,DateCreated

,DAteModified

,uses_ansi_nulls

,text_in_row_limit

,large_value_types_out_of_row

,IsCDCTracked

,lock_escalation_desc

,LobDataSpace

,FilestreamDataSpace

,DataSpace

,DataSpaceType

,NbrColumns

,IsHeap

,NoIndexes

,NoRows

,HasAfterTrigger

,HasDeleteTrigger

,HasInsertTrigger

,HasInsteadOfTrigger

,HasUpdateTrigger

,IsAnsiNullsOn

,IsEncrypted

,IsIndexed

,IsIndexable

,IsQuotedIdentOn

,IsSystemTable

,IsUserTable

,DeleteTriggerCount

,FullTextBackgroundUpdateIndexOn

,FulltextCatalogId

,FulltextChangeTrackingOn

,FulltextKeyColumn

,HasActiveFulltextIndex

,HasCheckCnst

,HasClustIndex

,HasDefaultCnst



436

www.it-ebooks.info



Chapter 8 ■ Metadata



,HasForeignKey

,HasForeignRef

,HasIdentity

,HasIndex

,HasNonclustIndex

,HasPrimaryKey

,HasRowGuidCol

,HasTextImage

,HasTimestamp

,HasUniqueCnst

,HasVarDecimalStorageFormat

,InsertTriggerCount

,TextInRowLimit

,UpdateTriggerCount

,HasColumnSet

)

SELECT

SCH.name AS SCHEMA_NAME

,TBL.name AS TABLE_NAME

,TBL.object_id

,TBL.type_desc AS TableType

,TBL.create_date AS DateCreated

,TBL.modify_date AS DAteModified

,TBL.uses_ansi_nulls

,TBL.text_in_row_limit

,TBL.large_value_types_out_of_row

,TBL.is_tracked_by_cdc AS IsCDCTracked

,TBL.lock_escalation_desc

,DSP.name AS LobDataSpace

,DSP1.name AS FilestreamDataSpace

,CAST(NULL AS VARCHAR(250)) AS DataSpace

,CAST(NULL AS VARCHAR(250)) AS DataSpaceType

,CAST(NULL AS SMALLINT) AS NbrColumns

,CAST(NULL AS BIT) AS IsHeap

,CAST(NULL AS BIT) AS NoIndexes

,CAST(NULL AS BIGINT) AS NoRows

,OBJECTPROPERTY(TBL.object_id, 'HasAfterTrigger') AS HasAfterTrigger

,OBJECTPROPERTY(TBL.object_id, 'HasDeleteTrigger') AS HasDeleteTrigger

,OBJECTPROPERTY(TBL.object_id, 'HasInsertTrigger') AS HasInsertTrigger

,OBJECTPROPERTY(TBL.object_id, 'HasInsteadOfTrigger') AS HasInsteadOfTrigger

,OBJECTPROPERTY(TBL.object_id, 'HasUpdateTrigger') AS HasUpdateTrigger

,OBJECTPROPERTY(TBL.object_id, 'IsAnsiNullsOn') AS IsAnsiNullsOn

,OBJECTPROPERTY(TBL.object_id, 'IsEncrypted') AS IsEncrypted

,OBJECTPROPERTY(TBL.object_id, 'IsIndexed') AS IsIndexed

,OBJECTPROPERTY(TBL.object_id, 'IsIndexable') AS IsIndexable

,OBJECTPROPERTY(TBL.object_id, 'IsQuotedIdentOn') AS IsQuotedIdentOn

,OBJECTPROPERTY(TBL.object_id, 'IsSystemTable') AS IsSystemTable

,OBJECTPROPERTY(TBL.object_id, 'IsUserTable') AS IsUserTable

,OBJECTPROPERTY(TBL.object_id, 'DeleteTriggerCount') AS DeleteTriggerCount

,OBJECTPROPERTY(TBL.object_id, 'FullTextBackgroundUpdateIndexOn')

AS FullTextBackgroundUpdateIndexOn



437

www.it-ebooks.info



Chapter 8 ■ Metadata



,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

,OBJECTPROPERTY(TBL.object_id,

FROM



'FulltextCatalogId') AS FulltextCatalogId

'FulltextChangeTrackingOn') AS FulltextChangeTrackingOn

'FulltextKeyColumn') AS FulltextKeyColumn

'HasActiveFulltextIndex') AS HasActiveFulltextIndex

'HasCheckCnst') AS HasCheckCnst

'HasClustIndex') AS HasClustIndex

'HasDefaultCnst') AS HasDefaultCnst

'HasForeignKey') AS HasForeignKey

'HasForeignRef') AS HasForeignRef

'HasIdentity') AS HasIdentity

'HasIndex') AS HasIndex

'HasNonclustIndex') AS HasNonclustIndex

'HasPrimaryKey') AS HasPrimaryKey

'HasRowGuidCol') AS HasRowGuidCol

'HasTextImage') AS HasTextImage

'HasTimestamp') AS HasTimestamp

'HasUniqueCnst') AS HasUniqueCnst

'HasVarDecimalStorageFormat') AS HasVarDecimalStorageFormat

'InsertTriggerCount') AS InsertTriggerCount

'TextInRowLimit') AS TextInRowLimit

'UpdateTriggerCount') AS UpdateTriggerCount

'HasColumnSet') AS HasColumnSet



sys.schemas AS SCH

INNER JOIN sys.tables AS TBL

ON SCH.schema_id = TBL.schema_id

LEFT OUTER JOIN sys.data_spaces DSP1

ON TBL.filestream_data_space_id = DSP1.data_space_id

LEFT OUTER JOIN sys.data_spaces DSP

ON TBL.lob_data_space_id = DSP.data_space_id



WHERE TBL.is_ms_shipped = 0

--------------------------------------------------------------------------------- Get all secondary elements, process later

--------------------------------------------------------------------------------- FileGroup

IF OBJECT_ID('tempdb..#Tmp_FileGroupDetails') IS NOT NULL

DROP TABLE tempdb..#Tmp_FileGroupDetails;

SELECT DISTINCT

DSP.name AS DataSpace

,DSP.type_desc AS DataSpaceType

,TBL.name AS TABLE_NAME

,TBL.object_id AS TableObjectID

INTO



#Tmp_FileGroupDetails



438

www.it-ebooks.info



Chapter 8 ■ Metadata



FROM



sys.data_spaces DSP

INNER JOIN sys.indexes SIX

ON DSP.data_space_id = SIX.data_space_id

INNER JOIN sys.tables TBL

ON SIX.object_id = TBL.object_id

--------------------------------------------------------------------------------- Process all secondary elements

--------------------------------------------------------------------------------- FileGroup

UPDATE



D



SET



D.DataSpace = Tmp.DataSpace

,D.DataSpaceType = Tmp.DataSpaceType



FROM



#MetaData_Tables D

INNER JOIN #Tmp_FileGroupDetails Tmp

ON D.object_id = Tmp.TableObjectID



-- Column Counts

;

WITH NoCols_CTE (SCHEMA_NAME,TABLE_NAME,object_id, NoCols)

AS

(

SELECT

TOP (100) PERCENT

SCH.name AS SCHEMA_NAME

,TBL.name AS TABLE_NAME

,COL.object_id

,COUNT(COL.column_id) AS NoCols

FROM



sys.columns COL

INNER JOIN sys.tables TBL

ON COL.object_id = TBL.object_id

INNER JOIN sys.schemas SCH

ON TBL.schema_id = SCH.schema_id



GROUP BY COL.object_id, TBL.name, SCH.name

)

UPDATED

SET

D.NbrColumns = CTE.NoCols

FROM #MetaData_Tables D

INNER JOIN NoCols_CTE CTE

ON D.object_id = CTE.object_id

-- Heaps

UPDATE #MetaData_Tables

SET IsHeap = 1



439

www.it-ebooks.info



Chapter 8 ■ Metadata



WHERE object_id IN(

SELECT DISTINCT TBL.object_id

FROM

sys.tables TBL

INNER JOIN sys.schemas SCH

ON TBL.schema_id = SCH.schema_id

INNER JOIN sys.indexes SIX

ON TBL.object_id = SIX.object_id

WHERE



SIX.type_desc = N'HEAP'



   )

-- Rows

;

WITH RowCount_CTE (SCHEMA_NAME, TABLE_NAME, object_id, NoRows)

AS

(

SELECT

SCH.name AS SCHEMA_NAME

,TBL.name AS TABLE_NAME

,TBL.object_id

,SSX.rows

FROM



sys.tables TBL

INNER JOIN sys.schemas SCH

ON TBL.schema_id = SCH.schema_id

INNER JOIN sys.sysindexes SSX

ON TBL.object_id = SSX.id



)

UPDATED

SETD.NoRows = CTE.NoRows

FROM



#MetaData_Tables D

INNER JOIN RowCount_CTE CTE

ON D.object_id = CTE.object_id



-- Indexes

;

WITH Indexes_CTE (SCHEMA_NAME, TABLE_NAME, object_id, NoIndexes)

AS

(

SELECT

SCH.name AS SCHEMA_NAME

,TBL.name AS TABLE_NAME

,TBL.object_id

,COUNT(SIX.index_id) AS NoIndexes

FROM



sys.tables TBL

INNER JOIN sys.schemas SCH

ON TBL.schema_id = SCH.schema_id



440

www.it-ebooks.info



Chapter 8 ■ Metadata



INNER JOIN sys.indexes SIX

ON TBL.object_id = SIX.object_id

GROUP BY

)



SCH.name, TBL.name, TBL.object_id



UPDATE



D



SET



D.NoIndexes = CTE.NoIndexes



FROM



#MetaData_Tables D

INNER JOIN Indexes_CTE CTE

ON D.object_id = CTE.object_id



-- Compression

;

WITH Compression_CTE

AS

(

SELECT

SCH.name AS SCHEMA_NAME

,TBL.name AS TABLE_NAME

,PRT.data_compression_desc

,TBL.object_id

FROM



sys.partitions PRT

INNER JOIN sys.tables TBL

ON PRT.object_id = TBL.object_id

INNER JOIN sys.schemas SCH

ON TBL.schema_id = SCH.schema_id



WHERE PRT.index_id = 0

OR PRT.index_id = 1

)

UPDATE



D



SET



D.DataCompression = CTE.data_compression_desc



FROM



#MetaData_Tables D

INNER JOIN Compression_CTE CTE

ON D.object_id = CTE.object_id



SELECT * from #MetaData_Tables; -- Yes SELECT * is bad—but here it saves space!

The output from this script (cut into several parts for easier viewing in a book format) looks like Figure 8-3.



441

www.it-ebooks.info



Chapter 8 ■ Metadata



Figure 8-3.  Metadata returned from the script in Recipe 8-6



How It Works

It is important to cover the topic of SQL Server metadata for the following reasons:





If you are dealing with SQL Server source data, then there is a tendency to think that

this will be the easy part, and so to push ahead with the creation of a data flow, only to

be tripped up later when a datatype limitation or a constraint causes unforeseen and

unexpected problems. And, of course, these are always the ones you never expect, and so

they take hours to debug.







When dealing with SQL Server tables—be they staging tables or a final database (possibly

one that you did not design), it is better to be forewarned about as much as possible.







Isolating and analyzing the SQL Server destination metadata just as you would the source

metadata allows you to compare the two cleanly and efficiently.



Let’s be clear, there are a multitude of ways to query the metadata of an SQL Server database. In fact, you

may wonder why you need to see so many ways of extracting the source metadata. The answer is—you never

know when you will need each one, so it is better to be aware that they exist.

For in-depth detail of source metadata, nothing can beat the system views. As you have probably found out

by now, using them properly requires a serious investment in understanding how they work. As this is not entirely

easy, I am proposing two scripts (in this recipe and the following one) that can return a relatively in-depth analysis

of SQL Server metadata for both tables (or views) and columns. If these scripts provide too much information,

then you can always reduce their complexity and limit the metadata that they provide. The main thing is to have

a tool to start your analysis. The script used in this recipe hopefully proves to be such a starting point, and returns

the table metadata shown in Table 8-6.



442

www.it-ebooks.info



Chapter 8 ■ Metadata



Table 8-6.  Table Metdata Returned by the Script in Recipe 8-6



Field Name



Description



SCHEMA_NAME



The schema of the table.



TABLE_NAME



The table name.



object_id



The internal object ID used by the system metadata.



TableType



The table type (table or view).



DateCreated



The date the table was created.



DateModified



The date the table was modified.



uses_ansi_nulls



The table uses ANSI NULLS.



text_in_row_limit



The upper limit (in bytes) for LOBs stored in-row.



large_value_types_out_of_row



Large values are stored out of row.



IsCDCTracked



The table has changes tracked using Change Data Capture.



lock_escalation_desc



The table’s Lock Escalation threshold.



LobDataSpace



The LOB dataspace type for the table’s LOB columns.



FilestreamDataSpace



The FILESTREAM dataspace type for the table’s FILESTREAM column.



DataSpace



The table dataspace.



DataSpaceType



The table dataspace type.



NbrColumns



The number of columns in the table.



IsHeap



The table is a heap (no clustered index).



NoIndexes



The number of indexes on the table.



NoRows



The number of rows in the table.



HasAfterTrigger



The table has an After trigger.



HasDeleteTrigger



The table has a Delete trigger.



HasInsertTrigger



The table has an Insert trigger.



HasInsteadOfTrigger



The table has an Instead Of trigger.



HasUpdateTrigger



The table has an Update trigger.



IsAnsiNullsOn



ANSI NULLS are active for this table.



IsEncrypted



The table is encrypted.



IsIndexed



The table is indexed.



IsIndexable



The table can be indexed.



IsQuotedIdentOn



The table uses quoted identifiers.



IsSystemTable



The table is a system table.

(continued)



443

www.it-ebooks.info



Chapter 8 ■ Metadata



Table 8-6.  (continued)



Field Name



Description



IsUserTable



The table is a user table.



DeleteTriggerCount



The number of delete triggers associated with the table.



FullTextBackgroundUpdateIndexOn



Background index updating is active for this table’s full-text index.



FulltextCatalogId



The ID of any full-text catalog.



FulltextChangeTrackingOn



Change tracking is active for full-text indexing.



FulltextKeyColumn



The key column for full-text indexing.



HasActiveFulltextIndex



The table has an active full-text index.



HasCheckCnst



The table has check constraints.



HasClustIndex



The table has a clustered index.



HasDefaultCnst



The table has default constraints.



HasForeignKey



The table contains foreign key(s).



HasForeignRef



The table contains foreign key references.



HasIdentity



The table contains an IDENTITY column.



HasIndex



The table has an index.



HasNonclustIndex



The table has a clustered index.



HasPrimaryKey



The table has a primary key.



HasRowGuidCol



The table has a Row GUID column.



HasTextImage



Has TEXT, IMAGE, VARCHAR(MAX), or VARBINARY(MAX) column(s).



HasTimestamp



The table has a Timestamp column.



HasUniqueCnst



The table has unique constraints.



HasVarDecimalStorageFormat



VarDecimal compression is active.



InsertTriggerCount



The number of insert triggers associated with the table.



UpdateTriggerCount



The number of update triggers associated with the table.



HasColumnSet



The table contains column sets.



DataCompression



Data compression is on for this table.



The script uses the @SERVER_NAME and @DATABASE_NAME input parameters to define the server and analyze the

database. They default to the current server and database, but you can alter this. It then creates a session-scoped

temporary table to hold all the required metadata. In a first pass, it uses the “core” catalog views (sys.tables,

sys.data_spaces and sys.schemas) and a series of OBJECTPROPERTY functions to get a fairly full set of metadata.

Following this, a series of subprocesses use various system catalog views (sys.columns, sys.sysindexes, and

sys.partitions) to return and calculate other metadata elements that are less readily available.



444

www.it-ebooks.info



Chapter 8 ■ Metadata



Hints, Tips, and Traps





I realize that using SELECT * to return the final output from the script in this recipe

contravenes all known best practices, but it saves space in a book. You can—and should—only

select the columns that you require.



8-7. Analyzing SQL Server Column Metadata

Problem

You need to obtain SQL Server column metadata for analysis.



Solution

Use the SQL Server system catalog views to return full column metadata.

Running the following script will give you extensive information about all the SQL Server columns in a

specified database (C:\SQL2012DIRecipes\CH08\SQLServerColumnMetadata.sql):

DECLARE @SERVER_NAME NVARCHAR(128) = @@SERVERNAME

DECLARE @DATABASE_NAME NVARCHAR(128) = DB_NAME()

-----------------------------------------IF OBJECT_ID('tempdb..#Metadata_ColumnTableType') IS NOT NULL

DROP TABLE tempdb..#Metadata_ColumnTableType;

CREATE TABLE #Metadata_ColumnTableType

(

SERVER_NAME VARCHAR(128) NULL,

DATABASE_NAME VARCHAR(128) NULL,

TABLE_SCHEMA VARCHAR(8) NULL,

TABLE_NAME VARCHAR(8) NULL,

COLUMN_NAME VARCHAR(8) NULL,

column_id INT NULL,

DataType VARCHAR(8) NULL,

ColLength INT NULL,

precision TINYINT NULL,

scale TINYINT NULL,

CollationName VARCHAR(8) NULL,

IsNullable BIT NULL,

IsIdentity BIT NULL,

IsComputed BIT NULL,

IsFileStream BIT NULL,

IsSparse BIT NULL,

IsColumnSet BIT NULL,

object_id INT NULL,

default_object_id INT NULL,

ColDefinition VARCHAR(max) NULL,

DefaultName VARCHAR(250) NULL,

DefaultDefinition VARCHAR(max) NULL,

IsFulltextIndexed BIT NULL,



445

www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

8-6. Analyzing SQL Server Table Metadata

Tải bản đầy đủ ngay(0 tr)

×