Conocer la estructura de una BD SQL


–TABLAS y COLUMNAS

SELECT SO.NAME, SC.NAME
FROM sys.objects SO INNER JOIN sys.columns SC
ON SO.OBJECT_ID = SC.OBJECT_ID
WHERE SO.TYPE = ‘U’
ORDER BY SO.NAME, SC.NAME

–TABLAS
SELECT SO.NAME
FROM sys.objects SO
WHERE SO.TYPE = ‘U’
ORDER BY SO.NAME

–COLUMANS Y TIPO
SELECT COLUMN_NAME AS NombreCampo,DATA_TYPE as TIPO FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ‘Audit_Trails’

— FK
EXEC sp_fkeys ‘Clientes’

–FK por query
select distinct name from sys.objects where object_id in
( select fk.constraint_object_id from sys.foreign_key_columns as fk
where fk.referenced_object_id =
(select object_id from sys.tables where name = ‘Clientes’)
)

–TABLAS QUE TIENEN FK A UNA TABLA
select t.name as TableWithForeignKey, fk.constraint_column_id as FK_PartNo , c.name as ForeignKeyColumn
from sys.foreign_key_columns as fk
inner join sys.tables as t on fk.parent_object_id = t.object_id
inner join sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where fk.referenced_object_id = (select object_id from sys.tables where name = ‘Clientes’)
order by TableWithForeignKey, FK_PartNo

–PRIMARY KEY
SELECT column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), ‘IsPrimaryKey’) = 1
AND table_name = ‘Clientes’

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s