0

我在all_col_comments表中有表和对该表列的注释。如何代替我的表中的列名输出选择查询中 all_col_comments 中的列注释?

例子:

SELECT column1 AS 'comment for column1 from all_col_comments table'
     , column2 AS 'comment for column2 from all_col_comments table',
  FROM my_table;

问题 V2我想做什么

SQL> create table myTable(
  2    id           NUMBER(2),
  3    value        NUMBER(6,2)
  4  )
  5  /
Table created.

SQL>
SQL> -- prepare data
SQL> insert into myTable(ID,  value)values (1,9)
  2  /

1 row created.

SQL> insert into myTable(ID,  value)values (2,2.11)
  2  /

1 row created.

SQL>
SQL> select * from myTable
  2  /

        ID      VALUE
---------- ----------
         1          9
         2       2.11

2 rows selected.

SQL>
SQL> COMMENT ON COLUMN myTable.id IS
  2  'id stores the id';

Comment created.

SQL> COMMENT ON COLUMN myTable.value IS
  2  'value stores the some comment for value';

Comment created.

然后我需要做一些选择并得到这个

SQL>
SQL> select ??? ...

id stores the id      value stores the some comment for value
      ----------                                   ----------
               1                                            9
               2                                         2.11

    2 rows selected.
4

3 回答 3

2

如果没有动态 SQL,我认为没有任何方法可以满足您的要求。无法参数化列别名( 之后的位AS),因此您必须使用连接构建 SQL 字符串。

当您使用连接构建 SQL 字符串时,您需要考虑如何缓解 SQL 注入。(风险很低;如果您有权更改数据库表上的评论,那么您可能有足够的权限直接访问数据库,而无需构建适当的恶意列评论。)至少,您的 SQL 字符串需要用"字符包围列别名(不像'您的问题那样),并且在将列注释连接到 SQL 字符串之前,您必须验证注释不包含该"字符。

编辑:从您的评论看来,您正在使用 Perl 与数据库通信。以下是一个未经测试的草图,希望能展示一种构建 SQL 字符串的方法。我将由您来填补空白:

# The list of columns to select from the table.
# Must exactly match the names of columns returned from user_col_comments
my @columns = qw/COLUMN1 COLUMN2 COLUMN3 COLUMN4/;

# Are we adding the first column?
my $first = 1;

my $sql = 'SELECT ';

# Hash that maps column names to comments.
my %commenthash = ();

# TODO query user_col_comments and add to %commenthash the column names and comments.

for my $col (@columns) {

    my $comment = $commenthash{$col};

    unless (defined $comment) {
        # Use the column name if no comment was found.
        $comment = $col;
    }

    if ($comment =~ /"/) {
        die "can't use double-quotes in column comment: $comment";
    }

    # Add separating comma if this is not the first column.
    $sql .= ', ' if !$first;

    $sql .= qq!"$col" AS "$comment"!;

    $first = 0;
}

$sql .= ' FROM my_table';

# TODO execute SQL.

请注意,您需要查询数据库两次:一次获取列注释,一次获取实际数据。

于 2013-03-16T22:00:53.903 回答
0

您可以使用 user_col_comments 获取有关您的列的评论

SELECT *
FROM user_col_comments
WHERE table_name = 'MYTABLE';
于 2013-03-16T16:34:58.533 回答
-1

使用动态查询(未测试):

begin
 s := ' select ';
 for i in ( select column_name, column_comment from user_tables where table_name = 'MyTable' )
 loop
  s := i.column_name ||' AS ' ||'"'|| i.column_comment || '", '; 
 end loop;
s := s || ' from ' || 'MyTable';

dbms_output.put_line( 'SQL: ' || s ); -- SHOW
execute immediate ... -- execute
end;
/
于 2013-03-16T17:43:22.870 回答