いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

SqlServerにてテーブルとカラムの説明を取得するSQL (sys.tables,sys.columns,sys.extended_properties)


普段はオラクルとMySQLを主に使っているので、SqlServerで上記の事をやるのに
どうやるのかなかなか分かりませんでした。(泣


SqlServerの場合、オラクルのようにALL_COL_COMMENTSみたいなビューで
一発で取得できるのかと思っていましたら実際には以下のテーブルをJOINして
取得するみたい。

  • sys.tables
  • sys.columns
  • sys.extended_properties


とりあえず、取得の方法は分かったので忘れない内にメモメモ。

 --
 -- SqlServerにてテーブルのコメントを取得するSQL
 --
select
     t.name    as TABLE_NAME
    ,ep.value  as COMMENT
from
     sys.tables              t
    ,sys.extended_properties ep
where
    t.name = 'TEST_TABLE'
    and
    t.object_id = ep.major_id
    and
    ep.minor_id = 0
;

 --
 -- SqlServerにてカラムのコメントを取得するSQL
 --
select
     t.name    as TABLE_NAME
    ,c.name    as COLUMN_NAME
    ,ep.value  as COMMENT
from
     sys.tables              t
    ,sys.columns             c
    ,sys.extended_properties ep
where
    t.name = 'TEST_TABLE'
    and
    t.object_id = c.object_id
    and    
    c.object_id = ep.major_id
    and
    c.column_id = ep.minor_id
;