본문 바로가기

프로그래밍 관련

MS-SQL 에서 테이블 구조 정보 빼오기

MS-SQL에서 테이블 구조 살펴보다가 귀찮아서 한번 만들어 보았습니다....

단순하게 만들었는데.. 쓸만한지 모르겠네요.. ㅎㅎ

테이블명, 컬럼명(속성), PK정보, FK정보 등을 보여 줍니다.


select (select count(*)
    from sysobjects
         where xtype = 'U'
           and name != 'dtproperties'
           and name <= a.name)  테이블번호,
    a.name 테이블명,
    b.colid 컬럼번호,
    b.name 컬럼명, c.name 컬럼속성,
       case when b.xtype = 108 then CAST(b.xprec as varchar(100)) + ',' + CAST(b.xscale as varchar(100)) else CAST(b.length as varchar(100)) end 속성값,
       case when b.isnullable = 1 then 'Y' else '' end null여부,
    ISNULL((select CAST(keyno as varchar(2)) from dbo.sysindexkeys where id = d.id and indid = d.indid and colid = b.colid), '') PK순서,
       ISNULL((select name from dbo.sysobjects where id = f.rkeyid), '') 참조테이블,
       ISNULL((select name from dbo.syscolumns where id = f.rkeyid and colid = f.rkey), '') 참조컬럼,
       ISNULL(CAST(f.keyno as varchar(2)), '') 참조컬럼순서
  from dbo.sysobjects a,
       dbo.syscolumns b,
    dbo.systypes c,
    dbo.sysindexes d,
    dbo.sysforeignkeys f
 where a.id = b.id
   and a.xtype = 'U'
   and b.xtype = c.xtype
   and b.id *= d.id
   and d.name like 'PK%'
   and b.id *= f.fkeyid
   and b.colid *= f.fkey
   and a.name != 'dtproperties'
   and ((c.xtype = '231' and c.status = '2') or c.xtype != '231')
order by a.name, b.colorder