Think Think .Net
Diego Nogare [MVP | MCT | MCITP | MCTS | MCP | INETA BR]

Como encontrar objetos do Database no SQL Server?

sábado, 15 maio 2010 05:36 by Nogare

Fala galera, essa semana, mais uma vez, precisei criar um script para uma documentação de sistema. Estamos montando algumas Matrizes de Rastreabilidade para um projeto no cliente e precisávamos saber todos os objetos que faziam parte de um determinado conjunto de tabelas. Como no código anterior (Como calcular a massa de dados no SQL Server?), a Engine que roda lá ainda é SQL Server 2000, e não temos muitas coisas que dê para fazer utilizando os recursos novos. O código original é pro SQL Server 2000 mas eu adaptei algumas poucas coisas rapidamente para o 2008. Essa execução abaixo é resultado do SQL Server 2008.

Neste caso, precisávamos encontrar todos os objetos que seriam documentados e, de acordo com a necessidade, migrado para a aplicação off-line que estamos atuando. Veja o código T-SQL e o resultado obtido.

O script é esse:

SET NOCOUNT ON

/* MOSTRAR TODAS TABELAS DO SCHEMA VENDAS [SALES] */
print('*********************************************************')
print('MOSTRAR TODAS TABELAS DO SCHEMA VENDAS [SALES]')

SELECT T.NAME 'TABELAS'
FROM sys.tables T
    INNER JOIN sys.schemas S
        ON T.schema_id = S.schema_id
WHERE S.name = 'Sales'
DECLARE @TABELA VARCHAR(50)
SET @TABELA = '%Store%'

/* RELACIONAMENTOS DE 1 NIVEL DA TABELA */
print('*********************************************************')
print('RELACIONAMENTOS DE 1 NIVEL DA TABELA')

SELECT PK.TABLE_NAME 'PAI',
       FK.TABLE_NAME 'FILHO'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
        ON C.CONSTRAINT_NAME = PK.CONSTRAINT_NAME
    INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
        ON C.UNIQUE_CONSTRAINT_NAME = FK.CONSTRAINT_NAME
WHERE FK.TABLE_NAME = REPLACE(@TABELA,'%','')
   OR PK.TABLE_NAME = REPLACE(@TABELA,'%','')

/* TODOS OS OBJETOS DA TABELA */
print('*********************************************************')
print('TODOS OS OBJETOS DA TABELA')

SELECT O.NAME 'NOME',
       REPLACE(O.type_desc,'_',' ') 'TIPO'
FROM SYS.OBJECTS O
    INNER JOIN SYSCOMMENTS C
        ON O.object_id = C.ID
WHERE C.TEXT LIKE @TABELA

/* TODAS AS CONSTRAINTS DA TABELA */
print('*********************************************************')
print('TODAS AS CONSTRAINTS DA TABELA')

SELECT O2.NAME 'TABELA',
       CL.NAME 'COLUNA',
       O.NAME 'CONSTRAINT',
       COM.TEXT 'CONDIÇÃO'
FROM SYSCONSTRAINTS C
    INNER JOIN SYSOBJECTS O
        ON O.ID = C.CONSTID
    INNER JOIN SYSOBJECTS O2
        ON O2.ID = C.ID
    INNER JOIN SYSCOLUMNS CL
        ON CL.ID = O2.ID
        AND CL.COLID = C.COLID
    INNER JOIN SYSCOMMENTS COM
        ON O.ID = COM.ID
WHERE O2.NAME LIKE REPLACE(@TABELA,'%','')
  AND O2.XTYPE = 'U'
ORDER BY O2.NAME, CL.NAME, O.NAME

SET NOCOUNT OFF

e o resultado apresentado é esse:

*********************************************************
MOSTRAR TODAS TABELAS DO SCHEMA VENDAS [SALES]
TABELAS
--------------------------------
Store
StoreContact
ContactCreditCard
CountryRegionCurrency
CreditCard
Currency
SalesOrderDetail
CurrencyRate
Customer
SalesOrderHeader
CustomerAddress
SalesOrderHeaderSalesReason
SalesPerson
SalesPersonQuotaHistory
SalesReason
Individual
SalesTaxRate
SalesTerritory
SalesTerritoryHistory
ShoppingCartItem
SpecialOffer
SpecialOfferProduct

*********************************************************
RELACIONAMENTOS DE 1 NIVEL DA TABELA
PAI               FILHO
----------------- ----------------
StoreContact      Store
Store             Customer
Store             SalesPerson

*********************************************************
TODOS OS OBJETOS DA TABELA
NOME                     TIPO
------------------------ ---------------------------
uspLogError              SQL STORED PROCEDURE
iuIndividual             SQL TRIGGER
iStore                   SQL TRIGGER
vStoreWithDemographics   VIEW
ufnGetContactInformation SQL TABLE VALUED FUNCTION

*********************************************************
TODAS AS CONSTRAINTS DA TABELA
TABELA  COLUNA         CONSTRAINT             CONDIÇÃO
------- -------------- ---------------------- -----------
Store   ModifiedDate   DF_Store_ModifiedDate  (getdate())
Store   rowguid        DF_Store_rowguid       (newid())

Mais uma vez gostaria de ver os comentários de vocês falando sobre como fariam pra chegar a essas informações.

Comentários

maio 15. 2010 06:11

pingback

Pingback from topsy.com

Twitter Trackbacks for
        
        Think Think .Net | Como encontrar objetos do Database no SQL Server?
        [diegonogare.net]
        on Topsy.com

topsy.com

maio 24. 2010 02:13

Tiago Salgado

Dá uma olhadela ao SQL Search da Redgate ;) http://oito.geracaohd.com/redgate-sql-search-2/

Tiago Salgado

agosto 5. 2010 03:31

Seattle Limo

Well said, you just earned another subscriber

Seattle Limo

agosto 6. 2010 01:15

Nude Chat

I dont know what to say.  This is definitely one of the better blogs Ive read.  Youre so insightful, have so much real stuff to bring to the table.  I hope that more people read this and get what I got from it:  chills.  Great job and great blog.  I cant wait to read more, keep em comin!

Nude Chat

agosto 6. 2010 23:04

Nude Cam

I have been checking out your posts for the last couple of hours, and everything has been very informative and well written.  I just wanted to tell you that for some reason this one doesn't seem to work in Internet Explorer.  On a side note, I was wondering if you wanted to swap blogroll links?  I hope to hear from you soon!

Nude Cam

agosto 9. 2010 01:15

Sex Cam

You're a very smart person!

Sex Cam

agosto 18. 2010 11:09

sex cam

adding this info to my blog if thats ok dude.

sex cam

agosto 20. 2010 03:22

vigrx

your site layout is very good

vigrx

Comentar


(Vai mostrar seu Gravatar)

  Country flag

biuquote
  • Comentário
  • Pré-visualização
Loading