Como saber as características de um objeto em SQL

novembro 7, 2007

A linguagem SQL possui uma função que exibe informações sobre todos os objetos existentes na base de dados.

Sintaxe:

OBJECTPROPERTY(id, propriedade)

Argumentos:

id -> É a identificação do objeto na base de dados, ou seja, uma identificação única e que pode ser encontrada na tabela sysobjects. Lembrando que este argumente DEVE ser do tipo inteiro.
propriedade -> É onde insere a expressão que se deseja obter sobre o objeto.

Segue abaixo todas as propriedades existentes no SQL Server:

Property name Object type Description and values returned
CnstIsClustKey Constraint A primary key with a clustered index. 1 = True0 = False
CnstIsColumn Constraint COLUMN constraint. 1 = True0 = False
CnstIsDeleteCascade Constraint A foreign key constraint with the ON DELETE CASCADE
option.
CnstIsDisabled Constraint Disabled constraint. 1 = True0 = False
CnstIsNonclustKey Constraint A primary key with a nonclustered index. 1 = True0 = False
CnstIsNotTrusted Constraint Constraint was enabled without checking existing rows, so constraint may not hold for all rows. 1 = True0 = False
CnstIsNotRepl Constraint The constraint is defined with the NOT FOR REPLICATION
keywords.
CnstIsUpdateCascade Constraint A foreign key constraint with the ON UPDATE CASCADE
option.
ExecIsAfterTrigger Trigger AFTER trigger.
ExecIsAnsiNullsOn Procedure, Trigger, View The setting of ANSI_NULLS at creation time. 1 = True0 = False
ExecIsDeleteTrigger Trigger DELETE trigger. 1 = True0 = False
ExecIsFirstDeleteTrigger Trigger The first trigger fired when a DELETE is executed against the
table.
ExecIsFirstInsertTrigger Trigger The first trigger fired when an INSERT is executed against the
table.
ExecIsFirstUpdateTrigger Trigger The first trigger fired when an UPDATE is executed against the
table.
ExecIsInsertTrigger Trigger INSERT trigger. 1 = True0 = False
ExecIsInsteadOfTrigger Trigger INSTEAD OF trigger.
ExecIsLastDeleteTrigger Trigger The last trigger fired when a DELETE is executed against the
table.
ExecIsLastInsertTrigger Trigger The last trigger fired when an INSERT is executed against the
table.
ExecIsLastUpdateTrigger Trigger The last trigger fired when an UPDATE is executed against the
table.
ExecIsQuotedIdentOn Procedure, Trigger, View The setting of QUOTED_IDENTIFIER at creation time. 1 = True0 = False
ExecIsStartup Procedure Startup procedure. 1 = True0 = False
ExecIsTriggerDisabled Trigger Disabled trigger. 1 = True0 = False
ExecIsUpdateTrigger Trigger UPDATE trigger. 1 = True0 = False
HasAfterTrigger Table, View Table or view has an AFTER trigger. 1 = True0 = False
HasInsertTrigger Table, View Table or view has an INSERT trigger. 1 = True0 = False
HasInsteadOfTrigger Table, View Table or view has an INSTEAD OF trigger. 1 = True0 = False
HasUpdateTrigger Table, View Table or view has an UPDATE trigger. 1 = True0 = False
IsAnsiNullsOn Function, Procedure, Table, Trigger, View Specifies that the ANSI NULLS option setting for the table is ON, meaning all comparisons against a null value evaluate to UNKNOWN. This setting applies to all expressions in the table definition, including computed columns and constraints, for as long as the table exists. 1 = ON0 = OFF
IsCheckCnst Any CHECK constraint. 1 = True0 = False
IsConstraint Any Constraint. 1 = True0 = False
IsDefault Any Bound default. 1 = True0 = False
IsDefaultCnst Any DEFAULT constraint. 1 = True0 = False
IsDeterministic Function, View The determinism property of the function. Applies only to scalar- and table-valued functions. 1 = Deterministic0 = Not DeterministicNULL = Not a scalar- or table-valued function, or invalid object ID.
IsExecuted Any Specifies how this object can be executed (view, procedure, or trigger). 1 = True0 = False
IsExtendedProc Any Extended procedure. 1 = True0 = False
IsForeignKey Any FOREIGN KEY constraint. 1 = True0 = False
IsIndexed Table, View A table or view with an index.
IsIndexable Table, View A table or view on which an index may be created.
IsInlineFunction Function Inline function. 1 = Inline function0 = Not inline functionNULL = Not a function, or invalid object ID.
IsMSShipped Any An object created during installation of Microsoft® SQL Server™ 2000. 1 = True0 = False
IsPrimaryKey Any PRIMARY KEY constraint. 1 = True0 = False
IsProcedure Any Procedure. 1 = True0 = False
IsQuotedIdentOn Function, Procedure, Table, Trigger, View Specifies that the quoted identifier setting for the table is ON, meaning double quotation marks delimit identifiers in all expressions involved in the table definition. 1 = ON0 = OFF
IsReplProc Any Replication procedure. 1 = True0 = False
IsRule Any Bound rule. 1 = True0 = False
IsScalarFunction Function Scalar-valued function. 1 = Scalar-valued0 = Table-valuedNULL = Not a function, or invalid object ID.
IsSchemaBound Function, View A schema bound function or view created with SCHEMABINDING. 1 = Schema-bound0 = Not schema-boundNULL = Not a function or a view, or invalid object ID.
IsSystemTable Table System table. 1 = True0 = False
IsTable Table Table. 1 = True0 = False
IsTableFunction Function Table-valued function. 1 = Table-valued0 = Scalar-valuedNULL = Not a function, or invalid object ID.
IsTrigger Any Trigger. 1 = True0 = False
IsUniqueCnst Any UNIQUE constraint. 1 = True0 = False
IsUserTable Table User-defined table. 1 = True0 = False
IsView View View. 1 = True0 = False
OwnerId Any Owner of the object. Nonnull = The database user ID of the object owner.NULL = Invalid input.
TableDeleteTrigger Table Table has a DELETE trigger. >1 = ID of first trigger with given type.
TableDeleteTriggerCount Table The table has the specified number of DELETE triggers. >1 = ID of first trigger with given type.NULL = Invalid input.
TableFullTextBackground… Table The table has full-text background update index enabled. 1 = TRUE0 = FALSE
TableFulltextCatalogId Table The ID of the full-text catalog in which the full-text index data for the table resides. Nonzero = Full-text catalog ID, associated with the unique index that
identifies the rows in a full-text indexed table.0 = Table is not full-text indexed.
TableFullTextChangeTr… Table The table has full-text change-tracking enabled. 1 = TRUE0 = FALSE
TableFulltextKeyColumn Table The ID of the column associated with the single-column unique index that is participating in the full-text index definition. 0 = Table is not full-text indexed.
TableFullTextPopulate… Table 0 = No population1 = Full population2 = Incremental population
TableHasActiveFulltext… Tables The table has an active full-text index. 1 = True0 = False
TableHasCheckCnst Table The table has a CHECK constraint. 1 = True0 = False
TableHasClustIndex Table The table has a clustered index. 1 = True0 = False
TableHasDefaultCnst Table The table has a DEFAULT constraint. 1 = True0 = False
TableHasDeleteTrigger Table The table has a DELETE trigger. 1 = True0 = False
TableHasForeignKey Table The table has a FOREIGN KEY constraint. 1 = True0 = False
TableHasForeignRef Table Table is referenced by a FOREIGN KEY constraint. 1 = True0 = False
TableHasIdentity Table The table has an identity column. 1 = True0 = False
TableHasIndex Table The table has an index of any type. 1 = True0 = False
TableHasInsertTrigger Table The object has an Insert trigger. 1 = True0 = FalseNULL = Invalid input.
TableHasNonclustIndex Table The table has a nonclustered index. 1 = True0 = False
TableHasPrimaryKey Table The table has a primary key. 1 = True0 = False
TableHasRowGuidCol Table The table has a ROWGUIDCOL for a uniqueidentifier column. 1 = True0 = False
TableHasTextImage Table The table has a text column. 1 = True0 = False
TableHasTimestamp Table The table has a timestamp column. 1 = True0 = False
TableHasUniqueCnst Table The table has a UNIQUE constraint. 1 = True0 = False
TableHasUpdateTrigger Table The object has an Update trigger. 1 = True0 = False
TableInsertTrigger Table The table has an INSERT trigger. >1 = ID of first trigger with given type.
TableInsertTriggerCount Table The table has the specified number of INSERT triggers. >1 = ID of first trigger with given type.
TableIsFake Table The table is not real. It is materialized internally on demand by SQL Server. 1 = True0 = False
TableIsPinned Table The table is pinned to be held in the data cache. 1 = True0 = False
TableTextInRowLimit Table The maximum bytes allowed for text in row, or 0 if
text in row option is not set.
TableUpdateTrigger Table The table has an UPDATE trigger. >1 = ID of first trigger with given type.
TableUpdateTriggerCount Table The table has the specified number of UPDATE triggers. >1 = ID of first trigger with given type.

