使用sql语句查询表结构
虽然DESC 命令能查看表的结构,但有时希望将表的结构输入到一张表中去或导入到EXCEL。用DESC命令有点繁琐。其实一条SQL语句即可。
查询自己能看到的表的表结构:
SELECT T1.TABLE_NAME,
T1.COLUMN_NAME,
T1.DATA_TYPE || '(' || T1.DATA_LENGTH || ')',
T2.COMMENTS
FROM USER_TAB_COLS T1, USER_COL_COMMENTS T2
WHERE T1.TABLE_NAME = T2.TABLE_NAME
AND T1.COLUMN_NAME = T2.COLUMN_NAME
AND T1.TABLE_NAME = 'EMP';
如果是DBA则可能过ALL_ 和DBA_来查询所有的表结构。
SQL92的写法,但是不知道怎么加限制条件,好像用了USING就不可以了。当然可以去掉USING换成 ON
SELECT TABLE_NAME,
COLUMN_NAME,
T1.DATA_TYPE || '(' || T1.DATA_LENGTH || ')',
T2.COMMENTS
FROM USER_TAB_COLS T1 INNER JOIN USER_COL_COMMENTS T2
USING(table_name,COLUMN_name);
注意,如果有些字段没有注释,是不能显示的, 这样改:
SELECT t.table_name,
t.colUMN_NAME,
t.DATA_TYPE || '(' || t.DATA_LENGTH || ')',
t1.COMMENTS
FROM User_Tab_Cols t, User_Col_Comments t1
WHERE t.table_name = t1.table_name
AND t.column_name = t1.column_name(+);
加个外连接就行了。
以上是从网友那里拷贝过来的,同事写过一个供参考的,详细代码如下:
1 SELECT C.COMMENTS AS 中文表名, 2 A.TABLE_NAME AS 表名, 3 CASE WHEN A.INTERNAL_COLUMN_ID=1 THEN A.COLUMN_NAME ELSE ','||A.COLUMN_NAME END AS A字段名, 4 '--'|| A.INTERNAL_COLUMN_ID|| B.COMMENTS AS 字段中文名, 5 CASE WHEN A.INTERNAL_COLUMN_ID=1 THEN 6 CASE WHEN A.DATA_TYPE ='DATE' THEN 'T1.'||A.COLUMN_NAME ELSE 'TRIM(T1.'||A.COLUMN_NAME||') AS '||A.COLUMN_NAME END 7 ELSE 8 CASE WHEN A.DATA_TYPE='DATE' THEN ',T1.'||A.COLUMN_NAME 9 ELSE ',TRIM(T1.'||A.COLUMN_NAME||') AS '||A.COLUMN_NAME END 10 END, 11 A.INTERNAL_COLUMN_ID 12 FROM ALL_TAB_COLS A 13 LEFT JOIN ALL_COL_COMMENTS B 14 ON A.OWNER = B.OWNER 15 AND A.TABLE_NAME = B.TABLE_NAME 16 AND A.COLUMN_NAME = B.COLUMN_NAME 17 LEFT JOIN ALL_TAB_COMMENTS C 18 ON A.OWNER = C.OWNER 19 AND A.TABLE_NAME = C.TABLE_NAME 20 WHERE A.OWNER='ETL' --用户名称 21 AND A.TABLE_NAME='HIS_FXOPT_TR_PTB' 22 ORDER BY A.INTERNAL_COLUMN_ID 23