Preventing sqlplus truncation of column names, without individual column formatting

前端 未结 6 2308
感情败类
感情败类 2021-02-09 13:13

By default sqlplus truncates column names to the length of the underlying data type. Many of the column names in our database are prefixed by the table name, and therefore look

6条回答
  •  滥情空心
    2021-02-09 13:37

    I don't think sqlplus offers the functionality you are requesting. You might be able to automate the formatting, using some sort of scripting language such as Perl or Python. In other words, query the ALL_TAB_COLS view for the schema and table, and then create the script dynamically with a format column attribute. This will only work, of course, if you have permission to query the ALL_TAB_COLS view (or some other equivalent).

    This is a quick proof-of-concept I threw together:

    #!/usr/bin/python
    
    import sys
    import cx_Oracle
    
    response=raw_input("Enter schema.table_name:  ")
    (schema, table) = response.split('.')
    schema = schema.upper()
    table = table.upper()
    sqlstr = """select column_name,
                       data_type,
                       data_length
                  from all_tab_cols
                 where owner      = '%s'
                   and table_name = '%s'""" % ( schema, table )
    
    ## open a connection to databases...
    try:
        oracle = cx_Oracle.Connection( oracleLogin )
        oracle_cursor = oracle.cursor()
    
    except cx_Oracle.DatabaseError, exc:
        print "Cannot connect to Oracle database as", oracleLogin
        print "Oracle Error %d:  %s" % ( exc.args[0].code, exc.args[0].message )
        sys.exit(1)
    
    try:
        oracle_cursor.execute( sqlstr )
    
        # fetch resultset from cursor
        for column_name, data_type, data_length in oracle_cursor.fetchmany(256):
            data_length = data_length + 0
            if data_length < len(column_name):
                if data_type == "CHAR" or data_type == "VARCHAR2":
                    print "column %s format a%d" % ( column_name.upper(), len(column_name) )
                else:
                    print "-- Handle %s, %s, %d" % (column_name, data_type, data_length)
    
    except cx_Oracle.DatabaseError, e:
        print "[Oracle Error %d: %s]:  %s" % (e.args[0].code, e.args[0].message, sqlstr)
        sys.exit(1)
    
    try:
        oracle_cursor.close()
        oracle.close()
    except cx_Oracle.DatabaseError, exc:
        print "Warning: Oracle Error %d:  %s" % ( exc.args[0].code, exc.args[0].message )
    
    print "select *"
    print "from %s.%s" % ( schema, table )
    

提交回复
热议问题