在SQL查询中动态查找表的列名(Dynamically look up column names for a table while in an sql query)

系统教程 行业动态 更新时间:2024-06-14 17:04:03
在SQL查询中动态查找表的列名(Dynamically look up column names for a table while in an sql query)

我正在编写SQL(对于Oracle),如:

INSERT INTO Schema1.tableA SELECT * FROM Schema2.tableA;

Schema1.tableA和Schema2.tableA具有相同的列。 但是,这似乎是不安全的,因为在SELECT中返回的列的顺序是未定义的。 我应该做的是:

INSERT INTO Schema1.tableA (col1, col2, ... colN) SELECT (col1, col2, ... colN) FROM Schema2.tableA;

我正在使用一些脚本来处理大量表格,所以我想要做的事情就是写下如下内容:

INSERT INTO Schema1.tableA (foo(Schema1.tableA)) SELECT (foo(Schema1.tableA)) FROM Schema2.tableA;

foo是从表1中提取列名并将其打包为适当语法的一些漂亮魔术。 思考?

I'm writing SQL (for Oracle) like:

INSERT INTO Schema1.tableA SELECT * FROM Schema2.tableA;

where Schema1.tableA and Schema2.tableA have the same columns. However, it seems like this is unsafe, since the order of the columns coming back in the SELECT is undefined. What I should be doing is:

INSERT INTO Schema1.tableA (col1, col2, ... colN) SELECT (col1, col2, ... colN) FROM Schema2.tableA;

I'm doing this for lots of tables using some scripts, so what I'd like to do is write something like:

INSERT INTO Schema1.tableA (foo(Schema1.tableA)) SELECT (foo(Schema1.tableA)) FROM Schema2.tableA;

Where foo is some nifty magic that extracts the column names from table one and packages them in the appropriate syntax. Thoughts?

最满意答案

这个PL / SQL应该这样做:

declare l_cols long; l_sql long; begin for r in (select column_name from all_tab_columns where table_name = 'TABLEA' and owner = 'SCHEMA1' ) loop l_cols := l_cols || ',' || r.column_name; end loop; -- Remove leading comma l_cols := substr(l_cols, 2); l_sql := 'insert into schema1.tableA (' || l_cols || ') select ' || l_cols || ' from schema2.tableA'; execute immediate l_sql; end; /

This PL/SQL should do it:

declare l_cols long; l_sql long; begin for r in (select column_name from all_tab_columns where table_name = 'TABLEA' and owner = 'SCHEMA1' ) loop l_cols := l_cols || ',' || r.column_name; end loop; -- Remove leading comma l_cols := substr(l_cols, 2); l_sql := 'insert into schema1.tableA (' || l_cols || ') select ' || l_cols || ' from schema2.tableA'; execute immediate l_sql; end; /

更多推荐

本文发布于:2023-04-24 21:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/38eda841c0a7d1dfad1499921d621410.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:动态   column   Dynamically   SQL   sql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!