Bootstrap

《SQL经典实例》第五章 元数据查询

--5.1 列出模式中的所有表
    select table_name
    from information_schema.tables
    where table_schema = 'dbo

--5.2 列出表中的列
    select column_name, data_type, ordinal_position
    from information_schema.columns
    where table_schema = 'dbo'
    and table_name   = 'EMP'

--5.3 列出表的索引列
    select a.name table_name,
        b.name index_name,
        d.name column_name,
        c.index_column_id
   from sys.tables a,
        sys.indexes b,
        sys.index_columns c,
        sys.columns d
   where a.object_id = b.object_id
         and b.object_id = c.object_id
         and b.index_id  = c.index_id
         and c.object_id = d.object_id
         and c.column_id = d.column_id
         and a.name      = 'EMP'

--5.4 列出表的约束
     select a.table_name,
         a.constraint_name,
         b.column_name,
         a.constraint_type
     from information_schema.table_constraints a,
          information_schema.key_column_usage b
     where a.table_name      = 'EMP'
           and a.table_schema    = 'dbo'
           and a.table_name      = b.table_name
           and a.table_schema    = b.table_schema
           and a.constraint_name = b.constraint_name

--5.5 列出没有相应索引的外键
    SELECT
	fkeys.table_name,
	fkeys.constraint_name,
	fkeys.column_name,
	ind_cols.index_name 
FROM
	(
	SELECT
		a.object_id,
		d.column_id,
		a.NAME table_name,
		b.NAME constraint_name,
		d.NAME column_name 
	FROM
		sys.TABLES a
		JOIN sys.foreign_keys b ON ( a.NAME = 'EMP' AND a.object_id = b.parent_object_id )
		JOIN sys.foreign_key_columns c ON ( b.object_id = c.constraint_object_id )
		JOIN sys.COLUMNS d ON ( c.constraint_column_id = d.column_id AND a.object_id = d.object_id ) 
	) fkeys
	LEFT JOIN (
	SELECT
		a.NAME index_name,
		b.object_id,
		b.column_id 
	FROM
		sys.indexes a,
		sys.index_columns b 
	WHERE
		a.index_id = b.index_id 
	) ind_cols ON ( fkeys.object_id = ind_cols.object_id AND fkeys.column_id = ind_cols.column_id ) 
WHERE
	ind_cols.index_name IS NULL

--

;