Nota: Tabela retirada do site MSDN

A propriedade IsIndexable pode consumir significantes recursos de processamento.
A propriedade TableHasActiveFulltextIndex retornará 1 (Verdadeiro) quando no mínimo uma coluna da tabela é adicionada com indíce.

Vamos aos exemplos:

A. Para descobrir se um determinado objeto (Veiculo) é uma VIEW, basta executar a seguinte instrução

IF OBJECTPROPERTY(OBJECT_ID(‘Veiculo’), ‘ISVIEW’) = 1
PRINT ‘Veiculo é uma VIEW’
ELSE
PRINT ‘Veiculo não é uma VIEW’

Observe que utilizei a função OBJECT_ID, esta função retorna a identificação do objeto passado como parâmetro, que deve ser o nome do objeto na base de dados. Foi utilizado esta função para não haver a necessidade de descobrir a identificação do objeto.

Caso a necessidade seja outra, como por exemplo, saber se o objeto é uma tabela, basta substituir a palavra-chave ISVIEW por ISTABLE. Como no exemplo abaixo:

IF OBJECTPROPERTY(OBJECT_ID(‘Veiculo’), ‘ISTABLE’) = 1
PRINT ‘Veiculo é uma TABLE’
ELSE
PRINT ‘Veiculo não é uma TABLE’

B. Saber se uma determinada tabela possui um campo do tipo TEXT, retornará 1 quando for verdadeiro e 0 quando for falso. Uma variável do tipo booleana.

SELECT OBJECTPROPERTY(OBJECT_ID(‘Cliente’), ‘TableHasTextImage’)

C. Saber se uma determinada tabela possui uma chave-primária

SELECT OBJECTPROPERTY(OBJECT_ID(‘Fornecedor’), ‘TableHasPrimaryKey’)

D. Saber se uma determinada tabela possui uma TRIGGER SQL que remove (DELETE) registros

SELECT OBJECTPROPERTY(OBJECT_ID(‘Cliente’), ‘TableDeleteTrigger’)

E. Descobrir qual o proprietário de um determinado objeto, Ex.: PROCEDURE, TRIGGER, TABLE, etc.

SELECT OBJECTPROPERTY(OBJECT_ID(‘Veiculo’), ‘OwnerId’)

Esta função retorna a identificação do proprietário do objeto na base de dados ou NULL caso passado o parâmetro incorretamente.

Finalizo este artigo por aqui, deixe seu comentário, críticas e/ou sugestões.

Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s

%d blogueiros gostam disto: