在Oracle中,当我们读取系统表USER_TAB_COLS中的DATA_DEFAULT字段时,发现这个是Long类型的字段,也就是说不能读取了,因此我们需要进行转换,下面是这种方法的转换函数
CREATE OR REPLACE FUNCTION LONG_TO_CHAR(uTABLE IN VARCHAR2,uID IN NUMBER)
RETURN VARCHAR2
AS
uVal VARCHAR2(32767);
BEGIN
SELECT DATA_DEFAULT INTO uVal FROM USER_TAB_COLS WHERE TABLE_NAME = UPPER(uTABLE) AND COLUMN_ID = uID;
uVal := SUBSTR(uVal,1,50);
RETURN uVal;
END LONG_TO_CHAR;
接下来,我们可以使用下面的SQL语句读取表的结构了。首先创建一个测试表和数据
-- 删除表存储过程
CALL p_DropTable('App_TEST');
-- 创建序列号
CALL p_SetSequence('APP_TEST_KEY');
-- 创建测试表
Create Table App_TEST
(
fKEY NUMBER,
fName VARCHAR2(10) DEFAULT 'PAUL',
fCSRQ DATE DEFAULT TO_DATE('2018-01-01','YYYY-MM-DD'),
fPID VARCHAR2(10)
);
Alter Table App_TEST Add Constraint App_TESTKey Primary Key (fKEY) Using index;
-- 加表和字段的注释
CALL p_SetComment( 'App_TEST','测试表|关键字|姓名|出生日期|点位号' );
-- 插入实验数据
INSERT INTO App_TEST (fKEY,fCSRQ,fPID) VALUES (APP_TEST_KEY.NEXTVAL,TO_DATE('1962-12-18','YYYY-MM=DD'),'P001');
INSERT INTO App_TEST (fKEY,fName,fCSRQ,fPID) VALUES (APP_TEST_KEY.NEXTVAL,'SEPT',TO_DATE('1968-09-17','YYYY-MM=DD'),'P002');
INSERT INTO App_TEST (fKEY,fName,fPID) VALUES (APP_TEST_KEY.NEXTVAL,'WENGLEI','P003');
COMMIT;
SELECT * FROM App_TEST;
-------------------------------
FKEY FNAME fCSRQ FPID
-------------------------------
1 PAUL 1962-12-18 P001
2 SEPT 1968-09-17 P002
3 WENGLEI 2018-01-01 P003
-------------------------------
下面是Oracle的表结构查询语句,当然也可以使用DESC
SELECT
CASE WHEN M.COLUMN_ID = 1 THEN M.TABLE_NAME END TABLE_NAME
,CASE WHEN M.COLUMN_ID = 1 THEN TC.COMMENTS END COMMENTS
,M.COLUMN_ID ID
,M.COLUMN_NAME
,M.DATA_TYPE
,M.DATA_LENGTH LEN
,M.NULLABLE
,CC.COMMENTS
,LONG_TO_CHAR(M.TABLE_NAME,M.COLUMN_ID) DEFAULT_VAL
FROM
USER_TAB_COLS M
LEFT JOIN
USER_COL_COMMENTS CC
ON M.TABLE_NAME = CC.TABLE_NAME AND M.COLUMN_NAME = CC.column_name
LEFT JOIN
USER_TAB_COMMENTS TC
ON M.TABLE_NAME = TC.TABLE_NAME
WHERE M.TABLE_NAME = 'APP_TEST'
ORDER BY M.COLUMN_ID
-----------------------------------------------------------------------------------------------------------
TABLE_NAME COMMENTS ID COLUMN_NAME DATA_TYPE LEN NULLABLE COMMENTS DEFAULT_VAL
-----------------------------------------------------------------------------------------------------------
APP_TEST 测试表 1 FKEY NUMBER 22 N 关键字
2 FNAME VARCHAR2 10 Y 姓名 'PAUL'
3 FCSRQ DATE 7 Y 出生日期 TO_DATE('2018-01-01','YYYY-MM-DD')
4 FPID VARCHAR2 10 Y 点位号
-----------------------------------------------------------------------------------------------------------